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/EmeraldEconomy/src/net/illusiononline/EmeraldEconomy/PlayerListener.java b/EmeraldEconomy/src/net/illusiononline/EmeraldEconomy/PlayerListener.java index efe6dd5..ebd8bf9 100644 --- a/EmeraldEconomy/src/net/illusiononline/EmeraldEconomy/PlayerListener.java +++ b/EmeraldEconomy/src/net/illusiononline/EmeraldEconomy/PlayerListener.java @@ -1,36 +1,36 @@ package net.illusiononline.EmeraldEconomy; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class PlayerListener implements Listener{ Logger log = Logger.getLogger("Minecraft"); public PlayerListener(EmeraldEconomy plugin){ plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler (priority = EventPriority.MONITOR) public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (player == null) return; Integer money = EmeraldEconomy.getSQLManager().getBalance(player.getName()); if (money == null) { - Boolean _w = EmeraldEconomy.getSQLManager().newUnit(player.getName(), false); + Boolean _w = EmeraldEconomy.getSQLManager().newUnit(player.getName()); if (_w) log.info("Creating new Economy Unit for Player: "+player.getName()); else { log.info("Failed to create Economy Unit for Player: "+player.getName()); player.sendMessage(ChatColor.RED+"Economy Unit Creation Failed: Please Relogg!"); } } else player.sendMessage(ChatColor.AQUA+"<------------>\n"+player.getName()+"'s Balance: "+(money)+"\n<------------>"); } }
true
true
public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (player == null) return; Integer money = EmeraldEconomy.getSQLManager().getBalance(player.getName()); if (money == null) { Boolean _w = EmeraldEconomy.getSQLManager().newUnit(player.getName(), false); if (_w) log.info("Creating new Economy Unit for Player: "+player.getName()); else { log.info("Failed to create Economy Unit for Player: "+player.getName()); player.sendMessage(ChatColor.RED+"Economy Unit Creation Failed: Please Relogg!"); } } else player.sendMessage(ChatColor.AQUA+"<------------>\n"+player.getName()+"'s Balance: "+(money)+"\n<------------>"); }
public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (player == null) return; Integer money = EmeraldEconomy.getSQLManager().getBalance(player.getName()); if (money == null) { Boolean _w = EmeraldEconomy.getSQLManager().newUnit(player.getName()); if (_w) log.info("Creating new Economy Unit for Player: "+player.getName()); else { log.info("Failed to create Economy Unit for Player: "+player.getName()); player.sendMessage(ChatColor.RED+"Economy Unit Creation Failed: Please Relogg!"); } } else player.sendMessage(ChatColor.AQUA+"<------------>\n"+player.getName()+"'s Balance: "+(money)+"\n<------------>"); }
diff --git a/src/Main.java b/src/Main.java index c012ddd..66cfd19 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,199 +1,196 @@ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Stack; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = null; String filepath; int count = 0; //counter int option; //Specifies the option that the user selects from the menu String x; //general purpose variable for user input/loading String classType; Stack<Team> teams = new Stack<Team>(); Stack<Player> players; Stack<Coach> coaches; boolean menuRunning; - int error = 0; menuRunning = true; do { //resets players and coaches players = new Stack<Player>(); coaches = new Stack<Coach>(); System.out.println("Step 1: Enter team information"); System.out.println("1 - Manually enter Team"); System.out.println("2 - Load Team from text file"); System.out.println("3 - Continue"); //continues to next step once more than 1 team is loaded System.out.println("Select an option: "); option = in.nextInt(); if (option == 1) { boolean continuePrompt; int type; //Prompts for team stats System.out.println("Step 1: Team Information"); teams.push(new Team()); //Prompts for player stats System.out.println("Step 2: Player Information"); do { do { System.out.println("1 - Forward"); System.out.println("2 - Defense"); System.out.println("3 - Goalie"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>3); if (type == 1) players.push(new Forward()); else if (type == 2) players.push(new Defense()); else players.push(new Goalie()); System.out.println("Add another player? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //prompts for coach stats System.out.println("Step 3: Coach Information"); do { do { System.out.println("1 - Head"); System.out.println("2 - Assistant"); System.out.println("3 - Goaltender"); System.out.println("4 - Trainer"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>4); if (type == 1) coaches.push(new head()); else if (type == 2) coaches.push(new assistant()); else if (type == 3) coaches.push(new goaltender()); else coaches.push(new trainer()); System.out.println("Add another coach? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 2) { //loads from team from text file boolean fileFound; in = new Scanner(System.in); //or else catch behaves weirdly do { System.out.println("Enter location of the text file you want to load from: "); filepath = in.nextLine(); try { br = new BufferedReader(new FileReader(filepath)); fileFound = true; } catch (FileNotFoundException e) { fileFound = false; System.out.println("File not found."); } } while (fileFound == false); teams.push(new Team(br)); - in.close(); //loads players from text file br.readLine(); //skips empty line do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); - error++; - System.out.println(error); if (classType.equals("forward")) players.push(new Forward(br)); else if (classType.equals("defense")) { players.push(new Defense(br)); } else players.push(new Goalie(br)); br.readLine();//skips the space between each player br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //reads next object classType = x.substring(x.indexOf(": ")+2,x.length()); br.reset();//moves cursor back to where stream was marked } while (classType.equals("forward")||classType.equals("defense")||classType.equals("goalie")); teams.get(count).putplayersize(players.size()); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //loads coaches from text file do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("head")) coaches.push(new head(br)); else if (classType.equals("assistant")) coaches.push(new assistant(br)); else if (classType.equals("goaltender")) coaches.push(new goaltender(br)); else coaches.push(new trainer(br)); x = br.readLine();//skips the space between each coach br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later - x = x.substring(x.indexOf(": ")+2,x.length()); //checks if next line in the text file is end of file or not ERROR ERROR ERROR + x = br.readLine(); //checks if next line in the text file is end of file or not br.reset(); } while (x != null); - coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into player array + teams.get(count).putcoachingstaffsize(coaches.size()); + coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 3) {//to avoid printing invalid if (count<1) System.out.println("Error - Information is required for at least 1 team."); else menuRunning = false; } else System.out.println("Invalid option."); } while (menuRunning); System.out.println("Enter location to save text file: "); filepath = in.next(); PrintWriter pw = new PrintWriter(new FileWriter(filepath)); System.out.println("League: NHL\n"); for (int i = 0; i<teams.size();i++) { teams.get(i).save(pw); teams.get(i).writePlayer(pw); teams.get(i).writeCoach(pw); pw.println(""); //skips an additional line between each team } in.close(); br.close(); pw.close(); } }
false
true
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = null; String filepath; int count = 0; //counter int option; //Specifies the option that the user selects from the menu String x; //general purpose variable for user input/loading String classType; Stack<Team> teams = new Stack<Team>(); Stack<Player> players; Stack<Coach> coaches; boolean menuRunning; int error = 0; menuRunning = true; do { //resets players and coaches players = new Stack<Player>(); coaches = new Stack<Coach>(); System.out.println("Step 1: Enter team information"); System.out.println("1 - Manually enter Team"); System.out.println("2 - Load Team from text file"); System.out.println("3 - Continue"); //continues to next step once more than 1 team is loaded System.out.println("Select an option: "); option = in.nextInt(); if (option == 1) { boolean continuePrompt; int type; //Prompts for team stats System.out.println("Step 1: Team Information"); teams.push(new Team()); //Prompts for player stats System.out.println("Step 2: Player Information"); do { do { System.out.println("1 - Forward"); System.out.println("2 - Defense"); System.out.println("3 - Goalie"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>3); if (type == 1) players.push(new Forward()); else if (type == 2) players.push(new Defense()); else players.push(new Goalie()); System.out.println("Add another player? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //prompts for coach stats System.out.println("Step 3: Coach Information"); do { do { System.out.println("1 - Head"); System.out.println("2 - Assistant"); System.out.println("3 - Goaltender"); System.out.println("4 - Trainer"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>4); if (type == 1) coaches.push(new head()); else if (type == 2) coaches.push(new assistant()); else if (type == 3) coaches.push(new goaltender()); else coaches.push(new trainer()); System.out.println("Add another coach? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 2) { //loads from team from text file boolean fileFound; in = new Scanner(System.in); //or else catch behaves weirdly do { System.out.println("Enter location of the text file you want to load from: "); filepath = in.nextLine(); try { br = new BufferedReader(new FileReader(filepath)); fileFound = true; } catch (FileNotFoundException e) { fileFound = false; System.out.println("File not found."); } } while (fileFound == false); teams.push(new Team(br)); in.close(); //loads players from text file br.readLine(); //skips empty line do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); error++; System.out.println(error); if (classType.equals("forward")) players.push(new Forward(br)); else if (classType.equals("defense")) { players.push(new Defense(br)); } else players.push(new Goalie(br)); br.readLine();//skips the space between each player br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //reads next object classType = x.substring(x.indexOf(": ")+2,x.length()); br.reset();//moves cursor back to where stream was marked } while (classType.equals("forward")||classType.equals("defense")||classType.equals("goalie")); teams.get(count).putplayersize(players.size()); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //loads coaches from text file do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("head")) coaches.push(new head(br)); else if (classType.equals("assistant")) coaches.push(new assistant(br)); else if (classType.equals("goaltender")) coaches.push(new goaltender(br)); else coaches.push(new trainer(br)); x = br.readLine();//skips the space between each coach br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = x.substring(x.indexOf(": ")+2,x.length()); //checks if next line in the text file is end of file or not ERROR ERROR ERROR br.reset(); } while (x != null); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into player array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 3) {//to avoid printing invalid if (count<1) System.out.println("Error - Information is required for at least 1 team."); else menuRunning = false; } else System.out.println("Invalid option."); } while (menuRunning); System.out.println("Enter location to save text file: "); filepath = in.next(); PrintWriter pw = new PrintWriter(new FileWriter(filepath)); System.out.println("League: NHL\n"); for (int i = 0; i<teams.size();i++) { teams.get(i).save(pw); teams.get(i).writePlayer(pw); teams.get(i).writeCoach(pw); pw.println(""); //skips an additional line between each team } in.close(); br.close(); pw.close(); }
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); BufferedReader br = null; String filepath; int count = 0; //counter int option; //Specifies the option that the user selects from the menu String x; //general purpose variable for user input/loading String classType; Stack<Team> teams = new Stack<Team>(); Stack<Player> players; Stack<Coach> coaches; boolean menuRunning; menuRunning = true; do { //resets players and coaches players = new Stack<Player>(); coaches = new Stack<Coach>(); System.out.println("Step 1: Enter team information"); System.out.println("1 - Manually enter Team"); System.out.println("2 - Load Team from text file"); System.out.println("3 - Continue"); //continues to next step once more than 1 team is loaded System.out.println("Select an option: "); option = in.nextInt(); if (option == 1) { boolean continuePrompt; int type; //Prompts for team stats System.out.println("Step 1: Team Information"); teams.push(new Team()); //Prompts for player stats System.out.println("Step 2: Player Information"); do { do { System.out.println("1 - Forward"); System.out.println("2 - Defense"); System.out.println("3 - Goalie"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>3); if (type == 1) players.push(new Forward()); else if (type == 2) players.push(new Defense()); else players.push(new Goalie()); System.out.println("Add another player? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //prompts for coach stats System.out.println("Step 3: Coach Information"); do { do { System.out.println("1 - Head"); System.out.println("2 - Assistant"); System.out.println("3 - Goaltender"); System.out.println("4 - Trainer"); System.out.println("Select player type: "); type = in.nextInt(); } while (type<1||type>4); if (type == 1) coaches.push(new head()); else if (type == 2) coaches.push(new assistant()); else if (type == 3) coaches.push(new goaltender()); else coaches.push(new trainer()); System.out.println("Add another coach? (Y/N"); x = in.next(); if (x.equalsIgnoreCase("Y")) continuePrompt = true; else continuePrompt = false; } while (continuePrompt); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 2) { //loads from team from text file boolean fileFound; in = new Scanner(System.in); //or else catch behaves weirdly do { System.out.println("Enter location of the text file you want to load from: "); filepath = in.nextLine(); try { br = new BufferedReader(new FileReader(filepath)); fileFound = true; } catch (FileNotFoundException e) { fileFound = false; System.out.println("File not found."); } } while (fileFound == false); teams.push(new Team(br)); //loads players from text file br.readLine(); //skips empty line do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("forward")) players.push(new Forward(br)); else if (classType.equals("defense")) { players.push(new Defense(br)); } else players.push(new Goalie(br)); br.readLine();//skips the space between each player br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //reads next object classType = x.substring(x.indexOf(": ")+2,x.length()); br.reset();//moves cursor back to where stream was marked } while (classType.equals("forward")||classType.equals("defense")||classType.equals("goalie")); teams.get(count).putplayersize(players.size()); players.copyInto(teams.get(count).getPlayers()); //copies stack into player array //loads coaches from text file do { x = br.readLine(); classType = x.substring(x.indexOf(": ")+2,x.length()); if (classType.equals("head")) coaches.push(new head(br)); else if (classType.equals("assistant")) coaches.push(new assistant(br)); else if (classType.equals("goaltender")) coaches.push(new goaltender(br)); else coaches.push(new trainer(br)); x = br.readLine();//skips the space between each coach br.mark(1000); //stores this location in the memory so program can revisit this part of the stream later x = br.readLine(); //checks if next line in the text file is end of file or not br.reset(); } while (x != null); teams.get(count).putcoachingstaffsize(coaches.size()); coaches.copyInto(teams.get(count).getCoachingstaff()); //copies stack into coach array teams.get(count).updateconf(); teams.get(count).updatediv(); count++; } else if (option == 3) {//to avoid printing invalid if (count<1) System.out.println("Error - Information is required for at least 1 team."); else menuRunning = false; } else System.out.println("Invalid option."); } while (menuRunning); System.out.println("Enter location to save text file: "); filepath = in.next(); PrintWriter pw = new PrintWriter(new FileWriter(filepath)); System.out.println("League: NHL\n"); for (int i = 0; i<teams.size();i++) { teams.get(i).save(pw); teams.get(i).writePlayer(pw); teams.get(i).writeCoach(pw); pw.println(""); //skips an additional line between each team } in.close(); br.close(); pw.close(); }
diff --git a/android/src/org/coolreader/crengine/BaseListView.java b/android/src/org/coolreader/crengine/BaseListView.java index 859ebbde..8478457e 100644 --- a/android/src/org/coolreader/crengine/BaseListView.java +++ b/android/src/org/coolreader/crengine/BaseListView.java @@ -1,59 +1,59 @@ package org.coolreader.crengine; import android.content.Context; import android.graphics.Rect; import android.view.KeyEvent; import android.view.View; import android.widget.ListView; public class BaseListView extends ListView { public BaseListView(Context context) { super(context); setFocusable(true); setFocusableInTouchMode(true); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { int dir = 0; if (keyCode == 0) keyCode = event.getScanCode(); if (DeviceInfo.SONY_NAVIGATION_KEYS) { if (keyCode == ReaderView.SONY_DPAD_RIGHT_SCANCODE || keyCode == ReaderView.SONY_DPAD_DOWN_SCANCODE || keyCode==KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) dir = 1; else if (keyCode == ReaderView.SONY_DPAD_LEFT_SCANCODE || keyCode == ReaderView.SONY_DPAD_UP_SCANCODE || keyCode==KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT ) dir = -1; } else { if (keyCode == ReaderView.NOOK_KEY_NEXT_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == ReaderView.NOOK_KEY_SHIFT_DOWN) dir = 1; if (keyCode == ReaderView.NOOK_KEY_PREV_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == ReaderView.NOOK_KEY_SHIFT_UP) dir = -1; } if (dir != 0) { int firstPos = getFirstVisiblePosition(); int lastPos = getLastVisiblePosition(); int count = getCount(); int delta = 1; if( dir < 0 ) { View v = getChildAt(0); if( v != null ) { int fh = v.getHeight(); Rect r = new Rect(0,0,v.getWidth(),fh); getChildVisibleRect(v, r, null); delta = (r.height() < fh) ? 1 : 0; } } - int nextPos = ( dir > 0 ) ? Math.min(lastPos, count - 1) : Math.max(0, firstPos - (lastPos - firstPos) + delta); + int nextPos = ( dir > 0 ) ? Math.min(lastPos + 1, count - 1) : Math.max(0, firstPos - (lastPos - firstPos) + delta); // Log.w("CoolReader", "first =" + firstPos + " last = " + lastPos + " next = " + nextPos + " count = " + count); setSelection(nextPos); clearFocus(); return true; } return super.onKeyDown(keyCode, event); } }
true
true
public boolean onKeyDown(int keyCode, KeyEvent event) { int dir = 0; if (keyCode == 0) keyCode = event.getScanCode(); if (DeviceInfo.SONY_NAVIGATION_KEYS) { if (keyCode == ReaderView.SONY_DPAD_RIGHT_SCANCODE || keyCode == ReaderView.SONY_DPAD_DOWN_SCANCODE || keyCode==KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) dir = 1; else if (keyCode == ReaderView.SONY_DPAD_LEFT_SCANCODE || keyCode == ReaderView.SONY_DPAD_UP_SCANCODE || keyCode==KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT ) dir = -1; } else { if (keyCode == ReaderView.NOOK_KEY_NEXT_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == ReaderView.NOOK_KEY_SHIFT_DOWN) dir = 1; if (keyCode == ReaderView.NOOK_KEY_PREV_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == ReaderView.NOOK_KEY_SHIFT_UP) dir = -1; } if (dir != 0) { int firstPos = getFirstVisiblePosition(); int lastPos = getLastVisiblePosition(); int count = getCount(); int delta = 1; if( dir < 0 ) { View v = getChildAt(0); if( v != null ) { int fh = v.getHeight(); Rect r = new Rect(0,0,v.getWidth(),fh); getChildVisibleRect(v, r, null); delta = (r.height() < fh) ? 1 : 0; } } int nextPos = ( dir > 0 ) ? Math.min(lastPos, count - 1) : Math.max(0, firstPos - (lastPos - firstPos) + delta); // Log.w("CoolReader", "first =" + firstPos + " last = " + lastPos + " next = " + nextPos + " count = " + count); setSelection(nextPos); clearFocus(); return true; } return super.onKeyDown(keyCode, event); }
public boolean onKeyDown(int keyCode, KeyEvent event) { int dir = 0; if (keyCode == 0) keyCode = event.getScanCode(); if (DeviceInfo.SONY_NAVIGATION_KEYS) { if (keyCode == ReaderView.SONY_DPAD_RIGHT_SCANCODE || keyCode == ReaderView.SONY_DPAD_DOWN_SCANCODE || keyCode==KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) dir = 1; else if (keyCode == ReaderView.SONY_DPAD_LEFT_SCANCODE || keyCode == ReaderView.SONY_DPAD_UP_SCANCODE || keyCode==KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT ) dir = -1; } else { if (keyCode == ReaderView.NOOK_KEY_NEXT_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == ReaderView.NOOK_KEY_SHIFT_DOWN) dir = 1; if (keyCode == ReaderView.NOOK_KEY_PREV_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == ReaderView.NOOK_KEY_SHIFT_UP) dir = -1; } if (dir != 0) { int firstPos = getFirstVisiblePosition(); int lastPos = getLastVisiblePosition(); int count = getCount(); int delta = 1; if( dir < 0 ) { View v = getChildAt(0); if( v != null ) { int fh = v.getHeight(); Rect r = new Rect(0,0,v.getWidth(),fh); getChildVisibleRect(v, r, null); delta = (r.height() < fh) ? 1 : 0; } } int nextPos = ( dir > 0 ) ? Math.min(lastPos + 1, count - 1) : Math.max(0, firstPos - (lastPos - firstPos) + delta); // Log.w("CoolReader", "first =" + firstPos + " last = " + lastPos + " next = " + nextPos + " count = " + count); setSelection(nextPos); clearFocus(); return true; } return super.onKeyDown(keyCode, event); }
diff --git a/source/core/src/test/java/org/marketcetera/core/HttpDatabaseIDFactoryTest.java b/source/core/src/test/java/org/marketcetera/core/HttpDatabaseIDFactoryTest.java index ca476b33d..bf619252c 100644 --- a/source/core/src/test/java/org/marketcetera/core/HttpDatabaseIDFactoryTest.java +++ b/source/core/src/test/java/org/marketcetera/core/HttpDatabaseIDFactoryTest.java @@ -1,80 +1,80 @@ package org.marketcetera.core; import junit.framework.Test; import junit.framework.TestCase; import java.net.URL; import java.net.InetAddress; import java.io.File; /** * @author toli * @version $Id$ */ @ClassVersion("$Id$") public class HttpDatabaseIDFactoryTest extends TestCase { public HttpDatabaseIDFactoryTest(String inName) { super(inName); } public static Test suite() { return new MarketceteraTestSuite(HttpDatabaseIDFactoryTest.class); } public void testFactory_existingURL() throws Exception { URL url= new File("src/test/resources/next_id_batch.xml").toURL(); HttpDatabaseIDFactory factory = new HttpDatabaseIDFactory(url); factory.grabIDs(); assertEquals("1", factory.getNext()); for(int i=2;i<100; i++) { assertEquals("comparing for " +i, ""+i, factory.getNext()); } } public void testFactory_existingURL_withPrefix() throws Exception { URL url= new File("src/test/resources/next_id_batch.xml").toURL(); HttpDatabaseIDFactory factory = new HttpDatabaseIDFactory(url, "prefix"); factory.grabIDs(); assertEquals("prefix1", factory.getNext()); for(int i=2;i<100; i++) { assertEquals("comparing for " +i, "prefix"+i, factory.getNext()); } } /** Verify that when a DB is inaccessible we still get an in-memory set of ids */ public void testInvalidURL() throws Exception { URL url = new URL("http://www.bogus.example.com/no/such/url"); final HttpDatabaseIDFactory factory = new HttpDatabaseIDFactory(url); - new ExpectedTestFailure(NoMoreIDsException.class, "bogus.example") { + new ExpectedTestFailure(NoMoreIDsException.class) { protected void execute() throws Throwable { factory.grabIDs(); } }.run(); assertFalse("1".equals(factory.getNext())); assertTrue("id is "+factory.getNext(), factory.getNext().contains(InetAddress.getLocalHost().toString())); // now verify subsequent are different String prev = factory.getNext(); for(int i=0;i<20; i++) { String cur = factory.getNext(); assertFalse("previous id equals to next id", prev.equals(cur)); prev = cur; } } public void testUnconnectableURL() throws Exception { URL url = new URL("http://localhost:3456/no/such/url"); final HttpDatabaseIDFactory factory = new HttpDatabaseIDFactory(url); new ExpectedTestFailure(NoMoreIDsException.class) { protected void execute() throws Throwable { factory.grabIDs(); } }.run(); assertNotNull(factory.getNext()); } }
true
true
public void testInvalidURL() throws Exception { URL url = new URL("http://www.bogus.example.com/no/such/url"); final HttpDatabaseIDFactory factory = new HttpDatabaseIDFactory(url); new ExpectedTestFailure(NoMoreIDsException.class, "bogus.example") { protected void execute() throws Throwable { factory.grabIDs(); } }.run(); assertFalse("1".equals(factory.getNext())); assertTrue("id is "+factory.getNext(), factory.getNext().contains(InetAddress.getLocalHost().toString())); // now verify subsequent are different String prev = factory.getNext(); for(int i=0;i<20; i++) { String cur = factory.getNext(); assertFalse("previous id equals to next id", prev.equals(cur)); prev = cur; } }
public void testInvalidURL() throws Exception { URL url = new URL("http://www.bogus.example.com/no/such/url"); final HttpDatabaseIDFactory factory = new HttpDatabaseIDFactory(url); new ExpectedTestFailure(NoMoreIDsException.class) { protected void execute() throws Throwable { factory.grabIDs(); } }.run(); assertFalse("1".equals(factory.getNext())); assertTrue("id is "+factory.getNext(), factory.getNext().contains(InetAddress.getLocalHost().toString())); // now verify subsequent are different String prev = factory.getNext(); for(int i=0;i<20; i++) { String cur = factory.getNext(); assertFalse("previous id equals to next id", prev.equals(cur)); prev = cur; } }
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/security/GroupMembers.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/security/GroupMembers.java index e3c5c258a..c5318fb62 100644 --- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/security/GroupMembers.java +++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/security/GroupMembers.java @@ -1,124 +1,119 @@ package net.cyklotron.cms.modules.views.security; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jcontainer.dna.Logger; import org.objectledge.ComponentInitializationError; import org.objectledge.authentication.DefaultPrincipal; import org.objectledge.authentication.UserManager; import org.objectledge.context.Context; import org.objectledge.coral.security.RoleAssignment; import org.objectledge.coral.security.Subject; import org.objectledge.coral.session.CoralSession; import org.objectledge.i18n.I18nContext; import org.objectledge.parameters.Parameters; import org.objectledge.parameters.directory.DirectoryParameters; import org.objectledge.pipeline.ProcessingException; import org.objectledge.table.TableColumn; import org.objectledge.table.TableException; import org.objectledge.table.TableModel; import org.objectledge.table.TableState; import org.objectledge.table.TableStateManager; import org.objectledge.table.TableTool; import org.objectledge.table.comparator.MapComparator; import org.objectledge.table.generic.ListTableModel; import org.objectledge.templating.TemplatingContext; import org.objectledge.web.HttpContext; import org.objectledge.web.mvc.MVCContext; import net.cyklotron.cms.CmsDataFactory; import net.cyklotron.cms.preferences.PreferencesService; import net.cyklotron.cms.security.RoleResource; import net.cyklotron.cms.security.RoleResourceImpl; import net.cyklotron.cms.security.SecurityService; public class GroupMembers extends BaseSecurityScreen { protected UserManager userManager; protected TableColumn[] columns; public GroupMembers(Context context, Logger logger, PreferencesService preferencesService, CmsDataFactory cmsDataFactory, TableStateManager tableStateManager, SecurityService securityService, UserManager userManager) { super(context, logger, preferencesService, cmsDataFactory, tableStateManager, securityService); this.userManager = userManager; try { columns = new TableColumn[4]; columns[0] = new TableColumn<Map<String, Long>>("id", null); columns[1] = new TableColumn<Map<String, String>>("login", new MapComparator<String, String>("login")); columns[2] = new TableColumn<Map<String, String>>("name", new MapComparator<String, String>("name")); columns[3] = new TableColumn<Map<String, Date>>("member_since", new MapComparator<String, Date>("member_since")); } catch(TableException e) { throw new ComponentInitializationError("failed to initialize table columns", e); } } @Override public void process(Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, I18nContext i18nContext, CoralSession coralSession) throws ProcessingException { try { long groupId = parameters.getLong("group_id"); RoleResource group = RoleResourceImpl.getRoleResource(coralSession, groupId); - Subject[] subjects = group.getRole().getSubjects(); + RoleAssignment[] assignments = group.getRole().getRoleAssignments(); List<Map<String, Object>> memberList = new ArrayList<Map<String, Object>>( - subjects.length); - for (Subject subject : subjects) + assignments.length); + for (RoleAssignment assignment : assignments) { + Subject subject = assignment.getSubject(); Parameters personalData = new DirectoryParameters(userManager .getPersonalData(new DefaultPrincipal(subject.getName()))); Map<String, Object> memberDesc = new HashMap<String, Object>(); memberDesc.put("id", subject.getIdObject()); memberDesc.put("login", userManager.getLogin(subject.getName())); memberDesc.put("name", personalData.get("cn", "")); - for (RoleAssignment ra : subject.getRoleAssignments()) - { - if(ra.getRole().equals(group.getRole())) - { - memberDesc.put("member_since", ra.getGrantTime().getTime()); - } - } + memberDesc.put("member_since", assignment.getGrantTime().getTime()); memberList.add(memberDesc); } TableState state = tableStateManager.getState(context, "view:security,GroupMemberList"); if(state.isNew()) { state.setTreeView(false); state.setPageSize(10); } TableModel<Map<String, Object>> model = new ListTableModel<Map<String, Object>>( memberList, columns); templatingContext.put("table", new TableTool<Map<String, Object>>(state, null, model)); templatingContext.put("group", group); if(cmsSecurityService.isGroupResource(group)) { templatingContext.put("groupName", cmsSecurityService.getShortGroupName(group)); } } catch(Exception e) { if(e instanceof ProcessingException) { throw (ProcessingException)e; } throw new ProcessingException("failed to retreive data", e); } } }
false
true
public void process(Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, I18nContext i18nContext, CoralSession coralSession) throws ProcessingException { try { long groupId = parameters.getLong("group_id"); RoleResource group = RoleResourceImpl.getRoleResource(coralSession, groupId); Subject[] subjects = group.getRole().getSubjects(); List<Map<String, Object>> memberList = new ArrayList<Map<String, Object>>( subjects.length); for (Subject subject : subjects) { Parameters personalData = new DirectoryParameters(userManager .getPersonalData(new DefaultPrincipal(subject.getName()))); Map<String, Object> memberDesc = new HashMap<String, Object>(); memberDesc.put("id", subject.getIdObject()); memberDesc.put("login", userManager.getLogin(subject.getName())); memberDesc.put("name", personalData.get("cn", "")); for (RoleAssignment ra : subject.getRoleAssignments()) { if(ra.getRole().equals(group.getRole())) { memberDesc.put("member_since", ra.getGrantTime().getTime()); } } memberList.add(memberDesc); } TableState state = tableStateManager.getState(context, "view:security,GroupMemberList"); if(state.isNew()) { state.setTreeView(false); state.setPageSize(10); } TableModel<Map<String, Object>> model = new ListTableModel<Map<String, Object>>( memberList, columns); templatingContext.put("table", new TableTool<Map<String, Object>>(state, null, model)); templatingContext.put("group", group); if(cmsSecurityService.isGroupResource(group)) { templatingContext.put("groupName", cmsSecurityService.getShortGroupName(group)); } } catch(Exception e) { if(e instanceof ProcessingException) { throw (ProcessingException)e; } throw new ProcessingException("failed to retreive data", e); } }
public void process(Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, I18nContext i18nContext, CoralSession coralSession) throws ProcessingException { try { long groupId = parameters.getLong("group_id"); RoleResource group = RoleResourceImpl.getRoleResource(coralSession, groupId); RoleAssignment[] assignments = group.getRole().getRoleAssignments(); List<Map<String, Object>> memberList = new ArrayList<Map<String, Object>>( assignments.length); for (RoleAssignment assignment : assignments) { Subject subject = assignment.getSubject(); Parameters personalData = new DirectoryParameters(userManager .getPersonalData(new DefaultPrincipal(subject.getName()))); Map<String, Object> memberDesc = new HashMap<String, Object>(); memberDesc.put("id", subject.getIdObject()); memberDesc.put("login", userManager.getLogin(subject.getName())); memberDesc.put("name", personalData.get("cn", "")); memberDesc.put("member_since", assignment.getGrantTime().getTime()); memberList.add(memberDesc); } TableState state = tableStateManager.getState(context, "view:security,GroupMemberList"); if(state.isNew()) { state.setTreeView(false); state.setPageSize(10); } TableModel<Map<String, Object>> model = new ListTableModel<Map<String, Object>>( memberList, columns); templatingContext.put("table", new TableTool<Map<String, Object>>(state, null, model)); templatingContext.put("group", group); if(cmsSecurityService.isGroupResource(group)) { templatingContext.put("groupName", cmsSecurityService.getShortGroupName(group)); } } catch(Exception e) { if(e instanceof ProcessingException) { throw (ProcessingException)e; } throw new ProcessingException("failed to retreive data", e); } }
diff --git a/src/test/java/test/thread/ThreadPoolSizeBase.java b/src/test/java/test/thread/ThreadPoolSizeBase.java index 517f6fa5..0822fdbb 100644 --- a/src/test/java/test/thread/ThreadPoolSizeBase.java +++ b/src/test/java/test/thread/ThreadPoolSizeBase.java @@ -1,18 +1,18 @@ package test.thread; import org.testng.annotations.BeforeClass; public class ThreadPoolSizeBase extends BaseThreadTest { @BeforeClass public void setUp() { log(getClass().getName(), "Init log ids"); initThreadLog(); } protected void logThread() { long n = Thread.currentThread().getId(); - log(getClass().getName(), "threadPoolSize:3"); + log(getClass().getName(), ""); logThread(n); } }
true
true
protected void logThread() { long n = Thread.currentThread().getId(); log(getClass().getName(), "threadPoolSize:3"); logThread(n); }
protected void logThread() { long n = Thread.currentThread().getId(); log(getClass().getName(), ""); logThread(n); }
diff --git a/src/edu/jas/ufd/FactorAbstract.java b/src/edu/jas/ufd/FactorAbstract.java index 41b74a44..31b2842f 100644 --- a/src/edu/jas/ufd/FactorAbstract.java +++ b/src/edu/jas/ufd/FactorAbstract.java @@ -1,621 +1,631 @@ /* * $Id$ */ package edu.jas.ufd; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import edu.jas.poly.GenPolynomial; import edu.jas.poly.GenPolynomialRing; import edu.jas.poly.PolyUtil; import edu.jas.structure.GcdRingElem; import edu.jas.structure.Power; import edu.jas.structure.RingFactory; import edu.jas.util.KsubSet; /** * Abstract factorization algorithms class. This class contains implementations * of all methods of the <code>Factorization</code> interface, except the * method for factorization of a squarefree polynomial. The methods to obtain * squarefree polynomials delegate the computation to the * <code>GreatestCommonDivisor</code> classes and are included for * convenience. * @param <C> coefficient type * @author Heinz Kredel * @see edu.jas.ufd.FactorFactory */ public abstract class FactorAbstract<C extends GcdRingElem<C>> implements Factorization<C> { private static final Logger logger = Logger.getLogger(FactorAbstract.class); private final boolean debug = logger.isDebugEnabled(); /** * Gcd engine for base coefficients. */ protected final GreatestCommonDivisorAbstract<C> engine; /** * Squarefree decompositon engine for base coefficients. */ protected final SquarefreeAbstract<C> sengine; /** * No argument constructor. */ protected FactorAbstract() { throw new IllegalArgumentException("don't use this constructor"); } /** * Constructor. * @param cfac coefficient ring factory. */ public FactorAbstract(RingFactory<C> cfac) { engine = GCDFactory.<C> getProxy(cfac); //engine = GCDFactory.<C> getImplementation(cfac); sengine = SquarefreeFactory.<C> getImplementation(cfac); } /** * Get the String representation. * @see java.lang.Object#toString() */ @Override public String toString() { return getClass().getName(); } /** * GenPolynomial test if is irreducible. * @param P GenPolynomial. * @return true if P is irreducible, else false. */ public boolean isIrreducible(GenPolynomial<C> P) { if (!isSquarefree(P)) { return false; } List<GenPolynomial<C>> F = factorsSquarefree(P); if (F.size() == 1) { return true; } else if (F.size() > 2) { return false; } else { //F.size() == 2 boolean cnst = false; for (GenPolynomial<C> p : F) { if (p.isConstant()) { cnst = true; } } return cnst; } } /** * GenPolynomial test if a non trivial factorization exsists. * @param P GenPolynomial. * @return true if P is reducible, else false. */ public boolean isReducible(GenPolynomial<C> P) { return !isIrreducible(P); } /** * GenPolynomial test if is squarefree. * @param P GenPolynomial. * @return true if P is squarefree, else false. */ public boolean isSquarefree(GenPolynomial<C> P) { GenPolynomial<C> S = squarefreePart(P); GenPolynomial<C> Ps = basePrimitivePart(P); return Ps.equals(S); } /** * GenPolynomial factorization of a squarefree polynomial. * @param P squarefree and primitive! (respectively monic) GenPolynomial. * @return [p_1,...,p_k] with P = prod_{i=1,...,r} p_i. */ public List<GenPolynomial<C>> factorsSquarefree(GenPolynomial<C> P) { if (P == null) { throw new RuntimeException(this.getClass().getName() + " P != null"); } GenPolynomialRing<C> pfac = P.ring; if (pfac.nvar == 1) { return baseFactorsSquarefree(P); } List<GenPolynomial<C>> factors = new ArrayList<GenPolynomial<C>>(); if (P.isZERO()) { return factors; } long d = P.degree() + 1L; GenPolynomial<C> kr = PolyUfdUtil.<C> substituteKronecker(P, d); GenPolynomialRing<C> ufac = kr.ring; ufac.setVars( ufac.newVars( "zz" ) ); // side effects if (debug) { logger.info("subs(P,d=" + d + ") = " + kr); //System.out.println("subs(P,d=" + d + ") = " + kr); } if (kr.degree(0) > 100) { logger.warn("Kronecker substitution has to high degree"); } // factor Kronecker polynomial List<GenPolynomial<C>> ulist = new ArrayList<GenPolynomial<C>>(); // kr might not be squarefree so complete factor univariate SortedMap<GenPolynomial<C>, Long> slist = baseFactors(kr); if (debug && !isFactorization(kr, slist)) { System.out.println("kr = " + kr); System.out.println("slist = " + slist); throw new RuntimeException("no factorization"); } for (GenPolynomial<C> g : slist.keySet()) { long e = slist.get(g); for (int i = 0; i < e; i++) { // is this really required? yes! ulist.add(g); } } //System.out.println("ulist = " + ulist); if (ulist.size() == 1 && ulist.get(0).degree() == P.degree()) { factors.add(P); return factors; } //List<GenPolynomial<C>> klist = PolyUfdUtil.<C> backSubstituteKronecker(pfac, ulist, d); //System.out.println("back(klist) = " + PolyUfdUtil.<C> backSubstituteKronecker(pfac, ulist, d)); if (logger.isInfoEnabled()) { logger.info("ulist = " + ulist); //System.out.println("ulist = " + ulist); } // combine trial factors int dl = ulist.size() - 1; //(ulist.size() + 1) / 2; //System.out.println("dl = " + dl); int ti = 0; GenPolynomial<C> u = P; long deg = (u.degree() + 1L) / 2L; // max deg //System.out.println("deg = " + deg); for (int j = 1; j <= dl; j++) { KsubSet<GenPolynomial<C>> ps = new KsubSet<GenPolynomial<C>>(ulist, j); for (List<GenPolynomial<C>> flist : ps) { //System.out.println("flist = " + flist); GenPolynomial<C> utrial = ufac.getONE(); for (int k = 0; k < flist.size(); k++) { utrial = utrial.multiply(flist.get(k)); } GenPolynomial<C> trial = PolyUfdUtil.<C> backSubstituteKronecker(pfac, utrial, d); if (trial.degree() > deg || trial.isConstant()) { continue; } + trial = trial.monic(); ti++; if (ti % 1000 == 0) { System.out.print("ti(" + ti + ") "); if (ti % 10000 == 0) { System.out.println("\ndl = " + dl + ", deg(u) = " + deg); System.out.println("ulist = " + ulist); System.out.println("kr = " + kr); System.out.println("u = " + u); } } GenPolynomial<C> rem = PolyUtil.<C> basePseudoRemainder(u, trial); //System.out.println(" rem = " + rem); if (rem.isZERO()) { logger.info("trial = " + trial); //System.out.println("trial = " + trial); factors.add(trial); u = PolyUtil.<C> basePseudoDivide(u, trial); //u = u.divide( trial ); if (ulist.removeAll(flist)) { //System.out.println("new ulist = " + ulist); dl = (ulist.size() + 1) / 2; j = 0; // since j++ break; } else { logger.error("error removing flist from ulist = " + ulist); } } } } if (!u.isONE() && !u.equals(P)) { logger.info("rest u = " + u); //System.out.println("rest u = " + u); factors.add(u); } + if ( factors.size() > 1 ) { + List<GenPolynomial<C>> facs = new ArrayList<GenPolynomial<C>>(); + System.out.println("factors = " + factors); + for ( GenPolynomial<C> p : factors ) { + List<GenPolynomial<C>> rfacs = factorsSquarefree(p); // recursion + facs.addAll(rfacs); + } + factors = facs; + } if (factors.size() == 0) { logger.info("irred u = " + u); //System.out.println("irred u = " + u); factors.add(P); } return factors; } /** * Univariate GenPolynomial factorization ignoring multiplicities. * @param P GenPolynomial in one variable. * @return [p_1, ..., p_k] with P = prod_{i=1,...,k} p_i**{e_i} for some * e_i. */ public List<GenPolynomial<C>> baseFactorsRadical(GenPolynomial<C> P) { return new ArrayList<GenPolynomial<C>>(baseFactors(P).keySet()); } /** * Univariate GenPolynomial factorization. * @param P GenPolynomial in one variable. * @return [p_1 -&gt; e_1, ..., p_k -&gt; e_k] with P = prod_{i=1,...,k} * p_i**e_i. */ public SortedMap<GenPolynomial<C>, Long> baseFactors(GenPolynomial<C> P) { if (P == null) { throw new RuntimeException(this.getClass().getName() + " P != null"); } GenPolynomialRing<C> pfac = P.ring; SortedMap<GenPolynomial<C>, Long> factors = new TreeMap<GenPolynomial<C>, Long>(pfac.getComparator()); if (P.isZERO()) { return factors; } if (pfac.nvar > 1) { throw new RuntimeException(this.getClass().getName() + " only for univariate polynomials"); } C c; if (pfac.coFac.isField()) { //pfac.characteristic().signum() > 0 c = P.leadingBaseCoefficient(); } else { c = engine.baseContent(P); // move sign to the content if (P.signum() < 0 && c.signum() > 0) { c = c.negate(); //P = P.negate(); } } if (!c.isONE()) { GenPolynomial<C> pc = pfac.getONE().multiply(c); factors.put(pc, 1L); P = P.divide(c); // make primitive or monic } if (logger.isInfoEnabled()) { logger.info("squarefree facs P = " + P); } SortedMap<GenPolynomial<C>, Long> facs = sengine.baseSquarefreeFactors(P); if (logger.isInfoEnabled() && facs.size() > 1) { logger.info("squarefree facs = " + facs); //System.out.println("sfacs = " + facs); //boolean tt = isFactorization(P,facs); //System.out.println("sfacs tt = " + tt); } for (GenPolynomial<C> g : facs.keySet()) { Long k = facs.get(g); //System.out.println("g = " + g); if (pfac.coFac.isField() && !g.leadingBaseCoefficient().isONE()) { g = g.monic(); // how can this happen? logger.warn("squarefree facs mon = " + g); } List<GenPolynomial<C>> sfacs = baseFactorsSquarefree(g); if (debug) { logger.info("factors of squarefree = " + sfacs); //System.out.println("sfacs = " + sfacs); } for (GenPolynomial<C> h : sfacs) { Long j = factors.get(h); // evtl. constants if (j != null) { k += j; } if ( ! h.isONE() ) { factors.put(h, k); } } } //System.out.println("factors = " + factors); return factors; } /** * Univariate GenPolynomial factorization of a squarefree polynomial. * @param P squarefree and primitive! GenPolynomial in one variable. * @return [p_1, ..., p_k] with P = prod_{i=1,...,k} p_i. */ public abstract List<GenPolynomial<C>> baseFactorsSquarefree(GenPolynomial<C> P); /** * GenPolynomial factorization ignoring multiplicities. * @param P GenPolynomial. * @return [p_1, ..., p_k] with P = prod_{i=1,...,k} p_i**{e_i} for some * e_i. */ public List<GenPolynomial<C>> factorsRadical(GenPolynomial<C> P) { return new ArrayList<GenPolynomial<C>>(factors(P).keySet()); } /** * GenPolynomial list factorization ignoring multiplicities. * @param L list of GenPolynomials. * @return [p_1, ..., p_k] with p = prod_{i=1,...,k} p_i**{e_i} for some * e_i for all p in L. */ public List<GenPolynomial<C>> factorsRadical(List<GenPolynomial<C>> L) { SortedSet<GenPolynomial<C>> facs = new TreeSet<GenPolynomial<C>>(); for ( GenPolynomial<C> p : L ) { List<GenPolynomial<C>> fs = factorsRadical(p); facs.addAll(fs); } return new ArrayList<GenPolynomial<C>>( facs ); } /** * GenPolynomial factorization. * @param P GenPolynomial. * @return [p_1 -&gt; e_1, ..., p_k -&gt; e_k] with P = prod_{i=1,...,k} * p_i**e_i. */ public SortedMap<GenPolynomial<C>, Long> factors(GenPolynomial<C> P) { if (P == null) { throw new RuntimeException(this.getClass().getName() + " P != null"); } GenPolynomialRing<C> pfac = P.ring; if (pfac.nvar == 1) { return baseFactors(P); } SortedMap<GenPolynomial<C>, Long> factors = new TreeMap<GenPolynomial<C>, Long>(pfac.getComparator()); if (P.isZERO()) { return factors; } C c; if (pfac.coFac.isField()) { // pfac.characteristic().signum() > 0 c = P.leadingBaseCoefficient(); } else { c = engine.baseContent(P); // move sign to the content if (P.signum() < 0 && c.signum() > 0) { c = c.negate(); //P = P.negate(); } } if (!c.isONE()) { GenPolynomial<C> pc = pfac.getONE().multiply(c); factors.put(pc, 1L); P = P.divide(c); // make base primitive or base monic } if (logger.isInfoEnabled()) { logger.info("squarefree mfacs P = " + P); } SortedMap<GenPolynomial<C>, Long> facs = sengine.squarefreeFactors(P); if (logger.isInfoEnabled() && facs.size() > 1) { logger.info("squarefree mfacs = " + facs); //System.out.println("facs = " + facs); } for (GenPolynomial<C> g : facs.keySet()) { Long d = facs.get(g); List<GenPolynomial<C>> sfacs = factorsSquarefree(g); if (debug) { logger.info("factors of squarefree = " + sfacs); //System.out.println("sfacs = " + sfacs); } for (GenPolynomial<C> h : sfacs) { Long j = factors.get(h); // evtl. constants if (j != null) { d += j; } factors.put(h, d); } } //System.out.println("factors = " + factors); return factors; } /** * GenPolynomial greatest squarefree divisor. Delegates computation to a * GreatestCommonDivisor class. * @param P GenPolynomial. * @return squarefree(P). */ public GenPolynomial<C> squarefreePart(GenPolynomial<C> P) { return sengine.squarefreePart(P); } /** * GenPolynomial primitive part. Delegates computation to a * GreatestCommonDivisor class. * @param P GenPolynomial. * @return primitivePart(P). */ public GenPolynomial<C> primitivePart(GenPolynomial<C> P) { return engine.primitivePart(P); } /** * GenPolynomial base primitive part. Delegates computation to a * GreatestCommonDivisor class. * @param P GenPolynomial. * @return basePrimitivePart(P). */ public GenPolynomial<C> basePrimitivePart(GenPolynomial<C> P) { return engine.basePrimitivePart(P); } /** * GenPolynomial squarefree factorization. Delegates computation to a * GreatestCommonDivisor class. * @param P GenPolynomial. * @return [p_1 -&gt; e_1, ..., p_k -&gt; e_k] with P = prod_{i=1,...,k} * p_i**e_i. */ public SortedMap<GenPolynomial<C>, Long> squarefreeFactors(GenPolynomial<C> P) { return sengine.squarefreeFactors(P); } /** * GenPolynomial is factorization. * @param P GenPolynomial. * @param F = [p_1,...,p_k]. * @return true if P = prod_{i=1,...,r} p_i, else false. */ public boolean isFactorization(GenPolynomial<C> P, List<GenPolynomial<C>> F) { return sengine.isFactorization(P,F); // test irreducible } /** * GenPolynomial is factorization. * @param P GenPolynomial. * @param F = [p_1 -&gt; e_1, ..., p_k -&gt; e_k]. * @return true if P = prod_{i=1,...,k} p_i**e_i , else false. */ public boolean isFactorization(GenPolynomial<C> P, SortedMap<GenPolynomial<C>, Long> F) { return sengine.isFactorization(P,F); // test irreducible } /** * GenPolynomial is factorization. * @param P GenPolynomial. * @param F = [p_1 -&gt; e_1, ..., p_k -&gt; e_k]. * @return true if P = prod_{i=1,...,k} p_i**e_i , else false. */ public boolean isRecursiveFactorization(GenPolynomial<GenPolynomial<C>> P, SortedMap<GenPolynomial<GenPolynomial<C>>, Long> F) { return sengine.isRecursiveFactorization(P,F); // test irreducible } /** * Recursive GenPolynomial factorization of a squarefree polynomial. * @param P squarefree recursive GenPolynomial. * @return [p_1,...,p_k] with P = prod_{i=1, ..., k} p_i. */ public List<GenPolynomial<GenPolynomial<C>>> recursiveFactorsSquarefree(GenPolynomial<GenPolynomial<C>> P) { if (P == null) { throw new RuntimeException(this.getClass().getName() + " P == null"); } List<GenPolynomial<GenPolynomial<C>>> factors = new ArrayList<GenPolynomial<GenPolynomial<C>>>(); if (P.isZERO()) { return factors; } if (P.isONE()) { factors.add(P); return factors; } GenPolynomialRing<GenPolynomial<C>> pfac = P.ring; GenPolynomialRing<C> qi = (GenPolynomialRing<C>) pfac.coFac; GenPolynomialRing<C> ifac = qi.extend(pfac.getVars()); GenPolynomial<C> Pi = PolyUtil.<C> distribute(ifac, P); //System.out.println("Pi = " + Pi); C ldcf = Pi.leadingBaseCoefficient(); if (!ldcf.isONE() && ldcf.isUnit()) { //System.out.println("ldcf = " + ldcf); Pi = Pi.monic(); } // factor in C[x_1,...,x_n,y_1,...,y_m] List<GenPolynomial<C>> ifacts = factorsSquarefree(Pi); if (logger.isInfoEnabled()) { logger.info("ifacts = " + ifacts); } if (ifacts.size() <= 1) { factors.add(P); return factors; } if (!ldcf.isONE() && ldcf.isUnit()) { GenPolynomial<C> r = ifacts.get(0); ifacts.remove(r); r = r.multiply(ldcf); ifacts.add(0, r); } List<GenPolynomial<GenPolynomial<C>>> rfacts = PolyUtil.<C> recursive(pfac, ifacts); //System.out.println("rfacts = " + rfacts); if (logger.isDebugEnabled()) { logger.info("rfacts = " + rfacts); } factors.addAll(rfacts); return factors; } /** * Recursive GenPolynomial factorization. * @param P recursive GenPolynomial. * @return [p_1 -&gt; e_1, ..., p_k -&gt; e_k] with P = prod_{i=1,...,k} * p_i**e_i. */ public SortedMap<GenPolynomial<GenPolynomial<C>>, Long> recursiveFactors(GenPolynomial<GenPolynomial<C>> P) { if (P == null) { throw new RuntimeException(this.getClass().getName() + " P != null"); } GenPolynomialRing<GenPolynomial<C>> pfac = P.ring; SortedMap<GenPolynomial<GenPolynomial<C>>, Long> factors = new TreeMap<GenPolynomial<GenPolynomial<C>>, Long>( pfac.getComparator()); if (P.isZERO()) { return factors; } if (P.isONE()) { factors.put(P, 1L); return factors; } GenPolynomialRing<C> qi = (GenPolynomialRing<C>) pfac.coFac; GenPolynomialRing<C> ifac = qi.extend(pfac.getVars()); GenPolynomial<C> Pi = PolyUtil.<C> distribute(ifac, P); //System.out.println("Pi = " + Pi); C ldcf = Pi.leadingBaseCoefficient(); if (!ldcf.isONE() && ldcf.isUnit()) { //System.out.println("ldcf = " + ldcf); Pi = Pi.monic(); } // factor in C[x_1,...,x_n,y_1,...,y_m] SortedMap<GenPolynomial<C>, Long> dfacts = factors(Pi); if (logger.isInfoEnabled()) { logger.info("dfacts = " + dfacts); } if (!ldcf.isONE() && ldcf.isUnit()) { GenPolynomial<C> r = dfacts.firstKey(); Long E = dfacts.remove(r); r = r.multiply(ldcf); dfacts.put(r, E); } for (GenPolynomial<C> f : dfacts.keySet()) { Long E = dfacts.get(f); GenPolynomial<GenPolynomial<C>> rp = PolyUtil.<C> recursive(pfac, f); factors.put(rp, E); } //System.out.println("rfacts = " + rfacts); if (logger.isInfoEnabled()) { logger.info("factors = " + factors); } return factors; } }
false
true
public List<GenPolynomial<C>> factorsSquarefree(GenPolynomial<C> P) { if (P == null) { throw new RuntimeException(this.getClass().getName() + " P != null"); } GenPolynomialRing<C> pfac = P.ring; if (pfac.nvar == 1) { return baseFactorsSquarefree(P); } List<GenPolynomial<C>> factors = new ArrayList<GenPolynomial<C>>(); if (P.isZERO()) { return factors; } long d = P.degree() + 1L; GenPolynomial<C> kr = PolyUfdUtil.<C> substituteKronecker(P, d); GenPolynomialRing<C> ufac = kr.ring; ufac.setVars( ufac.newVars( "zz" ) ); // side effects if (debug) { logger.info("subs(P,d=" + d + ") = " + kr); //System.out.println("subs(P,d=" + d + ") = " + kr); } if (kr.degree(0) > 100) { logger.warn("Kronecker substitution has to high degree"); } // factor Kronecker polynomial List<GenPolynomial<C>> ulist = new ArrayList<GenPolynomial<C>>(); // kr might not be squarefree so complete factor univariate SortedMap<GenPolynomial<C>, Long> slist = baseFactors(kr); if (debug && !isFactorization(kr, slist)) { System.out.println("kr = " + kr); System.out.println("slist = " + slist); throw new RuntimeException("no factorization"); } for (GenPolynomial<C> g : slist.keySet()) { long e = slist.get(g); for (int i = 0; i < e; i++) { // is this really required? yes! ulist.add(g); } } //System.out.println("ulist = " + ulist); if (ulist.size() == 1 && ulist.get(0).degree() == P.degree()) { factors.add(P); return factors; } //List<GenPolynomial<C>> klist = PolyUfdUtil.<C> backSubstituteKronecker(pfac, ulist, d); //System.out.println("back(klist) = " + PolyUfdUtil.<C> backSubstituteKronecker(pfac, ulist, d)); if (logger.isInfoEnabled()) { logger.info("ulist = " + ulist); //System.out.println("ulist = " + ulist); } // combine trial factors int dl = ulist.size() - 1; //(ulist.size() + 1) / 2; //System.out.println("dl = " + dl); int ti = 0; GenPolynomial<C> u = P; long deg = (u.degree() + 1L) / 2L; // max deg //System.out.println("deg = " + deg); for (int j = 1; j <= dl; j++) { KsubSet<GenPolynomial<C>> ps = new KsubSet<GenPolynomial<C>>(ulist, j); for (List<GenPolynomial<C>> flist : ps) { //System.out.println("flist = " + flist); GenPolynomial<C> utrial = ufac.getONE(); for (int k = 0; k < flist.size(); k++) { utrial = utrial.multiply(flist.get(k)); } GenPolynomial<C> trial = PolyUfdUtil.<C> backSubstituteKronecker(pfac, utrial, d); if (trial.degree() > deg || trial.isConstant()) { continue; } ti++; if (ti % 1000 == 0) { System.out.print("ti(" + ti + ") "); if (ti % 10000 == 0) { System.out.println("\ndl = " + dl + ", deg(u) = " + deg); System.out.println("ulist = " + ulist); System.out.println("kr = " + kr); System.out.println("u = " + u); } } GenPolynomial<C> rem = PolyUtil.<C> basePseudoRemainder(u, trial); //System.out.println(" rem = " + rem); if (rem.isZERO()) { logger.info("trial = " + trial); //System.out.println("trial = " + trial); factors.add(trial); u = PolyUtil.<C> basePseudoDivide(u, trial); //u = u.divide( trial ); if (ulist.removeAll(flist)) { //System.out.println("new ulist = " + ulist); dl = (ulist.size() + 1) / 2; j = 0; // since j++ break; } else { logger.error("error removing flist from ulist = " + ulist); } } } } if (!u.isONE() && !u.equals(P)) { logger.info("rest u = " + u); //System.out.println("rest u = " + u); factors.add(u); } if (factors.size() == 0) { logger.info("irred u = " + u); //System.out.println("irred u = " + u); factors.add(P); } return factors; }
public List<GenPolynomial<C>> factorsSquarefree(GenPolynomial<C> P) { if (P == null) { throw new RuntimeException(this.getClass().getName() + " P != null"); } GenPolynomialRing<C> pfac = P.ring; if (pfac.nvar == 1) { return baseFactorsSquarefree(P); } List<GenPolynomial<C>> factors = new ArrayList<GenPolynomial<C>>(); if (P.isZERO()) { return factors; } long d = P.degree() + 1L; GenPolynomial<C> kr = PolyUfdUtil.<C> substituteKronecker(P, d); GenPolynomialRing<C> ufac = kr.ring; ufac.setVars( ufac.newVars( "zz" ) ); // side effects if (debug) { logger.info("subs(P,d=" + d + ") = " + kr); //System.out.println("subs(P,d=" + d + ") = " + kr); } if (kr.degree(0) > 100) { logger.warn("Kronecker substitution has to high degree"); } // factor Kronecker polynomial List<GenPolynomial<C>> ulist = new ArrayList<GenPolynomial<C>>(); // kr might not be squarefree so complete factor univariate SortedMap<GenPolynomial<C>, Long> slist = baseFactors(kr); if (debug && !isFactorization(kr, slist)) { System.out.println("kr = " + kr); System.out.println("slist = " + slist); throw new RuntimeException("no factorization"); } for (GenPolynomial<C> g : slist.keySet()) { long e = slist.get(g); for (int i = 0; i < e; i++) { // is this really required? yes! ulist.add(g); } } //System.out.println("ulist = " + ulist); if (ulist.size() == 1 && ulist.get(0).degree() == P.degree()) { factors.add(P); return factors; } //List<GenPolynomial<C>> klist = PolyUfdUtil.<C> backSubstituteKronecker(pfac, ulist, d); //System.out.println("back(klist) = " + PolyUfdUtil.<C> backSubstituteKronecker(pfac, ulist, d)); if (logger.isInfoEnabled()) { logger.info("ulist = " + ulist); //System.out.println("ulist = " + ulist); } // combine trial factors int dl = ulist.size() - 1; //(ulist.size() + 1) / 2; //System.out.println("dl = " + dl); int ti = 0; GenPolynomial<C> u = P; long deg = (u.degree() + 1L) / 2L; // max deg //System.out.println("deg = " + deg); for (int j = 1; j <= dl; j++) { KsubSet<GenPolynomial<C>> ps = new KsubSet<GenPolynomial<C>>(ulist, j); for (List<GenPolynomial<C>> flist : ps) { //System.out.println("flist = " + flist); GenPolynomial<C> utrial = ufac.getONE(); for (int k = 0; k < flist.size(); k++) { utrial = utrial.multiply(flist.get(k)); } GenPolynomial<C> trial = PolyUfdUtil.<C> backSubstituteKronecker(pfac, utrial, d); if (trial.degree() > deg || trial.isConstant()) { continue; } trial = trial.monic(); ti++; if (ti % 1000 == 0) { System.out.print("ti(" + ti + ") "); if (ti % 10000 == 0) { System.out.println("\ndl = " + dl + ", deg(u) = " + deg); System.out.println("ulist = " + ulist); System.out.println("kr = " + kr); System.out.println("u = " + u); } } GenPolynomial<C> rem = PolyUtil.<C> basePseudoRemainder(u, trial); //System.out.println(" rem = " + rem); if (rem.isZERO()) { logger.info("trial = " + trial); //System.out.println("trial = " + trial); factors.add(trial); u = PolyUtil.<C> basePseudoDivide(u, trial); //u = u.divide( trial ); if (ulist.removeAll(flist)) { //System.out.println("new ulist = " + ulist); dl = (ulist.size() + 1) / 2; j = 0; // since j++ break; } else { logger.error("error removing flist from ulist = " + ulist); } } } } if (!u.isONE() && !u.equals(P)) { logger.info("rest u = " + u); //System.out.println("rest u = " + u); factors.add(u); } if ( factors.size() > 1 ) { List<GenPolynomial<C>> facs = new ArrayList<GenPolynomial<C>>(); System.out.println("factors = " + factors); for ( GenPolynomial<C> p : factors ) { List<GenPolynomial<C>> rfacs = factorsSquarefree(p); // recursion facs.addAll(rfacs); } factors = facs; } if (factors.size() == 0) { logger.info("irred u = " + u); //System.out.println("irred u = " + u); factors.add(P); } return factors; }
diff --git a/src/com/vesalaakso/rbb/states/GameState.java b/src/com/vesalaakso/rbb/states/GameState.java index 0b81535..49ac6c3 100644 --- a/src/com/vesalaakso/rbb/states/GameState.java +++ b/src/com/vesalaakso/rbb/states/GameState.java @@ -1,354 +1,355 @@ package com.vesalaakso.rbb.states; import java.util.LinkedList; import java.util.List; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.state.transition.FadeInTransition; import org.newdawn.slick.state.transition.FadeOutTransition; import org.newdawn.slick.state.transition.Transition; import org.newdawn.slick.util.Log; import com.vesalaakso.rbb.controller.CameraController; import com.vesalaakso.rbb.controller.DebugKeyController; import com.vesalaakso.rbb.controller.InputMaster; import com.vesalaakso.rbb.controller.MapChanger; import com.vesalaakso.rbb.controller.MenuKeyController; import com.vesalaakso.rbb.controller.PlayerListener; import com.vesalaakso.rbb.controller.Resetable; import com.vesalaakso.rbb.controller.RubberBandController; import com.vesalaakso.rbb.controller.Updateable; import com.vesalaakso.rbb.model.Background; import com.vesalaakso.rbb.model.ParticleManager; import com.vesalaakso.rbb.model.Physics; import com.vesalaakso.rbb.model.Player; import com.vesalaakso.rbb.model.RubberBand; import com.vesalaakso.rbb.model.TileMapContainer; import com.vesalaakso.rbb.model.exceptions.MapException; import com.vesalaakso.rbb.view.BackgroundPainter; import com.vesalaakso.rbb.view.DebugPrintPainter; import com.vesalaakso.rbb.view.PainterContainer; import com.vesalaakso.rbb.view.PhysicsPainter; import com.vesalaakso.rbb.view.PlayerPainter; import com.vesalaakso.rbb.view.RubberBandPainter; import com.vesalaakso.rbb.view.TileMapAreaPainter; import com.vesalaakso.rbb.view.TileMapBackLayerPainter; import com.vesalaakso.rbb.view.TileMapOverLayerPainter; /** * The state which handles the game logic. * * @author Vesa Laakso */ public class GameState extends BasicGameState { /** * The current map is always stored in this <code>TileMapContainer</code>. * The underlying <code>TileMap</code> object may change but this object * stays. */ private final TileMapContainer mapContainer = new TileMapContainer(); /** * The <code>MapChanger</code> responsible for changing the map and * notifying everything that needs to be notified. */ private MapChanger mapChanger = new MapChanger(mapContainer); /** * A <code>PainterContainer</code> which stores everything that can be * painted. */ private PainterContainer painterContainer = new PainterContainer(); /** * All the stuff which need to be updated in update()-method are stored * here. */ private List<Updateable> updateables = new LinkedList<Updateable>(); /** All the stuff which need to be reset when state is changed */ private List<Resetable> resetables = new LinkedList<Resetable>(); /** InputMaster to handle the coordination of various input controllers. */ private InputMaster inputMaster; /** What would a game be without a player? */ private Player player; /** The player is controlled by this rubber band! */ private RubberBand rubberBand; /** Ooh, particles, yes please! */ private ParticleManager particleManager = new ParticleManager(); /** Of course we need physics, here it is! */ private Physics physics; /** And some eye candy. */ private Background background; /** If the game should stop at next update()-call, this flag knows. */ private boolean stopAtNextUpdate; /** Is the game in debug mode? */ private boolean debugMode = true; /** Change to this map on the next update() call. */ private int changeToLevel = -1; /** The state which handles map changing routines. */ private MapChangeState mapChangeState; /** We need something to do something when player does something. */ private PlayerListener playerListener; /** Has this state been initialized in render call before enter already */ private boolean renderInitializedBeforeEnter = false; /** * Construct the GameState and tells it which state is responsible for map * changing routines. * * @param mapChangeState * the state which handles map changing routines. */ public GameState(MapChangeState mapChangeState) { this.mapChangeState = mapChangeState; } /** A helper method which adds all the painters in the correct order. */ private void addPainters() { painterContainer.addPainter(new BackgroundPainter(background)); painterContainer.addPainter(new TileMapAreaPainter(mapContainer)); painterContainer.addPainter(new TileMapBackLayerPainter(mapContainer)); painterContainer.addPainter(new PlayerPainter(player)); painterContainer.addPainter(new TileMapOverLayerPainter(mapContainer)); painterContainer.addPainter(new RubberBandPainter(rubberBand)); painterContainer.addDebugPainter(new PhysicsPainter(physics)); painterContainer .addDebugPainter(new DebugPrintPainter(physics, player)); } /** * A helper method which adds all the controllers and updateables to the * game. */ private void addControllers(Input input) { inputMaster = new InputMaster(input); inputMaster.addKeyListener(new CameraController(player)); inputMaster.addKeyListener(new MenuKeyController(this)); inputMaster.addMouseListener(new RubberBandController(rubberBand)); inputMaster.addKeyListener(new DebugKeyController(this, player)); } /** * A helper method for listing up everything that needs to be reset before * first render. */ private void addResetables() { resetables.add(player); resetables.add(rubberBand); resetables.add(physics); resetables.add(particleManager); resetables.add(background); } /** A helper method which adds all updateables. */ private void addUpdateables() { updateables.add(inputMaster); updateables.add(physics); updateables.add(playerListener); updateables.add(background); updateables.add(particleManager); } /** * Resets the state of the game, useful when transitions cause headaches. * Mainly resets positions of various stuff. */ private void resetBeforeRender() { if (renderInitializedBeforeEnter) { // No need to do anything. return; } stopAtNextUpdate = false; changeToLevel = -1; for (Resetable r : resetables) { r.reset(); } // This has been done now. renderInitializedBeforeEnter = true; } /** * Makes the game quit on the next update-loop. */ public void stop() { stopAtNextUpdate = true; } /** * Changes the level on the next update() call to the one given. * * @param level * the level index to change to. */ public void changeLevel(int level) { this.changeToLevel = level; } /** Toggles debug mode */ public void toggleDebug() { debugMode = !debugMode; } /** * Gets the debug status of the game. * * @return <code>true</code> if debug mode is on */ public boolean isDebugModeToggled() { return debugMode; } /** * From slick: Initialise the state. It should load any resources it needs * at this stage * * @see org.newdawn.slick.BasicGame#init(org.newdawn.slick.GameContainer) */ @Override public void init(GameContainer container, StateBasedGame game) throws SlickException { // Remove this as the input handler, as input handling is done via // InputMaster class and not this. container.getInput().removeListener(this); // Load the background image background = new Background(); // Construct the object representing the player player = new Player(mapContainer); // Physics world, too physics = new Physics(player, particleManager, mapContainer); // Add the rubber band to the game rubberBand = new RubberBand(player, physics); // The player listener. Oh yes. playerListener = new PlayerListener(mapContainer, player, physics, this); // Add the painters next addPainters(); // And then the controllers addControllers(container.getInput()); // Some stuff need to be reset before first render. addResetables(); // Finally add all objects which hook to the update()-method. addUpdateables(); // Then reset the map. mapChanger.changeMap(1); try { mapChanger.runChange(); } catch (MapException e) { - e.printStackTrace(); - container.exit(); + // So we couldn't load even the first map... that's sad. + Log.error("Failed to change to the first map."); + throw new SlickException("Failed to change to the first map.", e); } } /** * From slick: Render this state to the game's graphics context * * @param g * The graphics context that can be used to render. However, * normal rendering routines can also be used. * * @see org.newdawn.slick.Game#render(org.newdawn.slick.GameContainer, * org.newdawn.slick.Graphics) */ @Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { // Initialize some positions before rendering, because of transitions. resetBeforeRender(); painterContainer.paintAll(g, this); } @Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { // The game was not meant to last forever, my friend. if (stopAtNextUpdate) { Transition leave = new FadeOutTransition(); Transition enter = new FadeInTransition(); game.enterState(State.MAIN_MENU.ordinal(), leave, enter); } if (changeToLevel > 0) { Transition leave = new FadeOutTransition(); mapChanger.changeMap(changeToLevel); mapChangeState.setupChange(mapChanger, this); game.enterState(mapChangeState.getID(), leave, null); return; } // Update everything that wants to be updated. for (Updateable u : updateables) { u.update(delta); } } /** * @see org.newdawn.slick.state.GameState#enter(GameContainer, * StateBasedGame) */ @Override public void enter(GameContainer container, StateBasedGame game) throws SlickException { System.out.println("entered, time " + System.currentTimeMillis()); } /** * @see org.newdawn.slick.state.GameState#leave(GameContainer, * StateBasedGame) */ @Override public void leave(GameContainer container, StateBasedGame game) throws SlickException { renderInitializedBeforeEnter = false; } @Override public int getID() { return State.GAME.ordinal(); } /** * Called when the game should end * * @param reason * the reason why game ended */ public void gameOver(String reason) { // TODO: something System.out.println("GAME OVER -- " + reason); this.stop(); } }
true
true
public void init(GameContainer container, StateBasedGame game) throws SlickException { // Remove this as the input handler, as input handling is done via // InputMaster class and not this. container.getInput().removeListener(this); // Load the background image background = new Background(); // Construct the object representing the player player = new Player(mapContainer); // Physics world, too physics = new Physics(player, particleManager, mapContainer); // Add the rubber band to the game rubberBand = new RubberBand(player, physics); // The player listener. Oh yes. playerListener = new PlayerListener(mapContainer, player, physics, this); // Add the painters next addPainters(); // And then the controllers addControllers(container.getInput()); // Some stuff need to be reset before first render. addResetables(); // Finally add all objects which hook to the update()-method. addUpdateables(); // Then reset the map. mapChanger.changeMap(1); try { mapChanger.runChange(); } catch (MapException e) { e.printStackTrace(); container.exit(); } }
public void init(GameContainer container, StateBasedGame game) throws SlickException { // Remove this as the input handler, as input handling is done via // InputMaster class and not this. container.getInput().removeListener(this); // Load the background image background = new Background(); // Construct the object representing the player player = new Player(mapContainer); // Physics world, too physics = new Physics(player, particleManager, mapContainer); // Add the rubber band to the game rubberBand = new RubberBand(player, physics); // The player listener. Oh yes. playerListener = new PlayerListener(mapContainer, player, physics, this); // Add the painters next addPainters(); // And then the controllers addControllers(container.getInput()); // Some stuff need to be reset before first render. addResetables(); // Finally add all objects which hook to the update()-method. addUpdateables(); // Then reset the map. mapChanger.changeMap(1); try { mapChanger.runChange(); } catch (MapException e) { // So we couldn't load even the first map... that's sad. Log.error("Failed to change to the first map."); throw new SlickException("Failed to change to the first map.", e); } }
diff --git a/plugins/org.eclipse.acceleo.parser/src-ant/org/eclipse/acceleo/parser/compiler/AcceleoCompiler.java b/plugins/org.eclipse.acceleo.parser/src-ant/org/eclipse/acceleo/parser/compiler/AcceleoCompiler.java index 4883d3fc..b4a52c04 100644 --- a/plugins/org.eclipse.acceleo.parser/src-ant/org/eclipse/acceleo/parser/compiler/AcceleoCompiler.java +++ b/plugins/org.eclipse.acceleo.parser/src-ant/org/eclipse/acceleo/parser/compiler/AcceleoCompiler.java @@ -1,209 +1,210 @@ /******************************************************************************* * Copyright (c) 2008, 2010 Obeo. * 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: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.acceleo.parser.compiler; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.eclipse.acceleo.common.IAcceleoConstants; import org.eclipse.acceleo.parser.AcceleoFile; import org.eclipse.acceleo.parser.AcceleoParser; import org.eclipse.acceleo.parser.AcceleoParserProblem; import org.eclipse.acceleo.parser.AcceleoParserProblems; import org.eclipse.core.runtime.Path; import org.eclipse.emf.common.util.BasicMonitor; import org.eclipse.emf.common.util.URI; /** * The Acceleo Compiler ANT Task. * * @author <a href="mailto:[email protected]">Jonathan Musset</a> */ public class AcceleoCompiler extends Task { /** * The source folders to compile. */ private List<File> sourceFolders = new ArrayList<File>(); /** * The MTL file properties. * * @author <a href="mailto:[email protected]">Jonathan Musset</a> */ private final class MTLFileInfo { /** * The IO file. */ protected File mtlFile; /** * The absolute URI. */ protected URI emtlAbsoluteURI; /** * The full qualified module name. */ protected String fullModuleName; /** * Constructor. */ protected MTLFileInfo() { // Hides constructor from anything other than AcceleoCompiler } } /** * Sets the source folders to compile. They are separated by ';'. * * @param allSourceFolders * are the source folders to compile */ public void setSourceFolders(String allSourceFolders) { sourceFolders.clear(); StringTokenizer st = new StringTokenizer(allSourceFolders, ";"); //$NON-NLS-1$ while (st.hasMoreTokens()) { String path = st.nextToken().trim(); if (path.length() > 0) { File sourceFolder = new Path(path).toFile(); sourceFolders.add(sourceFolder); } } } /** * {@inheritDoc} * * @see org.apache.tools.ant.Task#execute() */ @Override public void execute() throws BuildException { StringBuffer message = new StringBuffer(); List<MTLFileInfo> fileInfos = new ArrayList<MTLFileInfo>(); for (File sourceFolder : sourceFolders) { if (sourceFolder != null && sourceFolder.exists() && sourceFolder.isDirectory()) { fileInfos.addAll(computeFileInfos(sourceFolder)); } else if (sourceFolder != null) { // The ANT Task localization doesn't work. message.append("The folder '"); //$NON-NLS-1$ message.append(sourceFolder.getName()); message.append('\''); message.append(" doesn't exist."); //$NON-NLS-1$ message.append('\n'); } } List<AcceleoFile> acceleoFiles = new ArrayList<AcceleoFile>(); List<URI> emtlAbsoluteURIs = new ArrayList<URI>(); for (MTLFileInfo mtlFileInfo : fileInfos) { acceleoFiles.add(new AcceleoFile(mtlFileInfo.mtlFile, mtlFileInfo.fullModuleName)); emtlAbsoluteURIs.add(mtlFileInfo.emtlAbsoluteURI); } List<URI> dependenciesURIs = new ArrayList<URI>(); AcceleoParser parser = new AcceleoParser(); parser.parse(acceleoFiles, emtlAbsoluteURIs, dependenciesURIs, new BasicMonitor()); for (Iterator<AcceleoFile> iterator = acceleoFiles.iterator(); iterator.hasNext();) { AcceleoFile acceleoFile = iterator.next(); AcceleoParserProblems problems = parser.getProblems(acceleoFile); if (problems != null) { List<AcceleoParserProblem> list = problems.getList(); if (!list.isEmpty()) { message.append(acceleoFile.getMtlFile().getName()); message.append('\n'); for (Iterator<AcceleoParserProblem> itProblems = list.iterator(); itProblems.hasNext();) { AcceleoParserProblem problem = itProblems.next(); message.append(problem.getLine()); message.append(':'); message.append(problem.getMessage()); message.append('\n'); } message.append('\n'); } } } if (message.length() > 0) { String log = message.toString(); - log(log, new BuildException(log), Project.MSG_ERR); + setDescription(log); + log(log, Project.MSG_ERR); } } /** * Computes the properties of the MTL files of the given source folder. * * @param sourceFolder * the current source folder * @return the MTL files properties */ private List<MTLFileInfo> computeFileInfos(File sourceFolder) { List<MTLFileInfo> fileInfosOutput = new ArrayList<MTLFileInfo>(); if (sourceFolder.exists()) { String sourceFolderAbsolutePath = sourceFolder.getAbsolutePath(); List<File> mtlFiles = new ArrayList<File>(); members(mtlFiles, sourceFolder, IAcceleoConstants.MTL_FILE_EXTENSION); for (File mtlFile : mtlFiles) { String mtlFileAbsolutePath = mtlFile.getAbsolutePath(); if (mtlFileAbsolutePath != null) { String relativePath; if (mtlFileAbsolutePath.startsWith(sourceFolderAbsolutePath)) { relativePath = mtlFileAbsolutePath.substring(sourceFolderAbsolutePath.length()); } else { relativePath = mtlFile.getName(); } URI emtlAbsoluteURI = URI.createFileURI(new Path(mtlFileAbsolutePath) .removeFileExtension().addFileExtension(IAcceleoConstants.EMTL_FILE_EXTENSION) .toString()); MTLFileInfo fileInfo = new MTLFileInfo(); fileInfo.mtlFile = mtlFile; fileInfo.emtlAbsoluteURI = emtlAbsoluteURI; fileInfo.fullModuleName = AcceleoFile.relativePathToFullModuleName(relativePath); fileInfosOutput.add(fileInfo); } } } return fileInfosOutput; } /** * Computes recursively the members of the given container that match the given file extension. * * @param filesOutput * is the list to create * @param container * is the container to browse * @param extension * is the extension to match */ private void members(List<File> filesOutput, File container, String extension) { if (container != null && container.isDirectory()) { File[] children = container.listFiles(); if (children != null) { for (File child : children) { if (child.isFile() && child.getName() != null && (extension == null || child.getName().endsWith('.' + extension))) { filesOutput.add(child); } else { members(filesOutput, child, extension); } } } } } }
true
true
public void execute() throws BuildException { StringBuffer message = new StringBuffer(); List<MTLFileInfo> fileInfos = new ArrayList<MTLFileInfo>(); for (File sourceFolder : sourceFolders) { if (sourceFolder != null && sourceFolder.exists() && sourceFolder.isDirectory()) { fileInfos.addAll(computeFileInfos(sourceFolder)); } else if (sourceFolder != null) { // The ANT Task localization doesn't work. message.append("The folder '"); //$NON-NLS-1$ message.append(sourceFolder.getName()); message.append('\''); message.append(" doesn't exist."); //$NON-NLS-1$ message.append('\n'); } } List<AcceleoFile> acceleoFiles = new ArrayList<AcceleoFile>(); List<URI> emtlAbsoluteURIs = new ArrayList<URI>(); for (MTLFileInfo mtlFileInfo : fileInfos) { acceleoFiles.add(new AcceleoFile(mtlFileInfo.mtlFile, mtlFileInfo.fullModuleName)); emtlAbsoluteURIs.add(mtlFileInfo.emtlAbsoluteURI); } List<URI> dependenciesURIs = new ArrayList<URI>(); AcceleoParser parser = new AcceleoParser(); parser.parse(acceleoFiles, emtlAbsoluteURIs, dependenciesURIs, new BasicMonitor()); for (Iterator<AcceleoFile> iterator = acceleoFiles.iterator(); iterator.hasNext();) { AcceleoFile acceleoFile = iterator.next(); AcceleoParserProblems problems = parser.getProblems(acceleoFile); if (problems != null) { List<AcceleoParserProblem> list = problems.getList(); if (!list.isEmpty()) { message.append(acceleoFile.getMtlFile().getName()); message.append('\n'); for (Iterator<AcceleoParserProblem> itProblems = list.iterator(); itProblems.hasNext();) { AcceleoParserProblem problem = itProblems.next(); message.append(problem.getLine()); message.append(':'); message.append(problem.getMessage()); message.append('\n'); } message.append('\n'); } } } if (message.length() > 0) { String log = message.toString(); log(log, new BuildException(log), Project.MSG_ERR); } }
public void execute() throws BuildException { StringBuffer message = new StringBuffer(); List<MTLFileInfo> fileInfos = new ArrayList<MTLFileInfo>(); for (File sourceFolder : sourceFolders) { if (sourceFolder != null && sourceFolder.exists() && sourceFolder.isDirectory()) { fileInfos.addAll(computeFileInfos(sourceFolder)); } else if (sourceFolder != null) { // The ANT Task localization doesn't work. message.append("The folder '"); //$NON-NLS-1$ message.append(sourceFolder.getName()); message.append('\''); message.append(" doesn't exist."); //$NON-NLS-1$ message.append('\n'); } } List<AcceleoFile> acceleoFiles = new ArrayList<AcceleoFile>(); List<URI> emtlAbsoluteURIs = new ArrayList<URI>(); for (MTLFileInfo mtlFileInfo : fileInfos) { acceleoFiles.add(new AcceleoFile(mtlFileInfo.mtlFile, mtlFileInfo.fullModuleName)); emtlAbsoluteURIs.add(mtlFileInfo.emtlAbsoluteURI); } List<URI> dependenciesURIs = new ArrayList<URI>(); AcceleoParser parser = new AcceleoParser(); parser.parse(acceleoFiles, emtlAbsoluteURIs, dependenciesURIs, new BasicMonitor()); for (Iterator<AcceleoFile> iterator = acceleoFiles.iterator(); iterator.hasNext();) { AcceleoFile acceleoFile = iterator.next(); AcceleoParserProblems problems = parser.getProblems(acceleoFile); if (problems != null) { List<AcceleoParserProblem> list = problems.getList(); if (!list.isEmpty()) { message.append(acceleoFile.getMtlFile().getName()); message.append('\n'); for (Iterator<AcceleoParserProblem> itProblems = list.iterator(); itProblems.hasNext();) { AcceleoParserProblem problem = itProblems.next(); message.append(problem.getLine()); message.append(':'); message.append(problem.getMessage()); message.append('\n'); } message.append('\n'); } } } if (message.length() > 0) { String log = message.toString(); setDescription(log); log(log, Project.MSG_ERR); } }
diff --git a/core/src/main/java/hudson/tasks/CommandInterpreter.java b/core/src/main/java/hudson/tasks/CommandInterpreter.java index c70ddd8a7..438f9a965 100644 --- a/core/src/main/java/hudson/tasks/CommandInterpreter.java +++ b/core/src/main/java/hudson/tasks/CommandInterpreter.java @@ -1,71 +1,71 @@ package hudson.tasks; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Project; import hudson.Launcher; import hudson.FilePath; import hudson.Util; import java.io.IOException; /** * Common part between {@link Shell} and {@link BatchFile}. * * @author Kohsuke Kawaguchi */ public abstract class CommandInterpreter extends Builder { /** * Command to execute. The format depends on the actual {@link CommandInterpreter} implementation. */ protected final String command; public CommandInterpreter(String command) { this.command = command; } public final String getCommand() { return command; } public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException { Project proj = build.getProject(); FilePath ws = proj.getWorkspace(); FilePath script=null; try { try { - script = ws.createTextTempFile("hudson", getFileExtension(), getContents()); + script = ws.createTextTempFile("hudson", getFileExtension(), getContents(), false); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("Unable to produce a script file") ); return false; } String[] cmd = buildCommandLine(script); int r; try { r = launcher.launch(cmd,build.getEnvVars(),listener.getLogger(),ws).join(); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("command execution failed") ); r = -1; } return r==0; } finally { try { if(script!=null) script.delete(); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("Unable to delete script file "+script) ); } } } protected abstract String[] buildCommandLine(FilePath script); protected abstract String getContents(); protected abstract String getFileExtension(); }
true
true
public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException { Project proj = build.getProject(); FilePath ws = proj.getWorkspace(); FilePath script=null; try { try { script = ws.createTextTempFile("hudson", getFileExtension(), getContents()); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("Unable to produce a script file") ); return false; } String[] cmd = buildCommandLine(script); int r; try { r = launcher.launch(cmd,build.getEnvVars(),listener.getLogger(),ws).join(); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("command execution failed") ); r = -1; } return r==0; } finally { try { if(script!=null) script.delete(); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("Unable to delete script file "+script) ); } } }
public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException { Project proj = build.getProject(); FilePath ws = proj.getWorkspace(); FilePath script=null; try { try { script = ws.createTextTempFile("hudson", getFileExtension(), getContents(), false); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("Unable to produce a script file") ); return false; } String[] cmd = buildCommandLine(script); int r; try { r = launcher.launch(cmd,build.getEnvVars(),listener.getLogger(),ws).join(); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("command execution failed") ); r = -1; } return r==0; } finally { try { if(script!=null) script.delete(); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace( listener.fatalError("Unable to delete script file "+script) ); } } }
diff --git a/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java b/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java index 28650fcae..7e1db0d9d 100644 --- a/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java +++ b/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java @@ -1,609 +1,609 @@ /* * 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.android.internal.telephony.cdma; import com.android.internal.telephony.TelephonyProperties; import com.android.internal.telephony.MccTable; import com.android.internal.telephony.EventLogTags; import com.android.internal.telephony.uicc.RuimRecords; import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppState; import android.telephony.CellInfo; import android.telephony.CellInfoLte; import android.telephony.CellSignalStrengthLte; import android.telephony.CellIdentityLte; import android.telephony.SignalStrength; import android.telephony.ServiceState; import android.telephony.cdma.CdmaCellLocation; import android.text.TextUtils; import android.os.AsyncResult; import android.os.Message; import android.os.SystemClock; import android.os.SystemProperties; import android.telephony.Rlog; import android.util.EventLog; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class CdmaLteServiceStateTracker extends CdmaServiceStateTracker { private CDMALTEPhone mCdmaLtePhone; private final CellInfoLte mCellInfoLte; protected int mNewRilRadioTechnology = 0; private CellIdentityLte mNewCellIdentityLte = new CellIdentityLte(); private CellIdentityLte mLasteCellIdentityLte = new CellIdentityLte(); public CdmaLteServiceStateTracker(CDMALTEPhone phone) { super(phone, new CellInfoLte()); mCdmaLtePhone = phone; mCellInfoLte = (CellInfoLte) mCellInfo; ((CellInfoLte)mCellInfo).setCellSignalStrength(new CellSignalStrengthLte()); ((CellInfoLte)mCellInfo).setCellIdentity(new CellIdentityLte()); if (DBG) log("CdmaLteServiceStateTracker Constructors"); } @Override public void handleMessage(Message msg) { AsyncResult ar; int[] ints; String[] strings; if (!mPhone.mIsTheCurrentActivePhone) { loge("Received message " + msg + "[" + msg.what + "]" + " while being destroyed. Ignoring."); return; } switch (msg.what) { case EVENT_POLL_STATE_GPRS: if (DBG) log("handleMessage EVENT_POLL_STATE_GPRS"); ar = (AsyncResult)msg.obj; handlePollStateResult(msg.what, ar); break; case EVENT_RUIM_RECORDS_LOADED: updatePhoneObject(); RuimRecords ruim = (RuimRecords)mIccRecords; if ((ruim != null) && ruim.isProvisioned()) { mMdn = ruim.getMdn(); mMin = ruim.getMin(); parseSidNid(ruim.getSid(), ruim.getNid()); mPrlVersion = ruim.getPrlVersion(); mIsMinInfoReady = true; updateOtaspState(); } // SID/NID/PRL is loaded. Poll service state // again to update to the roaming state with // the latest variables. pollState(); break; default: super.handleMessage(msg); } } /** * Handle the result of one of the pollState()-related requests */ @Override protected void handlePollStateResultMessage(int what, AsyncResult ar) { if (what == EVENT_POLL_STATE_GPRS) { String states[] = (String[])ar.result; if (DBG) { log("handlePollStateResultMessage: EVENT_POLL_STATE_GPRS states.length=" + states.length + " states=" + states); } int type = 0; int regState = -1; if (states.length > 0) { try { regState = Integer.parseInt(states[0]); // states[3] (if present) is the current radio technology if (states.length >= 4 && states[3] != null) { type = Integer.parseInt(states[3]); } } catch (NumberFormatException ex) { loge("handlePollStateResultMessage: error parsing GprsRegistrationState: " + ex); } if (states.length >= 10) { int mcc; int mnc; int tac; int pci; int eci; int csgid; String operatorNumeric = null; try { operatorNumeric = mNewSS.getOperatorNumeric(); mcc = Integer.parseInt(operatorNumeric.substring(0,3)); } catch (Exception e) { try { operatorNumeric = mSS.getOperatorNumeric(); mcc = Integer.parseInt(operatorNumeric.substring(0,3)); } catch (Exception ex) { loge("handlePollStateResultMessage: bad mcc operatorNumeric=" + operatorNumeric + " ex=" + ex); operatorNumeric = ""; mcc = Integer.MAX_VALUE; } } try { mnc = Integer.parseInt(operatorNumeric.substring(3)); } catch (Exception e) { loge("handlePollStateResultMessage: bad mnc operatorNumeric=" + operatorNumeric + " e=" + e); mnc = Integer.MAX_VALUE; } // Use Integer#decode to be generous in what we receive and allow // decimal, hex or octal values. try { tac = Integer.decode(states[6]); } catch (Exception e) { loge("handlePollStateResultMessage: bad tac states[6]=" + states[6] + " e=" + e); tac = Integer.MAX_VALUE; } try { pci = Integer.decode(states[7]); } catch (Exception e) { loge("handlePollStateResultMessage: bad pci states[7]=" + states[7] + " e=" + e); pci = Integer.MAX_VALUE; } try { eci = Integer.decode(states[8]); } catch (Exception e) { loge("handlePollStateResultMessage: bad eci states[8]=" + states[8] + " e=" + e); eci = Integer.MAX_VALUE; } try { csgid = Integer.decode(states[9]); } catch (Exception e) { // FIX: Always bad so don't pollute the logs // loge("handlePollStateResultMessage: bad csgid states[9]=" + // states[9] + " e=" + e); csgid = Integer.MAX_VALUE; } mNewCellIdentityLte = new CellIdentityLte(mcc, mnc, eci, pci, tac); if (DBG) { log("handlePollStateResultMessage: mNewLteCellIdentity=" + mNewCellIdentityLte); } } } mNewSS.setRilDataRadioTechnology(type); int dataRegState = regCodeToServiceState(regState); mNewSS.setDataRegState(dataRegState); if (DBG) { log("handlPollStateResultMessage: CdmaLteSST setDataRegState=" + dataRegState + " regState=" + regState + " dataRadioTechnology=" + type); } } else { super.handlePollStateResultMessage(what, ar); } } @Override protected void pollState() { mPollingContext = new int[1]; mPollingContext[0] = 0; switch (mCi.getRadioState()) { case RADIO_UNAVAILABLE: mNewSS.setStateOutOfService(); mNewCellLoc.setStateInvalid(); setSignalStrengthDefaultValues(); mGotCountryCode = false; pollStateDone(); break; case RADIO_OFF: mNewSS.setStateOff(); mNewCellLoc.setStateInvalid(); setSignalStrengthDefaultValues(); mGotCountryCode = false; pollStateDone(); break; default: // Issue all poll-related commands at once, then count // down the responses which are allowed to arrive // out-of-order. mPollingContext[0]++; // RIL_REQUEST_OPERATOR is necessary for CDMA mCi.getOperator(obtainMessage(EVENT_POLL_STATE_OPERATOR_CDMA, mPollingContext)); mPollingContext[0]++; // RIL_REQUEST_VOICE_REGISTRATION_STATE is necessary for CDMA mCi.getVoiceRegistrationState(obtainMessage(EVENT_POLL_STATE_REGISTRATION_CDMA, mPollingContext)); mPollingContext[0]++; // RIL_REQUEST_DATA_REGISTRATION_STATE mCi.getDataRegistrationState(obtainMessage(EVENT_POLL_STATE_GPRS, mPollingContext)); break; } } @Override protected void pollStateDone() { // Some older CDMA/LTE RILs only report VoiceRadioTechnology which results in network // Unknown. In these cases return RilVoiceRadioTechnology for RilDataRadioTechnology. boolean oldRil = mCi.needsOldRilFeature("usevoicetechfordata"); if (mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE && oldRil) { // LTE out of service, get CDMA Service State mNewRilRadioTechnology = mNewSS.getRilVoiceRadioTechnology(); mNewSS.setDataRegState(radioTechnologyToDataServiceState(mNewRilRadioTechnology)); mNewSS.setRilDataRadioTechnology(mNewRilRadioTechnology); log("pollStateDone CDMA STATE_IN_SERVICE mNewRilRadioTechnology = " + mNewRilRadioTechnology + " mNewSS.getDataRegState() = " + mNewSS.getDataRegState()); } log("pollStateDone: lte 1 ss=[" + mSS + "] newSS=[" + mNewSS + "]"); useDataRegStateForDataOnlyDevices(); boolean hasRegistered = mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE && mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE; boolean hasDeregistered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE && mNewSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionAttached = mSS.getDataRegState() != ServiceState.STATE_IN_SERVICE && mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionDetached = mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE && mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionChanged = mSS.getDataRegState() != mNewSS.getDataRegState(); boolean hasVoiceRadioTechnologyChanged = mSS.getRilVoiceRadioTechnology() != mNewSS.getRilVoiceRadioTechnology(); boolean hasDataRadioTechnologyChanged = mSS.getRilDataRadioTechnology() != mNewSS.getRilDataRadioTechnology(); boolean hasChanged = !mNewSS.equals(mSS); boolean hasRoamingOn = !mSS.getRoaming() && mNewSS.getRoaming(); boolean hasRoamingOff = mSS.getRoaming() && !mNewSS.getRoaming(); boolean hasLocationChanged = !mNewCellLoc.equals(mCellLoc); boolean has4gHandoff = mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE && (((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) && (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) || ((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD) && (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE))); boolean hasMultiApnSupport = (((mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) || (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) && ((mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_LTE) && (mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD))); boolean hasLostMultiApnSupport = ((mNewSS.getRilDataRadioTechnology() >= ServiceState.RIL_RADIO_TECHNOLOGY_IS95A) && (mNewSS.getRilDataRadioTechnology() <= ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A)); if (DBG) { log("pollStateDone:" + " hasRegistered=" + hasRegistered + " hasDeegistered=" + hasDeregistered + " hasCdmaDataConnectionAttached=" + hasCdmaDataConnectionAttached + " hasCdmaDataConnectionDetached=" + hasCdmaDataConnectionDetached + " hasCdmaDataConnectionChanged=" + hasCdmaDataConnectionChanged + " hasVoiceRadioTechnologyChanged= " + hasVoiceRadioTechnologyChanged + " hasDataRadioTechnologyChanged=" + hasDataRadioTechnologyChanged + " hasChanged=" + hasChanged + " hasRoamingOn=" + hasRoamingOn + " hasRoamingOff=" + hasRoamingOff + " hasLocationChanged=" + hasLocationChanged + " has4gHandoff = " + has4gHandoff + " hasMultiApnSupport=" + hasMultiApnSupport + " hasLostMultiApnSupport=" + hasLostMultiApnSupport); } // Add an event log when connection state changes if (mSS.getVoiceRegState() != mNewSS.getVoiceRegState() || mSS.getDataRegState() != mNewSS.getDataRegState()) { EventLog.writeEvent(EventLogTags.CDMA_SERVICE_STATE_CHANGE, mSS.getVoiceRegState(), mSS.getDataRegState(), mNewSS.getVoiceRegState(), mNewSS.getDataRegState()); } ServiceState tss; tss = mSS; mSS = mNewSS; mNewSS = tss; // clean slate for next time mNewSS.setStateOutOfService(); CdmaCellLocation tcl = mCellLoc; mCellLoc = mNewCellLoc; mNewCellLoc = tcl; mNewSS.setStateOutOfService(); // clean slate for next time if (hasVoiceRadioTechnologyChanged) { updatePhoneObject(); } if (hasDataRadioTechnologyChanged) { mPhone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE, ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology())); // Query Signalstrength when there is a change in PS RAT. sendMessage(obtainMessage(EVENT_POLL_SIGNAL_STRENGTH)); } if (hasRegistered) { mNetworkAttachedRegistrants.notifyRegistrants(); } if (hasChanged) { - if (mPhone.isEriFileLoaded()) { + if ((mCi.getRadioState().isOn()) && (mPhone.isEriFileLoaded())) { String eriText; // Now the CDMAPhone sees the new ServiceState so it can get the // new ERI text if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE) { eriText = mPhone.getCdmaEriText(); } else if (mSS.getVoiceRegState() == ServiceState.STATE_POWER_OFF) { eriText = (mIccRecords != null) ? mIccRecords.getServiceProviderName() : null; if (TextUtils.isEmpty(eriText)) { // Sets operator alpha property by retrieving from // build-time system property eriText = SystemProperties.get("ro.cdma.home.operator.alpha"); } } else { // Note that ServiceState.STATE_OUT_OF_SERVICE is valid used // for mRegistrationState 0,2,3 and 4 eriText = mPhone.getContext() .getText(com.android.internal.R.string.roamingTextSearching).toString(); } mSS.setOperatorAlphaLong(eriText); } if (mUiccApplcation != null && mUiccApplcation.getState() == AppState.APPSTATE_READY && mIccRecords != null) { // SIM is found on the device. If ERI roaming is OFF, and SID/NID matches // one configured in SIM, use operator name from CSIM record. boolean showSpn = ((RuimRecords)mIccRecords).getCsimSpnDisplayCondition(); int iconIndex = mSS.getCdmaEriIconIndex(); if (showSpn && (iconIndex == EriInfo.ROAMING_INDICATOR_OFF) && isInHomeSidNid(mSS.getSystemId(), mSS.getNetworkId()) && mIccRecords != null) { mSS.setOperatorAlphaLong(mIccRecords.getServiceProviderName()); } } String operatorNumeric; mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA, mSS.getOperatorAlphaLong()); String prevOperatorNumeric = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, ""); operatorNumeric = mSS.getOperatorNumeric(); mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric); if (operatorNumeric == null) { if (DBG) log("operatorNumeric is null"); mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, ""); mGotCountryCode = false; } else { String isoCountryCode = ""; String mcc = operatorNumeric.substring(0, 3); try { isoCountryCode = MccTable.countryCodeForMcc(Integer.parseInt(operatorNumeric .substring(0, 3))); } catch (NumberFormatException ex) { loge("countryCodeForMcc error" + ex); } catch (StringIndexOutOfBoundsException ex) { loge("countryCodeForMcc error" + ex); } mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, isoCountryCode); mGotCountryCode = true; if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric, mNeedFixZone)) { fixTimeZone(isoCountryCode); } } mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING, mSS.getRoaming() ? "true" : "false"); updateSpnDisplay(); mPhone.notifyServiceStateChanged(mSS); } if (hasCdmaDataConnectionAttached || has4gHandoff) { mAttachedRegistrants.notifyRegistrants(); } if (hasCdmaDataConnectionDetached) { mDetachedRegistrants.notifyRegistrants(); } if ((hasCdmaDataConnectionChanged || hasDataRadioTechnologyChanged)) { notifyDataRegStateRilRadioTechnologyChanged(); mPhone.notifyDataConnection(null); } if (hasRoamingOn) { mRoamingOnRegistrants.notifyRegistrants(); } if (hasRoamingOff) { mRoamingOffRegistrants.notifyRegistrants(); } if (hasLocationChanged) { mPhone.notifyLocationChanged(); } ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>(); synchronized(mCellInfo) { CellInfoLte cil = (CellInfoLte)mCellInfo; boolean cidChanged = ! mNewCellIdentityLte.equals(mLasteCellIdentityLte); if (hasRegistered || hasDeregistered || cidChanged) { // TODO: Handle the absence of LteCellIdentity long timeStamp = SystemClock.elapsedRealtime() * 1000; boolean registered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE; mLasteCellIdentityLte = mNewCellIdentityLte; cil.setRegisterd(registered); cil.setCellIdentity(mLasteCellIdentityLte); if (DBG) { log("pollStateDone: hasRegistered=" + hasRegistered + " hasDeregistered=" + hasDeregistered + " cidChanged=" + cidChanged + " mCellInfo=" + mCellInfo); } arrayCi.add(mCellInfo); } mPhoneBase.notifyCellInfo(arrayCi); } } @Override protected boolean onSignalStrengthResult(AsyncResult ar, boolean isGsm) { if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) { isGsm = true; } boolean ssChanged = super.onSignalStrengthResult(ar, isGsm); synchronized (mCellInfo) { if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) { mCellInfoLte.setTimeStamp(SystemClock.elapsedRealtime() * 1000); mCellInfoLte.setTimeStampType(CellInfo.TIMESTAMP_TYPE_JAVA_RIL); mCellInfoLte.getCellSignalStrength() .initialize(mSignalStrength,SignalStrength.INVALID); } if (mCellInfoLte.getCellIdentity() != null) { ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>(); arrayCi.add(mCellInfoLte); mPhoneBase.notifyCellInfo(arrayCi); } } return ssChanged; } @Override public boolean isConcurrentVoiceAndDataAllowed() { // For LTE set true, else if the SVDO property is set, else use the CSS indicator to // check for concurrent voice and data capability if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) { return true; } else if (SystemProperties.getBoolean(TelephonyProperties.PROPERTY_SVDO, false)) { return true; } else { return mSS.getCssIndicator() == 1; } } /** * Check whether the specified SID and NID pair appears in the HOME SID/NID list * read from NV or SIM. * * @return true if provided sid/nid pair belongs to operator's home network. */ private boolean isInHomeSidNid(int sid, int nid) { // if SID/NID is not available, assume this is home network. if (isSidsAllZeros()) return true; // length of SID/NID shold be same if (mHomeSystemId.length != mHomeNetworkId.length) return true; if (sid == 0) return true; for (int i = 0; i < mHomeSystemId.length; i++) { // Use SID only if NID is a reserved value. // SID 0 and NID 0 and 65535 are reserved. (C.0005 2.6.5.2) if ((mHomeSystemId[i] == sid) && ((mHomeNetworkId[i] == 0) || (mHomeNetworkId[i] == 65535) || (nid == 0) || (nid == 65535) || (mHomeNetworkId[i] == nid))) { return true; } } // SID/NID are not in the list. So device is not in home network return false; } /** * TODO: Remove when we get new ril/modem for Galaxy Nexus. * * @return all available cell information, the returned List maybe empty but never null. */ @Override public List<CellInfo> getAllCellInfo() { if (mCi.getRilVersion() >= 8) { return super.getAllCellInfo(); } else { ArrayList<CellInfo> arrayList = new ArrayList<CellInfo>(); CellInfo ci; synchronized(mCellInfo) { arrayList.add(mCellInfoLte); } if (DBG) log ("getAllCellInfo: arrayList=" + arrayList); return arrayList; } } @Override protected void log(String s) { Rlog.d(LOG_TAG, "[CdmaLteSST] " + s); } @Override protected void loge(String s) { Rlog.e(LOG_TAG, "[CdmaLteSST] " + s); } @Override public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { pw.println("CdmaLteServiceStateTracker extends:"); super.dump(fd, pw, args); pw.println(" mCdmaLtePhone=" + mCdmaLtePhone); } }
true
true
protected void pollStateDone() { // Some older CDMA/LTE RILs only report VoiceRadioTechnology which results in network // Unknown. In these cases return RilVoiceRadioTechnology for RilDataRadioTechnology. boolean oldRil = mCi.needsOldRilFeature("usevoicetechfordata"); if (mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE && oldRil) { // LTE out of service, get CDMA Service State mNewRilRadioTechnology = mNewSS.getRilVoiceRadioTechnology(); mNewSS.setDataRegState(radioTechnologyToDataServiceState(mNewRilRadioTechnology)); mNewSS.setRilDataRadioTechnology(mNewRilRadioTechnology); log("pollStateDone CDMA STATE_IN_SERVICE mNewRilRadioTechnology = " + mNewRilRadioTechnology + " mNewSS.getDataRegState() = " + mNewSS.getDataRegState()); } log("pollStateDone: lte 1 ss=[" + mSS + "] newSS=[" + mNewSS + "]"); useDataRegStateForDataOnlyDevices(); boolean hasRegistered = mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE && mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE; boolean hasDeregistered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE && mNewSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionAttached = mSS.getDataRegState() != ServiceState.STATE_IN_SERVICE && mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionDetached = mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE && mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionChanged = mSS.getDataRegState() != mNewSS.getDataRegState(); boolean hasVoiceRadioTechnologyChanged = mSS.getRilVoiceRadioTechnology() != mNewSS.getRilVoiceRadioTechnology(); boolean hasDataRadioTechnologyChanged = mSS.getRilDataRadioTechnology() != mNewSS.getRilDataRadioTechnology(); boolean hasChanged = !mNewSS.equals(mSS); boolean hasRoamingOn = !mSS.getRoaming() && mNewSS.getRoaming(); boolean hasRoamingOff = mSS.getRoaming() && !mNewSS.getRoaming(); boolean hasLocationChanged = !mNewCellLoc.equals(mCellLoc); boolean has4gHandoff = mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE && (((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) && (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) || ((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD) && (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE))); boolean hasMultiApnSupport = (((mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) || (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) && ((mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_LTE) && (mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD))); boolean hasLostMultiApnSupport = ((mNewSS.getRilDataRadioTechnology() >= ServiceState.RIL_RADIO_TECHNOLOGY_IS95A) && (mNewSS.getRilDataRadioTechnology() <= ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A)); if (DBG) { log("pollStateDone:" + " hasRegistered=" + hasRegistered + " hasDeegistered=" + hasDeregistered + " hasCdmaDataConnectionAttached=" + hasCdmaDataConnectionAttached + " hasCdmaDataConnectionDetached=" + hasCdmaDataConnectionDetached + " hasCdmaDataConnectionChanged=" + hasCdmaDataConnectionChanged + " hasVoiceRadioTechnologyChanged= " + hasVoiceRadioTechnologyChanged + " hasDataRadioTechnologyChanged=" + hasDataRadioTechnologyChanged + " hasChanged=" + hasChanged + " hasRoamingOn=" + hasRoamingOn + " hasRoamingOff=" + hasRoamingOff + " hasLocationChanged=" + hasLocationChanged + " has4gHandoff = " + has4gHandoff + " hasMultiApnSupport=" + hasMultiApnSupport + " hasLostMultiApnSupport=" + hasLostMultiApnSupport); } // Add an event log when connection state changes if (mSS.getVoiceRegState() != mNewSS.getVoiceRegState() || mSS.getDataRegState() != mNewSS.getDataRegState()) { EventLog.writeEvent(EventLogTags.CDMA_SERVICE_STATE_CHANGE, mSS.getVoiceRegState(), mSS.getDataRegState(), mNewSS.getVoiceRegState(), mNewSS.getDataRegState()); } ServiceState tss; tss = mSS; mSS = mNewSS; mNewSS = tss; // clean slate for next time mNewSS.setStateOutOfService(); CdmaCellLocation tcl = mCellLoc; mCellLoc = mNewCellLoc; mNewCellLoc = tcl; mNewSS.setStateOutOfService(); // clean slate for next time if (hasVoiceRadioTechnologyChanged) { updatePhoneObject(); } if (hasDataRadioTechnologyChanged) { mPhone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE, ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology())); // Query Signalstrength when there is a change in PS RAT. sendMessage(obtainMessage(EVENT_POLL_SIGNAL_STRENGTH)); } if (hasRegistered) { mNetworkAttachedRegistrants.notifyRegistrants(); } if (hasChanged) { if (mPhone.isEriFileLoaded()) { String eriText; // Now the CDMAPhone sees the new ServiceState so it can get the // new ERI text if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE) { eriText = mPhone.getCdmaEriText(); } else if (mSS.getVoiceRegState() == ServiceState.STATE_POWER_OFF) { eriText = (mIccRecords != null) ? mIccRecords.getServiceProviderName() : null; if (TextUtils.isEmpty(eriText)) { // Sets operator alpha property by retrieving from // build-time system property eriText = SystemProperties.get("ro.cdma.home.operator.alpha"); } } else { // Note that ServiceState.STATE_OUT_OF_SERVICE is valid used // for mRegistrationState 0,2,3 and 4 eriText = mPhone.getContext() .getText(com.android.internal.R.string.roamingTextSearching).toString(); } mSS.setOperatorAlphaLong(eriText); } if (mUiccApplcation != null && mUiccApplcation.getState() == AppState.APPSTATE_READY && mIccRecords != null) { // SIM is found on the device. If ERI roaming is OFF, and SID/NID matches // one configured in SIM, use operator name from CSIM record. boolean showSpn = ((RuimRecords)mIccRecords).getCsimSpnDisplayCondition(); int iconIndex = mSS.getCdmaEriIconIndex(); if (showSpn && (iconIndex == EriInfo.ROAMING_INDICATOR_OFF) && isInHomeSidNid(mSS.getSystemId(), mSS.getNetworkId()) && mIccRecords != null) { mSS.setOperatorAlphaLong(mIccRecords.getServiceProviderName()); } } String operatorNumeric; mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA, mSS.getOperatorAlphaLong()); String prevOperatorNumeric = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, ""); operatorNumeric = mSS.getOperatorNumeric(); mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric); if (operatorNumeric == null) { if (DBG) log("operatorNumeric is null"); mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, ""); mGotCountryCode = false; } else { String isoCountryCode = ""; String mcc = operatorNumeric.substring(0, 3); try { isoCountryCode = MccTable.countryCodeForMcc(Integer.parseInt(operatorNumeric .substring(0, 3))); } catch (NumberFormatException ex) { loge("countryCodeForMcc error" + ex); } catch (StringIndexOutOfBoundsException ex) { loge("countryCodeForMcc error" + ex); } mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, isoCountryCode); mGotCountryCode = true; if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric, mNeedFixZone)) { fixTimeZone(isoCountryCode); } } mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING, mSS.getRoaming() ? "true" : "false"); updateSpnDisplay(); mPhone.notifyServiceStateChanged(mSS); } if (hasCdmaDataConnectionAttached || has4gHandoff) { mAttachedRegistrants.notifyRegistrants(); } if (hasCdmaDataConnectionDetached) { mDetachedRegistrants.notifyRegistrants(); } if ((hasCdmaDataConnectionChanged || hasDataRadioTechnologyChanged)) { notifyDataRegStateRilRadioTechnologyChanged(); mPhone.notifyDataConnection(null); } if (hasRoamingOn) { mRoamingOnRegistrants.notifyRegistrants(); } if (hasRoamingOff) { mRoamingOffRegistrants.notifyRegistrants(); } if (hasLocationChanged) { mPhone.notifyLocationChanged(); } ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>(); synchronized(mCellInfo) { CellInfoLte cil = (CellInfoLte)mCellInfo; boolean cidChanged = ! mNewCellIdentityLte.equals(mLasteCellIdentityLte); if (hasRegistered || hasDeregistered || cidChanged) { // TODO: Handle the absence of LteCellIdentity long timeStamp = SystemClock.elapsedRealtime() * 1000; boolean registered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE; mLasteCellIdentityLte = mNewCellIdentityLte; cil.setRegisterd(registered); cil.setCellIdentity(mLasteCellIdentityLte); if (DBG) { log("pollStateDone: hasRegistered=" + hasRegistered + " hasDeregistered=" + hasDeregistered + " cidChanged=" + cidChanged + " mCellInfo=" + mCellInfo); } arrayCi.add(mCellInfo); } mPhoneBase.notifyCellInfo(arrayCi); } }
protected void pollStateDone() { // Some older CDMA/LTE RILs only report VoiceRadioTechnology which results in network // Unknown. In these cases return RilVoiceRadioTechnology for RilDataRadioTechnology. boolean oldRil = mCi.needsOldRilFeature("usevoicetechfordata"); if (mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE && oldRil) { // LTE out of service, get CDMA Service State mNewRilRadioTechnology = mNewSS.getRilVoiceRadioTechnology(); mNewSS.setDataRegState(radioTechnologyToDataServiceState(mNewRilRadioTechnology)); mNewSS.setRilDataRadioTechnology(mNewRilRadioTechnology); log("pollStateDone CDMA STATE_IN_SERVICE mNewRilRadioTechnology = " + mNewRilRadioTechnology + " mNewSS.getDataRegState() = " + mNewSS.getDataRegState()); } log("pollStateDone: lte 1 ss=[" + mSS + "] newSS=[" + mNewSS + "]"); useDataRegStateForDataOnlyDevices(); boolean hasRegistered = mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE && mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE; boolean hasDeregistered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE && mNewSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionAttached = mSS.getDataRegState() != ServiceState.STATE_IN_SERVICE && mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionDetached = mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE && mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE; boolean hasCdmaDataConnectionChanged = mSS.getDataRegState() != mNewSS.getDataRegState(); boolean hasVoiceRadioTechnologyChanged = mSS.getRilVoiceRadioTechnology() != mNewSS.getRilVoiceRadioTechnology(); boolean hasDataRadioTechnologyChanged = mSS.getRilDataRadioTechnology() != mNewSS.getRilDataRadioTechnology(); boolean hasChanged = !mNewSS.equals(mSS); boolean hasRoamingOn = !mSS.getRoaming() && mNewSS.getRoaming(); boolean hasRoamingOff = mSS.getRoaming() && !mNewSS.getRoaming(); boolean hasLocationChanged = !mNewCellLoc.equals(mCellLoc); boolean has4gHandoff = mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE && (((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) && (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) || ((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD) && (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE))); boolean hasMultiApnSupport = (((mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) || (mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) && ((mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_LTE) && (mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD))); boolean hasLostMultiApnSupport = ((mNewSS.getRilDataRadioTechnology() >= ServiceState.RIL_RADIO_TECHNOLOGY_IS95A) && (mNewSS.getRilDataRadioTechnology() <= ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A)); if (DBG) { log("pollStateDone:" + " hasRegistered=" + hasRegistered + " hasDeegistered=" + hasDeregistered + " hasCdmaDataConnectionAttached=" + hasCdmaDataConnectionAttached + " hasCdmaDataConnectionDetached=" + hasCdmaDataConnectionDetached + " hasCdmaDataConnectionChanged=" + hasCdmaDataConnectionChanged + " hasVoiceRadioTechnologyChanged= " + hasVoiceRadioTechnologyChanged + " hasDataRadioTechnologyChanged=" + hasDataRadioTechnologyChanged + " hasChanged=" + hasChanged + " hasRoamingOn=" + hasRoamingOn + " hasRoamingOff=" + hasRoamingOff + " hasLocationChanged=" + hasLocationChanged + " has4gHandoff = " + has4gHandoff + " hasMultiApnSupport=" + hasMultiApnSupport + " hasLostMultiApnSupport=" + hasLostMultiApnSupport); } // Add an event log when connection state changes if (mSS.getVoiceRegState() != mNewSS.getVoiceRegState() || mSS.getDataRegState() != mNewSS.getDataRegState()) { EventLog.writeEvent(EventLogTags.CDMA_SERVICE_STATE_CHANGE, mSS.getVoiceRegState(), mSS.getDataRegState(), mNewSS.getVoiceRegState(), mNewSS.getDataRegState()); } ServiceState tss; tss = mSS; mSS = mNewSS; mNewSS = tss; // clean slate for next time mNewSS.setStateOutOfService(); CdmaCellLocation tcl = mCellLoc; mCellLoc = mNewCellLoc; mNewCellLoc = tcl; mNewSS.setStateOutOfService(); // clean slate for next time if (hasVoiceRadioTechnologyChanged) { updatePhoneObject(); } if (hasDataRadioTechnologyChanged) { mPhone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE, ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology())); // Query Signalstrength when there is a change in PS RAT. sendMessage(obtainMessage(EVENT_POLL_SIGNAL_STRENGTH)); } if (hasRegistered) { mNetworkAttachedRegistrants.notifyRegistrants(); } if (hasChanged) { if ((mCi.getRadioState().isOn()) && (mPhone.isEriFileLoaded())) { String eriText; // Now the CDMAPhone sees the new ServiceState so it can get the // new ERI text if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE) { eriText = mPhone.getCdmaEriText(); } else if (mSS.getVoiceRegState() == ServiceState.STATE_POWER_OFF) { eriText = (mIccRecords != null) ? mIccRecords.getServiceProviderName() : null; if (TextUtils.isEmpty(eriText)) { // Sets operator alpha property by retrieving from // build-time system property eriText = SystemProperties.get("ro.cdma.home.operator.alpha"); } } else { // Note that ServiceState.STATE_OUT_OF_SERVICE is valid used // for mRegistrationState 0,2,3 and 4 eriText = mPhone.getContext() .getText(com.android.internal.R.string.roamingTextSearching).toString(); } mSS.setOperatorAlphaLong(eriText); } if (mUiccApplcation != null && mUiccApplcation.getState() == AppState.APPSTATE_READY && mIccRecords != null) { // SIM is found on the device. If ERI roaming is OFF, and SID/NID matches // one configured in SIM, use operator name from CSIM record. boolean showSpn = ((RuimRecords)mIccRecords).getCsimSpnDisplayCondition(); int iconIndex = mSS.getCdmaEriIconIndex(); if (showSpn && (iconIndex == EriInfo.ROAMING_INDICATOR_OFF) && isInHomeSidNid(mSS.getSystemId(), mSS.getNetworkId()) && mIccRecords != null) { mSS.setOperatorAlphaLong(mIccRecords.getServiceProviderName()); } } String operatorNumeric; mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA, mSS.getOperatorAlphaLong()); String prevOperatorNumeric = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, ""); operatorNumeric = mSS.getOperatorNumeric(); mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric); if (operatorNumeric == null) { if (DBG) log("operatorNumeric is null"); mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, ""); mGotCountryCode = false; } else { String isoCountryCode = ""; String mcc = operatorNumeric.substring(0, 3); try { isoCountryCode = MccTable.countryCodeForMcc(Integer.parseInt(operatorNumeric .substring(0, 3))); } catch (NumberFormatException ex) { loge("countryCodeForMcc error" + ex); } catch (StringIndexOutOfBoundsException ex) { loge("countryCodeForMcc error" + ex); } mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, isoCountryCode); mGotCountryCode = true; if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric, mNeedFixZone)) { fixTimeZone(isoCountryCode); } } mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING, mSS.getRoaming() ? "true" : "false"); updateSpnDisplay(); mPhone.notifyServiceStateChanged(mSS); } if (hasCdmaDataConnectionAttached || has4gHandoff) { mAttachedRegistrants.notifyRegistrants(); } if (hasCdmaDataConnectionDetached) { mDetachedRegistrants.notifyRegistrants(); } if ((hasCdmaDataConnectionChanged || hasDataRadioTechnologyChanged)) { notifyDataRegStateRilRadioTechnologyChanged(); mPhone.notifyDataConnection(null); } if (hasRoamingOn) { mRoamingOnRegistrants.notifyRegistrants(); } if (hasRoamingOff) { mRoamingOffRegistrants.notifyRegistrants(); } if (hasLocationChanged) { mPhone.notifyLocationChanged(); } ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>(); synchronized(mCellInfo) { CellInfoLte cil = (CellInfoLte)mCellInfo; boolean cidChanged = ! mNewCellIdentityLte.equals(mLasteCellIdentityLte); if (hasRegistered || hasDeregistered || cidChanged) { // TODO: Handle the absence of LteCellIdentity long timeStamp = SystemClock.elapsedRealtime() * 1000; boolean registered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE; mLasteCellIdentityLte = mNewCellIdentityLte; cil.setRegisterd(registered); cil.setCellIdentity(mLasteCellIdentityLte); if (DBG) { log("pollStateDone: hasRegistered=" + hasRegistered + " hasDeregistered=" + hasDeregistered + " cidChanged=" + cidChanged + " mCellInfo=" + mCellInfo); } arrayCi.add(mCellInfo); } mPhoneBase.notifyCellInfo(arrayCi); } }
diff --git a/src/migration/java/org/infoscoop/batch/migration/v200to210/WidgetConfConvertTask.java b/src/migration/java/org/infoscoop/batch/migration/v200to210/WidgetConfConvertTask.java index ae040b1d..ec97bcd3 100644 --- a/src/migration/java/org/infoscoop/batch/migration/v200to210/WidgetConfConvertTask.java +++ b/src/migration/java/org/infoscoop/batch/migration/v200to210/WidgetConfConvertTask.java @@ -1,72 +1,72 @@ package org.infoscoop.batch.migration.v200to210; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.infoscoop.batch.migration.HibernateBeansTask; import org.infoscoop.dao.model.WidgetConf; import org.infoscoop.util.XmlUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class WidgetConfConvertTask implements HibernateBeansTask.BeanTask2 { public WidgetConfConvertTask() { } public void execute(Project project, Object object) throws BuildException { WidgetConf bean = (WidgetConf) object; try { if("FragmentMiniBrowser".equals(bean.getType())){ Document doc = (Document) XmlUtil.string2Dom(bean.getData()); Element newUserPref = doc.createElement("UserPref"); newUserPref.setAttribute("default_value", ""); newUserPref.setAttribute("datatype", "hidden"); newUserPref.setAttribute("name", "additional_css"); newUserPref.setAttribute("display_name", "!{lb_additionalCss}"); newUserPref.setAttribute("admin_datatype", "textarea"); NodeList userPrefs = doc.getElementsByTagName("UserPref"); Node lastUserPref = userPrefs.item(userPrefs.getLength()-1); lastUserPref.getParentNode().insertBefore(newUserPref, lastUserPref.getNextSibling()); bean.setData(XmlUtil.dom2String(doc)); } else if("Message".equals(bean.getType())){ Document doc = (Document) XmlUtil.string2Dom(bean.getData()); NodeList widPrefs = doc.getElementsByTagName("WidgetPref"); int length = widPrefs.getLength(); for(int i=0;i<length;i++){ - Element widPref = (Element)widPrefs.item(length); + Element widPref = (Element)widPrefs.item(i); if(widPref.getAttribute("name").equalsIgnoreCase("broadcastAdminOnly")){ String value = widPref.getAttribute("default_value"); if(value != null && !"".equals(value)){ widPref.setAttribute("value", value); }else{ widPref.setAttribute("value", "false"); } widPref.removeAttribute("default_value"); } } bean.setData(XmlUtil.dom2String(doc)); } } catch (SAXException e) { throw new BuildException(e); } } public void prepare( Project project ) throws BuildException { } public void finish( Project project ) throws BuildException { } }
true
true
public void execute(Project project, Object object) throws BuildException { WidgetConf bean = (WidgetConf) object; try { if("FragmentMiniBrowser".equals(bean.getType())){ Document doc = (Document) XmlUtil.string2Dom(bean.getData()); Element newUserPref = doc.createElement("UserPref"); newUserPref.setAttribute("default_value", ""); newUserPref.setAttribute("datatype", "hidden"); newUserPref.setAttribute("name", "additional_css"); newUserPref.setAttribute("display_name", "!{lb_additionalCss}"); newUserPref.setAttribute("admin_datatype", "textarea"); NodeList userPrefs = doc.getElementsByTagName("UserPref"); Node lastUserPref = userPrefs.item(userPrefs.getLength()-1); lastUserPref.getParentNode().insertBefore(newUserPref, lastUserPref.getNextSibling()); bean.setData(XmlUtil.dom2String(doc)); } else if("Message".equals(bean.getType())){ Document doc = (Document) XmlUtil.string2Dom(bean.getData()); NodeList widPrefs = doc.getElementsByTagName("WidgetPref"); int length = widPrefs.getLength(); for(int i=0;i<length;i++){ Element widPref = (Element)widPrefs.item(length); if(widPref.getAttribute("name").equalsIgnoreCase("broadcastAdminOnly")){ String value = widPref.getAttribute("default_value"); if(value != null && !"".equals(value)){ widPref.setAttribute("value", value); }else{ widPref.setAttribute("value", "false"); } widPref.removeAttribute("default_value"); } } bean.setData(XmlUtil.dom2String(doc)); } } catch (SAXException e) { throw new BuildException(e); } }
public void execute(Project project, Object object) throws BuildException { WidgetConf bean = (WidgetConf) object; try { if("FragmentMiniBrowser".equals(bean.getType())){ Document doc = (Document) XmlUtil.string2Dom(bean.getData()); Element newUserPref = doc.createElement("UserPref"); newUserPref.setAttribute("default_value", ""); newUserPref.setAttribute("datatype", "hidden"); newUserPref.setAttribute("name", "additional_css"); newUserPref.setAttribute("display_name", "!{lb_additionalCss}"); newUserPref.setAttribute("admin_datatype", "textarea"); NodeList userPrefs = doc.getElementsByTagName("UserPref"); Node lastUserPref = userPrefs.item(userPrefs.getLength()-1); lastUserPref.getParentNode().insertBefore(newUserPref, lastUserPref.getNextSibling()); bean.setData(XmlUtil.dom2String(doc)); } else if("Message".equals(bean.getType())){ Document doc = (Document) XmlUtil.string2Dom(bean.getData()); NodeList widPrefs = doc.getElementsByTagName("WidgetPref"); int length = widPrefs.getLength(); for(int i=0;i<length;i++){ Element widPref = (Element)widPrefs.item(i); if(widPref.getAttribute("name").equalsIgnoreCase("broadcastAdminOnly")){ String value = widPref.getAttribute("default_value"); if(value != null && !"".equals(value)){ widPref.setAttribute("value", value); }else{ widPref.setAttribute("value", "false"); } widPref.removeAttribute("default_value"); } } bean.setData(XmlUtil.dom2String(doc)); } } catch (SAXException e) { throw new BuildException(e); } }
diff --git a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java index 1dd4118b..48f92cab 100644 --- a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java +++ b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java @@ -1,763 +1,768 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ethan Hugg * Terry Lucas * Milen Nankov * David P. Caldwell <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript.xmlimpl; import org.mozilla.javascript.*; import org.mozilla.javascript.xml.*; class XMLList extends XMLObjectImpl implements Function { static final long serialVersionUID = -4543618751670781135L; // Fields private XmlNode.List _annos; private XMLObjectImpl targetObject = null; private XmlNode.QName targetProperty = null; XMLList() { _annos = new XmlNode.List(); } /** @deprecated Will probably end up unnecessary as we move things around */ XmlNode.List getNodeList() { return _annos; } // TODO Should be XMLObjectImpl, XMLName? void setTargets(XMLObjectImpl object, XmlNode.QName property) { targetObject = object; targetProperty = property; } /** @deprecated */ private XML getXmlFromAnnotation(int index) { return getXML(_annos, index); } XML XML() { if (length() == 1) return getXmlFromAnnotation(0); return null; } private void internalRemoveFromList(int index) { _annos.remove(index); } void replace(int index, XML xml) { if (index < length()) { XmlNode.List newAnnoList = new XmlNode.List(); newAnnoList.add(_annos, 0, index); newAnnoList.add(xml); newAnnoList.add(_annos, index+1, length()); _annos = newAnnoList; } } private void insert(int index, XML xml) { if (index < length()) { XmlNode.List newAnnoList = new XmlNode.List(); newAnnoList.add(_annos, 0, index); newAnnoList.add(xml); newAnnoList.add(_annos, index, length()); _annos = newAnnoList; } } // // // methods overriding ScriptableObject // // public String getClassName() { return "XMLList"; } // // // methods overriding IdScriptableObject // // public Object get(int index, Scriptable start) { //Log("get index: " + index); if (index >= 0 && index < length()) { return getXmlFromAnnotation(index); } else { return Scriptable.NOT_FOUND; } } boolean hasXMLProperty(XMLName xmlName) { boolean result = false; // Has now should return true if the property would have results > 0 or // if it's a method name String name = xmlName.localName(); if ((getPropertyList(xmlName).length() > 0) || (getMethod(name) != NOT_FOUND)) { result = true; } return result; } public boolean has(int index, Scriptable start) { return 0 <= index && index < length(); } void putXMLProperty(XMLName xmlName, Object value) { //Log("put property: " + name); // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (length() > 1) { throw ScriptRuntime.typeError("Assignment to lists with more than one item is not supported"); } else if (length() == 0) { // Secret sauce for super-expandos. // We set an element here, and then add ourselves to our target. if (targetObject != null && targetProperty != null && targetProperty.getLocalName() != null) { // Add an empty element with our targetProperty name and then set it. XML xmlValue = newTextElementXML(null, targetProperty, null); addToList(xmlValue); if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = (XML)item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, (XML)item(0)); } // Now add us to our parent XMLName name2 = XMLName.formProperty(targetProperty.getUri(), targetProperty.getLocalName()); targetObject.putXMLProperty(name2, this); } else { throw ScriptRuntime.typeError("Assignment to empty XMLList without targets not supported"); } } else if(xmlName.isAttributeName()) { setAttribute(xmlName, value); } else { XML xml = (XML)item(0); xml.putXMLProperty(xmlName, value); // Update the list with the new item at location 0. replace(0, (XML)item(0)); } } Object getXMLProperty(XMLName name) { return getPropertyList(name); } private void replaceNode(XML xml, XML with) { xml.replaceWith(with); } public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = newXMLFromJs(value.toString()); } else { - xmlValue = newTextElementXML(null, targetProperty, value.toString()); + // Note that later in the code, we will use this as an argument to replace(int,value) + // So we will be "replacing" this element with itself + // There may well be a better way to do this + // TODO Find a way to refactor this whole method and simplify it + xmlValue = item(index); + ((XML)xmlValue).setChildren(value); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, (XML)list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = getXML(_annos, index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, (XML)list.item(i)); } } } } else { addToList(xmlValue); } } } private XML getXML(XmlNode.List _annos, int index) { if (index >= 0 && index < length()) { return xmlFromNode(_annos.item(index)); } else { return null; } } void deleteXMLProperty(XMLName name) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml.isElement()) { xml.deleteXMLProperty(name); } } } public void delete(int index) { if (index >= 0 && index < length()) { XML xml = getXmlFromAnnotation(index); xml.remove(); internalRemoveFromList(index); } } public Object[] getIds() { Object enumObjs[]; if (isPrototype()) { enumObjs = new Object[0]; } else { enumObjs = new Object[length()]; for (int i = 0; i < enumObjs.length; i++) { enumObjs[i] = new Integer(i); } } return enumObjs; } public Object[] getIdsForDebug() { return getIds(); } // XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator. void remove() { int nLen = length(); for (int i = nLen - 1; i >= 0; i--) { XML xml = getXmlFromAnnotation(i); if (xml != null) { xml.remove(); internalRemoveFromList(i); } } } XML item(int index) { return _annos != null ? getXmlFromAnnotation(index) : createEmptyXML(); } private void setAttribute(XMLName xmlName, Object value) { for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); xml.setAttribute(xmlName, value); } } void addToList(Object toAdd) { _annos.addToList(toAdd); } // // // Methods from section 12.4.4 in the spec // // XMLList child(int index) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(index)); } return result; } XMLList child(XMLName xmlName) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).child(xmlName)); } return result; } void addMatches(XMLList rv, XMLName name) { for (int i=0; i<length(); i++) { getXmlFromAnnotation(i).addMatches(rv, name); } } XMLList children() { java.util.Vector v = new java.util.Vector(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); if (xml != null) { Object o = xml.children(); if (o instanceof XMLList) { XMLList childList = (XMLList)o; int cChildren = childList.length(); for (int j = 0; j < cChildren; j++) { v.addElement(childList.item(j)); } } } } XMLList allChildren = newXMLList(); int sz = v.size(); for (int i = 0; i < sz; i++) { allChildren.addToList(v.get(i)); } return allChildren; } XMLList comments() { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.comments()); } return result; } XMLList elements(XMLName name) { XMLList rv = newXMLList(); for (int i=0; i<length(); i++) { XML xml = getXmlFromAnnotation(i); rv.addToList(xml.elements(name)); } return rv; } boolean contains(Object xml) { boolean result = false; for (int i = 0; i < length(); i++) { XML member = getXmlFromAnnotation(i); if (member.equivalentXml(xml)) { result = true; break; } } return result; } XMLObjectImpl copy() { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.copy()); } return result; } boolean hasOwnProperty(XMLName xmlName) { if (isPrototype()) { String property = xmlName.localName(); return (findPrototypeId(property) != 0); } else { return (getPropertyList(xmlName).length() > 0); } } boolean hasComplexContent() { boolean complexContent; int length = length(); if (length == 0) { complexContent = false; } else if (length == 1) { complexContent = getXmlFromAnnotation(0).hasComplexContent(); } else { complexContent = false; for (int i = 0; i < length; i++) { XML nextElement = getXmlFromAnnotation(i); if (nextElement.isElement()) { complexContent = true; break; } } } return complexContent; } boolean hasSimpleContent() { if (length() == 0) { return true; } else if (length() == 1) { return getXmlFromAnnotation(0).hasSimpleContent(); } else { for (int i=0; i<length(); i++) { XML nextElement = getXmlFromAnnotation(i); if (nextElement.isElement()) { return false; } } return true; } } int length() { int result = 0; if (_annos != null) { result = _annos.length(); } return result; } void normalize() { for (int i = 0; i < length(); i++) { getXmlFromAnnotation(i).normalize(); } } /** * If list is empty, return undefined, if elements have different parents return undefined, * If they all have the same parent, return that parent. * * @return */ Object parent() { if (length() == 0) return Undefined.instance; XML candidateParent = null; for (int i = 0; i < length(); i++) { Object currParent = getXmlFromAnnotation(i).parent(); if (!(currParent instanceof XML)) return Undefined.instance; XML xml = (XML)currParent; if (i == 0) { // Set the first for the rest to compare to. candidateParent = xml; } else { if (candidateParent.is(xml)) { // keep looking } else { return Undefined.instance; } } } return candidateParent; } XMLList processingInstructions(XMLName xmlName) { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { XML xml = getXmlFromAnnotation(i); result.addToList(xml.processingInstructions(xmlName)); } return result; } boolean propertyIsEnumerable(Object name) { long index; if (name instanceof Integer) { index = ((Integer)name).intValue(); } else if (name instanceof Number) { double x = ((Number)name).doubleValue(); index = (long)x; if ((double)index != x) { return false; } if (index == 0 && 1.0 / x < 0) { // Negative 0 return false; } } else { String s = ScriptRuntime.toString(name); index = ScriptRuntime.testUint32String(s); } return (0 <= index && index < length()); } XMLList text() { XMLList result = newXMLList(); for (int i = 0; i < length(); i++) { result.addToList(getXmlFromAnnotation(i).text()); } return result; } public String toString() { // ECMA357 10.1.2 if (hasSimpleContent()) { StringBuffer sb = new StringBuffer(); for(int i = 0; i < length(); i++) { XML next = getXmlFromAnnotation(i); if (next.isComment() || next.isProcessingInstruction()) { // do nothing } else { sb.append(next.toString()); } } return sb.toString(); } else { return toXMLString(); } } String toXMLString() { // See ECMA 10.2.1 StringBuffer sb = new StringBuffer(); for (int i=0; i<length(); i++) { if (getProcessor().isPrettyPrinting() && i != 0) { sb.append('\n'); } sb.append(getXmlFromAnnotation(i).toXMLString()); } return sb.toString(); } Object valueOf() { return this; } // // Other public Functions from XMLObject // boolean equivalentXml(Object target) { boolean result = false; // Zero length list should equate to undefined if (target instanceof Undefined && length() == 0) { result = true; } else if (length() == 1) { result = getXmlFromAnnotation(0).equivalentXml(target); } else if (target instanceof XMLList) { XMLList otherList = (XMLList) target; if (otherList.length() == length()) { result = true; for (int i = 0; i < length(); i++) { if (!getXmlFromAnnotation(i).equivalentXml(otherList.getXmlFromAnnotation(i))) { result = false; break; } } } } return result; } private XMLList getPropertyList(XMLName name) { XMLList propertyList = newXMLList(); XmlNode.QName qname = null; if (!name.isDescendants() && !name.isAttributeName()) { // Only set the targetProperty if this is a regular child get // and not a descendant or attribute get qname = name.toQname(); } propertyList.setTargets(this, qname); for (int i = 0; i < length(); i++) { propertyList.addToList( getXmlFromAnnotation(i).getPropertyList(name)); } return propertyList; } private Object applyOrCall(boolean isApply, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { String methodName = isApply ? "apply" : "call"; if(!(thisObj instanceof XMLList) || ((XMLList)thisObj).targetProperty == null) throw ScriptRuntime.typeError1("msg.isnt.function", methodName); return ScriptRuntime.applyOrCall(isApply, cx, scope, thisObj, args); } protected Object jsConstructor(Context cx, boolean inNewExpr, Object[] args) { if (args.length == 0) { return newXMLList(); } else { Object arg0 = args[0]; if (!inNewExpr && arg0 instanceof XMLList) { // XMLList(XMLList) returns the same object. return arg0; } return newXMLListFrom(arg0); } } /** * See ECMA 357, 11_2_2_1, Semantics, 3_e. */ public Scriptable getExtraMethodSource(Context cx) { if (length() == 1) { return getXmlFromAnnotation(0); } return null; } public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { // This XMLList is being called as a Function. // Let's find the real Function object. if(targetProperty == null) throw ScriptRuntime.notFunctionError(this); String methodName = targetProperty.getLocalName(); boolean isApply = methodName.equals("apply"); if(isApply || methodName.equals("call")) return applyOrCall(isApply, cx, scope, thisObj, args); Callable method = ScriptRuntime.getElemFunctionAndThis( this, methodName, cx); // Call lastStoredScriptable to clear stored thisObj // but ignore the result as the method should use the supplied // thisObj, not one from redirected call ScriptRuntime.lastStoredScriptable(cx); return method.call(cx, scope, thisObj, args); } public Scriptable construct(Context cx, Scriptable scope, Object[] args) { throw ScriptRuntime.typeError1("msg.not.ctor", "XMLList"); } }
true
true
public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = newXMLFromJs(value.toString()); } else { xmlValue = newTextElementXML(null, targetProperty, value.toString()); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, (XML)list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = getXML(_annos, index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, (XML)list.item(i)); } } } } else { addToList(xmlValue); } } }
public void put(int index, Scriptable start, Object value) { Object parent = Undefined.instance; // Convert text into XML if needed. XMLObject xmlValue; // Special-case checks for undefined and null if (value == null) { value = "null"; } else if (value instanceof Undefined) { value = "undefined"; } if (value instanceof XMLObject) { xmlValue = (XMLObject) value; } else { if (targetProperty == null) { xmlValue = newXMLFromJs(value.toString()); } else { // Note that later in the code, we will use this as an argument to replace(int,value) // So we will be "replacing" this element with itself // There may well be a better way to do this // TODO Find a way to refactor this whole method and simplify it xmlValue = item(index); ((XML)xmlValue).setChildren(value); } } // Find the parent if (index < length()) { parent = item(index).parent(); } else { // Appending parent = parent(); } if (parent instanceof XML) { // found parent, alter doc XML xmlParent = (XML) parent; if (index < length()) { // We're replacing the the node. XML xmlNode = getXmlFromAnnotation(index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { int lastIndexAdded = xmlNode.childIndex(); replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i)); lastIndexAdded++; insert(index + i, (XML)list.item(i)); } } } } else { // Appending xmlParent.appendChild(xmlValue); addToList(xmlParent.getXmlChild(index)); } } else { // Don't all have same parent, no underlying doc to alter if (index < length()) { XML xmlNode = getXML(_annos, index); if (xmlValue instanceof XML) { replaceNode(xmlNode, (XML) xmlValue); replace(index, xmlNode); } else if (xmlValue instanceof XMLList) { // Replace the first one, and add the rest on the list. XMLList list = (XMLList) xmlValue; if (list.length() > 0) { replaceNode(xmlNode, (XML)list.item(0)); replace(index, (XML)list.item(0)); for (int i = 1; i < list.length(); i++) { insert(index + i, (XML)list.item(i)); } } } } else { addToList(xmlValue); } } }
diff --git a/spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java b/spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java index 879ebf9..9259ab5 100644 --- a/spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java +++ b/spoon-runner/src/main/java/com/squareup/spoon/html/HtmlUtils.java @@ -1,252 +1,252 @@ package com.squareup.spoon.html; import com.squareup.spoon.DeviceDetails; import com.squareup.spoon.DeviceTestResult; import com.squareup.spoon.misc.StackTrace; import java.io.File; import java.io.IOException; import java.text.Format; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.io.FilenameUtils; import static com.squareup.spoon.DeviceTestResult.SCREENSHOT_SEPARATOR; /** Utilities for representing the execution in HTML. */ final class HtmlUtils { private static final String INVALID_ID_CHARS = "[^a-zA-Z0-9]"; private static final ThreadLocal<Format> DATE_FORMAT = new ThreadLocal<Format>() { @Override protected Format initialValue() { return new SimpleDateFormat("yyyy-MM-dd hh:mm a"); } }; private static final ThreadLocal<Format> DATE_FORMAT_TV = new ThreadLocal<Format>() { @Override protected Format initialValue() { return new SimpleDateFormat("EEEE, MMMM dd, h:mm a"); } }; static String deviceDetailsToString(DeviceDetails details) { if (details == null) return null; StringBuilder builder = new StringBuilder(); builder.append("Running Android ") .append(details.getVersion()) .append(" (API ") .append(details.getApiLevel()) .append(")"); if (details.getLanguage() != null || details.getRegion() != null) { builder.append(" with locale "); if (details.getLanguage() != null) { builder.append(details.getLanguage()); if (details.getRegion() != null) { builder.append("-"); } if (details.getRegion() != null) { builder.append(details.getRegion()); } } } return builder.toString(); } static String dateToString(long date) { return DATE_FORMAT.get().format(new Date(date)); } public static String dateToTvString(long date) { return DATE_FORMAT_TV.get().format(new Date(date)); } /** Convert a class name and method name to a single HTML ID. */ static String testClassAndMethodToId(String className, String methodName) { return className.replaceAll(INVALID_ID_CHARS, "-") + "-" // + methodName.replaceAll(INVALID_ID_CHARS, "-"); } /** Fake Class#getSimpleName logic. */ static String getClassSimpleName(String className) { int lastPeriod = className.lastIndexOf("."); if (lastPeriod != -1) { return className.substring(lastPeriod + 1); } return className; } /** Convert a test result status into an HTML CSS class. */ static String getStatusCssClass(DeviceTestResult testResult) { String status; switch (testResult.getStatus()) { case PASS: status = "pass"; break; case FAIL: status = "fail"; break; case ERROR: status = "error"; break; default: throw new IllegalArgumentException("Unknown result status: " + testResult.getStatus()); } return status; } /** Convert a method name from {@code testThisThing_DoesThat} to "This Thing, Does That". */ static String prettifyMethodName(String methodName) { if (!methodName.startsWith("test")) { - throw new IllegalArgumentException("Method name does not start with 'test'."); + throw new IllegalArgumentException("Method name '" + methodName + "' does not start with 'test'."); } StringBuilder pretty = new StringBuilder(); String[] parts = methodName.substring(4).split("_"); for (String part : parts) { if ("".equals(part.trim())) { continue; // Skip empty parts. } if (pretty.length() > 0) { pretty.append(","); } boolean inUpper = true; for (char letter : part.toCharArray()) { boolean isUpper = Character.isUpperCase(letter); if (!isUpper && inUpper && pretty.length() > 1 // && pretty.charAt(pretty.length() - 2) != ' ') { // Lowercase coming from an uppercase, insert a space before uppercase if not present. pretty.insert(pretty.length() - 1, " "); } else if (isUpper && !inUpper) { // Uppercase coming from a lowercase, add a space. pretty.append(" "); } inUpper = isUpper; // Update current upper/lower status. pretty.append(letter); // Append ourselves! } } return pretty.toString(); } /** Convert an image name from {@code 87243508_this-here-is-it} to "This Here Is It". */ static String prettifyImageName(String imageName) { imageName = FilenameUtils.removeExtension(imageName); // Remove the timestamp information. imageName = imageName.split(SCREENSHOT_SEPARATOR, 2)[1]; StringBuilder pretty = new StringBuilder(); for (String part : imageName.replace('_', '-').split("-")) { if ("".equals(part.trim())) { continue; // Skip empty parts. } pretty.append(Character.toUpperCase(part.charAt(0))); pretty.append(part, 1, part.length()); pretty.append(" "); } return pretty.deleteCharAt(pretty.length() - 1).toString(); } /** Get a relative URI for {@code file} from {@code output} folder. */ static String createRelativeUri(File file, File output) { if (file == null) { return null; } try { file = file.getCanonicalFile(); output = output.getCanonicalFile(); if (file.equals(output)) { throw new IllegalArgumentException("File path and output folder are the same."); } StringBuilder builder = new StringBuilder(); while (!file.equals(output)) { if (builder.length() > 0) { builder.insert(0, "/"); } builder.insert(0, file.getName()); file = file.getParentFile().getCanonicalFile(); } return builder.toString(); } catch (IOException e) { throw new RuntimeException(e); } } /** Get a HTML representation of a screenshot with respect to {@code output} directory. */ static Screenshot getScreenshot(File screenshot, File output) { String relativePath = createRelativeUri(screenshot, output); String caption = prettifyImageName(screenshot.getName()); return new Screenshot(relativePath, caption); } /** Parse the string representation of an exception to a {@link ExceptionInfo} instance. */ static ExceptionInfo processStackTrace(StackTrace exception) { if (exception == null) { return null; } String message = exception.toString().replace("\n", "<br/>"); List<String> lines = new ArrayList<String>(); for (StackTrace.Element element : exception.getElements()) { lines.add("&nbsp;&nbsp;&nbsp;&nbsp;at " + element.toString()); } while (exception.getCause() != null) { exception = exception.getCause(); lines.add("Caused by: " + exception.toString().replace("\n", "<br/>")); } return new ExceptionInfo(message, lines); } static String humanReadableDuration(long length) { long minutes = length / 60; long seconds = length - (minutes * 60); StringBuilder builder = new StringBuilder(); if (minutes != 0) { builder.append(minutes).append(" minute"); if (minutes != 1) { builder.append("s"); } } if (seconds != 0 || minutes == 0) { if (builder.length() > 0) { builder.append(", "); } builder.append(seconds).append(" second"); if (seconds != 1) { builder.append("s"); } } return builder.toString(); } static final class Screenshot { private static final AtomicLong ID = new AtomicLong(0); public final long id; public final String path; public final String caption; Screenshot(String path, String caption) { this.id = ID.getAndIncrement(); this.path = path; this.caption = caption; } } static final class ExceptionInfo { private static final AtomicLong ID = new AtomicLong(0); public final long id; public final String title; public final List<String> body; ExceptionInfo(String title, List<String> body) { this.id = ID.getAndIncrement(); this.title = title; this.body = body; } } }
true
true
static String prettifyMethodName(String methodName) { if (!methodName.startsWith("test")) { throw new IllegalArgumentException("Method name does not start with 'test'."); } StringBuilder pretty = new StringBuilder(); String[] parts = methodName.substring(4).split("_"); for (String part : parts) { if ("".equals(part.trim())) { continue; // Skip empty parts. } if (pretty.length() > 0) { pretty.append(","); } boolean inUpper = true; for (char letter : part.toCharArray()) { boolean isUpper = Character.isUpperCase(letter); if (!isUpper && inUpper && pretty.length() > 1 // && pretty.charAt(pretty.length() - 2) != ' ') { // Lowercase coming from an uppercase, insert a space before uppercase if not present. pretty.insert(pretty.length() - 1, " "); } else if (isUpper && !inUpper) { // Uppercase coming from a lowercase, add a space. pretty.append(" "); } inUpper = isUpper; // Update current upper/lower status. pretty.append(letter); // Append ourselves! } } return pretty.toString(); }
static String prettifyMethodName(String methodName) { if (!methodName.startsWith("test")) { throw new IllegalArgumentException("Method name '" + methodName + "' does not start with 'test'."); } StringBuilder pretty = new StringBuilder(); String[] parts = methodName.substring(4).split("_"); for (String part : parts) { if ("".equals(part.trim())) { continue; // Skip empty parts. } if (pretty.length() > 0) { pretty.append(","); } boolean inUpper = true; for (char letter : part.toCharArray()) { boolean isUpper = Character.isUpperCase(letter); if (!isUpper && inUpper && pretty.length() > 1 // && pretty.charAt(pretty.length() - 2) != ' ') { // Lowercase coming from an uppercase, insert a space before uppercase if not present. pretty.insert(pretty.length() - 1, " "); } else if (isUpper && !inUpper) { // Uppercase coming from a lowercase, add a space. pretty.append(" "); } inUpper = isUpper; // Update current upper/lower status. pretty.append(letter); // Append ourselves! } } return pretty.toString(); }
diff --git a/src/com/othersonline/kv/distributed/AbstractRefreshingNodeStore.java b/src/com/othersonline/kv/distributed/AbstractRefreshingNodeStore.java index f48d4f5..47a0c16 100644 --- a/src/com/othersonline/kv/distributed/AbstractRefreshingNodeStore.java +++ b/src/com/othersonline/kv/distributed/AbstractRefreshingNodeStore.java @@ -1,100 +1,100 @@ package com.othersonline.kv.distributed; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class AbstractRefreshingNodeStore implements NodeStore { public static final Long DEFAULT_DELAY = 1000l * 60l; public static final Long DEFAULT_PERIOD = 1000l * 60l; protected Log log = LogFactory.getLog(getClass()); protected List<NodeChangeListener> listeners = new LinkedList<NodeChangeListener>(); protected volatile List<Node> activeNodes = new LinkedList<Node>(); public void start() throws IOException, ConfigurationException { this.activeNodes = refreshActiveNodes(); publish(); schedule(DEFAULT_DELAY, DEFAULT_PERIOD); } public void schedule(long delay, long period) { Timer t = new Timer(true); t.scheduleAtFixedRate(new TimerTask() { public void run() { try { List<Node> newActiveNodes = refreshActiveNodes(); if (changed(activeNodes, newActiveNodes)) { activeNodes = newActiveNodes; publish(); } } catch (Exception e) { log.error("Exception calling refreshActiveNodes()", e); } } }, delay, period); } public void addChangeListener(NodeChangeListener listener) { this.listeners.add(listener); } public void addNode(Node node) { if (!this.activeNodes.contains(node)) { this.activeNodes.add(node); publish(); } } public void removeNode(Node node) { if (this.activeNodes.contains(node)) { this.activeNodes.remove(node); publish(); } } public List<Node> getActiveNodes() { return activeNodes; } public abstract List<Node> refreshActiveNodes() throws IOException, ConfigurationException; protected void publish() { activeNodes = getActiveNodes(); for (NodeChangeListener listener : listeners) { try { listener.setActiveNodes(activeNodes); } catch (Exception e) { log.warn("Exception calling activeNodes() on listener class.", e); } } } private boolean changed(List<Node> active, List<Node> updated) { if (active.size() != updated.size()) return true; for (int i = 0; i < active.size(); ++i) { Node currentNode = active.get(i); Node updatedNode = updated.get(i); // compare if ((currentNode.getId() != updatedNode.getId()) || (!currentNode.getConnectionURI().equals( updatedNode.getConnectionURI())) || (currentNode.getPhysicalId() != updatedNode .getPhysicalId()) - || (currentNode.getSalt().equals(updatedNode.getSalt()))) + || (!currentNode.getSalt().equals(updatedNode.getSalt()))) return true; } return false; } }
true
true
private boolean changed(List<Node> active, List<Node> updated) { if (active.size() != updated.size()) return true; for (int i = 0; i < active.size(); ++i) { Node currentNode = active.get(i); Node updatedNode = updated.get(i); // compare if ((currentNode.getId() != updatedNode.getId()) || (!currentNode.getConnectionURI().equals( updatedNode.getConnectionURI())) || (currentNode.getPhysicalId() != updatedNode .getPhysicalId()) || (currentNode.getSalt().equals(updatedNode.getSalt()))) return true; } return false; }
private boolean changed(List<Node> active, List<Node> updated) { if (active.size() != updated.size()) return true; for (int i = 0; i < active.size(); ++i) { Node currentNode = active.get(i); Node updatedNode = updated.get(i); // compare if ((currentNode.getId() != updatedNode.getId()) || (!currentNode.getConnectionURI().equals( updatedNode.getConnectionURI())) || (currentNode.getPhysicalId() != updatedNode .getPhysicalId()) || (!currentNode.getSalt().equals(updatedNode.getSalt()))) return true; } return false; }
diff --git a/src/org/ebookdroid/core/events/EventDispatcher.java b/src/org/ebookdroid/core/events/EventDispatcher.java index 3a4c91b1..5eec4029 100644 --- a/src/org/ebookdroid/core/events/EventDispatcher.java +++ b/src/org/ebookdroid/core/events/EventDispatcher.java @@ -1,22 +1,22 @@ package org.ebookdroid.core.events; import java.util.ArrayList; public class EventDispatcher { private final ArrayList<Object> listeners = new ArrayList<Object>(); - public void dispatch(final Event event) { + public void dispatch(final Event<?> event) { for (final Object listener : listeners) { event.dispatchOn(listener); } } public void addEventListener(final Object listener) { listeners.add(listener); } public void removeEventListener(final Object listener) { listeners.remove(listener); } }
true
true
public void dispatch(final Event event) { for (final Object listener : listeners) { event.dispatchOn(listener); } }
public void dispatch(final Event<?> event) { for (final Object listener : listeners) { event.dispatchOn(listener); } }
diff --git a/tools/runner/java/dalvik/runner/Dx.java b/tools/runner/java/dalvik/runner/Dx.java index 83f126552..d36a99d28 100644 --- a/tools/runner/java/dalvik/runner/Dx.java +++ b/tools/runner/java/dalvik/runner/Dx.java @@ -1,32 +1,37 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dalvik.runner; /** * A dx command. */ final class Dx { public void dex(String output, Classpath classpath) { + // We pass --core-library so that we can write tests in the same package they're testing, + // even when that's a core library package. If you're actually just using this tool to + // execute arbitrary code, this has the unfortunate side-effect of preventing "dx" from + // protecting you from yourself. new Command.Builder() .args("dx") + .args("--core-library") .args("--dex") .args("--output=" + output) .args(Strings.objectsToStrings(classpath.getElements())) .execute(); } }
false
true
public void dex(String output, Classpath classpath) { new Command.Builder() .args("dx") .args("--dex") .args("--output=" + output) .args(Strings.objectsToStrings(classpath.getElements())) .execute(); }
public void dex(String output, Classpath classpath) { // We pass --core-library so that we can write tests in the same package they're testing, // even when that's a core library package. If you're actually just using this tool to // execute arbitrary code, this has the unfortunate side-effect of preventing "dx" from // protecting you from yourself. new Command.Builder() .args("dx") .args("--core-library") .args("--dex") .args("--output=" + output) .args(Strings.objectsToStrings(classpath.getElements())) .execute(); }
diff --git a/luaj-vm/src/core/org/luaj/vm2/lib/BaseLib.java b/luaj-vm/src/core/org/luaj/vm2/lib/BaseLib.java index f5b639f..fabc868 100644 --- a/luaj-vm/src/core/org/luaj/vm2/lib/BaseLib.java +++ b/luaj-vm/src/core/org/luaj/vm2/lib/BaseLib.java @@ -1,396 +1,397 @@ /******************************************************************************* * Copyright (c) 2009 Luaj.org. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/package org.luaj.vm2.lib; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import org.luaj.vm2.LoadState; import org.luaj.vm2.LuaError; import org.luaj.vm2.LuaString; import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaThread; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; /** * Base library implementation, targeted for JME platforms. * * BaseLib instances are typically used as the initial globals table * when creating a new uniqued runtime context. * * Since JME has no file system by default, dofile and loadfile use the * FINDER instance to find resource files. The default loader chain * in PackageLib will use these as well. * * For an implementation that looks in the current directory on JSE, * use org.luaj.lib.j2se.BaseLib instead. * * @see org.luaj.vm2.lib.jse.JseBaseLib */ public class BaseLib extends OneArgFunction implements ResourceFinder { public static final String VERSION = "Luaj 2.0"; public static BaseLib instance; public InputStream STDIN = null; public PrintStream STDOUT = System.out; public PrintStream STDERR = System.err; /** * Singleton file opener for this Java ClassLoader realm. * * Unless set or changed elsewhere, will be set by the BaseLib that is created. */ public static ResourceFinder FINDER; private LuaValue next; private LuaValue inext; /** * Construct a base libarary instance. */ public BaseLib() { instance = this; } public LuaValue call(LuaValue arg) { env.set( "_G", env ); env.set( "_VERSION", VERSION ); bind( env, BaseLib1.class, new String[] { "getfenv", // ( [f] ) -> env "getmetatable", // ( object ) -> table } ); bind( env, BaseLib2.class, new String[] { "collectgarbage", // ( opt [,arg] ) -> value "error", // ( message [,level] ) -> ERR "rawequal", // (v1, v2) -> boolean "setfenv", // (f, table) -> void } ); bind( env, BaseLibV.class, new String[] { "assert", // ( v [,message] ) -> v, message | ERR "dofile", // ( filename ) -> result1, ... "load", // ( func [,chunkname] ) -> chunk | nil, msg "loadfile", // ( [filename] ) -> chunk | nil, msg "loadstring", // ( string [,chunkname] ) -> chunk | nil, msg "pcall", // (f, arg1, ...) -> status, result1, ... "xpcall", // (f, err) -> result1, ... "print", // (...) -> void "select", // (f, ...) -> value1, ... "unpack", // (list [,i [,j]]) -> result1, ... "type", // (v) -> value "rawget", // (table, index) -> value "rawset", // (table, index, value) -> table "setmetatable", // (table, metatable) -> table "tostring", // (e) -> value "tonumber", // (e [,base]) -> value "pairs", // "pairs" (t) -> iter-func, t, nil "ipairs", // "ipairs", // (t) -> iter-func, t, 0 "next", // "next" ( table, [index] ) -> next-index, next-value "__inext", // "inext" ( table, [int-index] ) -> next-index, next-value } ); // remember next, and inext for use in pairs and ipairs next = env.get("next"); inext = env.get("__inext"); // inject base lib ((BaseLibV) env.get("print")).baselib = this; ((BaseLibV) env.get("pairs")).baselib = this; ((BaseLibV) env.get("ipairs")).baselib = this; // set the default resource finder if not set already if ( FINDER == null ) FINDER = this; return env; } /** ResourceFinder implementation * * Tries to open the file as a resource, which can work for . */ public InputStream findResource(String filename) { Class c = getClass(); return c.getResourceAsStream(filename.startsWith("/")? filename: "/"+filename); } public static final class BaseLib1 extends OneArgFunction { public LuaValue call(LuaValue arg) { switch ( opcode ) { case 0: { // "getfenv", // ( [f] ) -> env LuaValue f = getfenvobj(arg); LuaValue e = f.getfenv(); return e!=null? e: NIL; } case 1: // "getmetatable", // ( object ) -> table LuaValue mt = arg.getmetatable(); return mt!=null? mt: NIL; } return NIL; } } public static final class BaseLib2 extends TwoArgFunction { public LuaValue call(LuaValue arg1, LuaValue arg2) { switch ( opcode ) { case 0: // "collectgarbage", // ( opt [,arg] ) -> value String s = arg1.optjstring("collect"); int result = 0; if ( "collect".equals(s) ) { System.gc(); return ZERO; } else if ( "count".equals(s) ) { Runtime rt = Runtime.getRuntime(); long used = rt.totalMemory() - rt.freeMemory(); return valueOf(used/1024.); } else if ( "step".equals(s) ) { System.gc(); return LuaValue.TRUE; } return NIL; case 1: // "error", // ( message [,level] ) -> ERR throw new LuaError( arg1.isnil()? null: arg1.tojstring(), arg2.optint(1) ); case 2: // "rawequal", // (v1, v2) -> boolean return valueOf(arg1 == arg2); case 3: { // "setfenv", // (f, table) -> void LuaTable t = arg2.checktable(); LuaValue f = getfenvobj(arg1); f.setfenv(t); return f.isthread()? NONE: f; } } return NIL; } } private static LuaValue getfenvobj(LuaValue arg) { if ( arg.isclosure() ) return arg; int level = arg.optint(1); if ( level == 0 ) return LuaThread.getRunning(); LuaValue f = LuaThread.getCallstackFunction(level); arg.argcheck(f != null, 1, "invalid level"); return f; } public static final class BaseLibV extends VarArgFunction { public BaseLib baselib; public Varargs invoke(Varargs args) { switch ( opcode ) { case 0: // "assert", // ( v [,message] ) -> v, message | ERR - if ( !args.arg1().toboolean() ) error("assertion failed!"); + if ( !args.arg1().toboolean() ) + error( args.narg()>1? args.checkjstring(2): "assertion failed!" ); return args; case 1: // "dofile", // ( filename ) -> result1, ... { LuaValue chunk; try { String filename = args.checkjstring(1); chunk = loadFile(filename).arg1(); } catch ( IOException e ) { return error(e.getMessage()); } return chunk.invoke(); } case 2: // "load", // ( func [,chunkname] ) -> chunk | nil, msg try { LuaValue func = args.checkfunction(1); String chunkname = args.optjstring(2, "function"); return LoadState.load(new StringInputStream(func), chunkname, LuaThread.getGlobals()); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } case 3: // "loadfile", // ( [filename] ) -> chunk | nil, msg { try { String filename = args.checkjstring(1); return loadFile(filename); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } } case 4: // "loadstring", // ( string [,chunkname] ) -> chunk | nil, msg try { LuaString script = args.checkstring(1); String chunkname = args.optjstring(2, "string"); return LoadState.load(script.toInputStream(),chunkname,LuaThread.getGlobals()); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } case 5: // "pcall", // (f, arg1, ...) -> status, result1, ... { LuaThread.onCall(this); try { return pcall(args.arg1(),args.subargs(2),null); } finally { LuaThread.onReturn(); } } case 6: // "xpcall", // (f, err) -> result1, ... { LuaThread.onCall(this); try { return pcall(args.arg1(),NONE,args.checkvalue(2)); } finally { LuaThread.onReturn(); } } case 7: // "print", // (...) -> void { LuaValue tostring = LuaThread.getGlobals().get("tostring"); for ( int i=1, n=args.narg(); i<=n; i++ ) { if ( i>1 ) baselib.STDOUT.write( '\t' ); LuaString s = tostring.call( args.arg(i) ).strvalue(); int z = s.indexOf((byte)0, 0); baselib.STDOUT.write( s.m_bytes, s.m_offset, z>=0? z: s.m_length ); } baselib.STDOUT.println(); return NONE; } case 8: // "select", // (f, ...) -> value1, ... { int n = args.narg()-1; if ( args.arg1().equals(valueOf("#")) ) return valueOf(n); int i = args.checkint(1); if ( i == 0 || i < -n ) typerror(1,"index out of range"); return args.subargs(i<0? n+i+2: i+1); } case 9: // "unpack", // (list [,i [,j]]) -> result1, ... { int na = args.narg(); LuaTable t = args.checktable(1); int n = t.length(); int i = na>=2? args.checkint(2): 1; int j = na>=3? args.checkint(3): n; n = j-i+1; if ( n<0 ) return NONE; if ( n==1 ) return t.get(i); if ( n==2 ) return varargsOf(t.get(i),t.get(j)); LuaValue[] v = new LuaValue[n]; for ( int k=0; k<n; k++ ) v[k] = t.get(i+k); return varargsOf(v); } case 10: // "type", // (v) -> value return valueOf(args.checkvalue(1).typename()); case 11: // "rawget", // (table, index) -> value return args.checktable(1).rawget(args.checkvalue(2)); case 12: { // "rawset", // (table, index, value) -> table LuaTable t = args.checktable(1); t.rawset(args.checknotnil(2), args.checkvalue(3)); return t; } case 13: { // "setmetatable", // (table, metatable) -> table final LuaValue t = args.arg1(); final LuaValue mt = args.checkvalue(2); return t.setmetatable(mt.isnil()? null: mt.checktable()); } case 14: { // "tostring", // (e) -> value LuaValue arg = args.checkvalue(1); return arg.type() == LuaValue.TSTRING? arg: valueOf(arg.tojstring()); } case 15: { // "tonumber", // (e [,base]) -> value LuaValue arg1 = args.checkvalue(1); final int base = args.optint(2,10); if (base == 10) { /* standard conversion */ return arg1.tonumber(); } else { if ( base < 2 || base > 36 ) argerror(2, "base out of range"); final LuaString str = arg1.optstring(null); return str!=null? str.tonumber(base): NIL; } } case 16: // "pairs" (t) -> iter-func, t, nil return varargsOf( baselib.next, args.checktable(1) ); case 17: // "ipairs", // (t) -> iter-func, t, 0 return varargsOf( baselib.inext, args.checktable(1), ZERO ); case 18: // "next" ( table, [index] ) -> next-index, next-value return args.arg1().next(args.arg(2)); case 19: // "inext" ( table, [int-index] ) -> next-index, next-value return args.arg1().inext(args.arg(2)); } return NONE; } } public static Varargs pcall(LuaValue func, Varargs args, LuaValue errfunc) { try { LuaThread thread = LuaThread.getRunning(); LuaValue olderr = thread.err; try { thread.err = errfunc; return varargsOf(LuaValue.TRUE, func.invoke(args)); } finally { thread.err = olderr; } } catch ( LuaError le ) { String m = le.getMessage(); return varargsOf(FALSE, m!=null? valueOf(m): NIL); } catch ( Exception e ) { String m = e.getMessage(); return varargsOf(FALSE, valueOf(m!=null? m: e.toString())); } } public static Varargs loadFile(String filename) throws IOException { InputStream is = FINDER.findResource(filename); if ( is == null ) return varargsOf(NIL, valueOf("not found: "+filename)); try { return LoadState.load(is, filename, LuaThread.getGlobals()); } finally { is.close(); } } private static class StringInputStream extends InputStream { LuaValue func; byte[] bytes; int offset; StringInputStream(LuaValue func) { this.func = func; } public int read() throws IOException { if ( func == null ) return -1; if ( bytes == null ) { LuaValue s = func.call(); if ( s.isnil() ) { func = null; bytes = null; return -1; } bytes = s.tojstring().getBytes(); offset = 0; } if ( offset >= bytes.length ) return -1; return bytes[offset++]; } } }
true
true
public Varargs invoke(Varargs args) { switch ( opcode ) { case 0: // "assert", // ( v [,message] ) -> v, message | ERR if ( !args.arg1().toboolean() ) error("assertion failed!"); return args; case 1: // "dofile", // ( filename ) -> result1, ... { LuaValue chunk; try { String filename = args.checkjstring(1); chunk = loadFile(filename).arg1(); } catch ( IOException e ) { return error(e.getMessage()); } return chunk.invoke(); } case 2: // "load", // ( func [,chunkname] ) -> chunk | nil, msg try { LuaValue func = args.checkfunction(1); String chunkname = args.optjstring(2, "function"); return LoadState.load(new StringInputStream(func), chunkname, LuaThread.getGlobals()); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } case 3: // "loadfile", // ( [filename] ) -> chunk | nil, msg { try { String filename = args.checkjstring(1); return loadFile(filename); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } } case 4: // "loadstring", // ( string [,chunkname] ) -> chunk | nil, msg try { LuaString script = args.checkstring(1); String chunkname = args.optjstring(2, "string"); return LoadState.load(script.toInputStream(),chunkname,LuaThread.getGlobals()); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } case 5: // "pcall", // (f, arg1, ...) -> status, result1, ... { LuaThread.onCall(this); try { return pcall(args.arg1(),args.subargs(2),null); } finally { LuaThread.onReturn(); } } case 6: // "xpcall", // (f, err) -> result1, ... { LuaThread.onCall(this); try { return pcall(args.arg1(),NONE,args.checkvalue(2)); } finally { LuaThread.onReturn(); } } case 7: // "print", // (...) -> void { LuaValue tostring = LuaThread.getGlobals().get("tostring"); for ( int i=1, n=args.narg(); i<=n; i++ ) { if ( i>1 ) baselib.STDOUT.write( '\t' ); LuaString s = tostring.call( args.arg(i) ).strvalue(); int z = s.indexOf((byte)0, 0); baselib.STDOUT.write( s.m_bytes, s.m_offset, z>=0? z: s.m_length ); } baselib.STDOUT.println(); return NONE; } case 8: // "select", // (f, ...) -> value1, ... { int n = args.narg()-1; if ( args.arg1().equals(valueOf("#")) ) return valueOf(n); int i = args.checkint(1); if ( i == 0 || i < -n ) typerror(1,"index out of range"); return args.subargs(i<0? n+i+2: i+1); } case 9: // "unpack", // (list [,i [,j]]) -> result1, ... { int na = args.narg(); LuaTable t = args.checktable(1); int n = t.length(); int i = na>=2? args.checkint(2): 1; int j = na>=3? args.checkint(3): n; n = j-i+1; if ( n<0 ) return NONE; if ( n==1 ) return t.get(i); if ( n==2 ) return varargsOf(t.get(i),t.get(j)); LuaValue[] v = new LuaValue[n]; for ( int k=0; k<n; k++ ) v[k] = t.get(i+k); return varargsOf(v); } case 10: // "type", // (v) -> value return valueOf(args.checkvalue(1).typename()); case 11: // "rawget", // (table, index) -> value return args.checktable(1).rawget(args.checkvalue(2)); case 12: { // "rawset", // (table, index, value) -> table LuaTable t = args.checktable(1); t.rawset(args.checknotnil(2), args.checkvalue(3)); return t; } case 13: { // "setmetatable", // (table, metatable) -> table final LuaValue t = args.arg1(); final LuaValue mt = args.checkvalue(2); return t.setmetatable(mt.isnil()? null: mt.checktable()); } case 14: { // "tostring", // (e) -> value LuaValue arg = args.checkvalue(1); return arg.type() == LuaValue.TSTRING? arg: valueOf(arg.tojstring()); } case 15: { // "tonumber", // (e [,base]) -> value LuaValue arg1 = args.checkvalue(1); final int base = args.optint(2,10); if (base == 10) { /* standard conversion */ return arg1.tonumber(); } else { if ( base < 2 || base > 36 ) argerror(2, "base out of range"); final LuaString str = arg1.optstring(null); return str!=null? str.tonumber(base): NIL; } } case 16: // "pairs" (t) -> iter-func, t, nil return varargsOf( baselib.next, args.checktable(1) ); case 17: // "ipairs", // (t) -> iter-func, t, 0 return varargsOf( baselib.inext, args.checktable(1), ZERO ); case 18: // "next" ( table, [index] ) -> next-index, next-value return args.arg1().next(args.arg(2)); case 19: // "inext" ( table, [int-index] ) -> next-index, next-value return args.arg1().inext(args.arg(2)); } return NONE; }
public Varargs invoke(Varargs args) { switch ( opcode ) { case 0: // "assert", // ( v [,message] ) -> v, message | ERR if ( !args.arg1().toboolean() ) error( args.narg()>1? args.checkjstring(2): "assertion failed!" ); return args; case 1: // "dofile", // ( filename ) -> result1, ... { LuaValue chunk; try { String filename = args.checkjstring(1); chunk = loadFile(filename).arg1(); } catch ( IOException e ) { return error(e.getMessage()); } return chunk.invoke(); } case 2: // "load", // ( func [,chunkname] ) -> chunk | nil, msg try { LuaValue func = args.checkfunction(1); String chunkname = args.optjstring(2, "function"); return LoadState.load(new StringInputStream(func), chunkname, LuaThread.getGlobals()); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } case 3: // "loadfile", // ( [filename] ) -> chunk | nil, msg { try { String filename = args.checkjstring(1); return loadFile(filename); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } } case 4: // "loadstring", // ( string [,chunkname] ) -> chunk | nil, msg try { LuaString script = args.checkstring(1); String chunkname = args.optjstring(2, "string"); return LoadState.load(script.toInputStream(),chunkname,LuaThread.getGlobals()); } catch ( Exception e ) { return varargsOf(NIL, valueOf(e.getMessage())); } case 5: // "pcall", // (f, arg1, ...) -> status, result1, ... { LuaThread.onCall(this); try { return pcall(args.arg1(),args.subargs(2),null); } finally { LuaThread.onReturn(); } } case 6: // "xpcall", // (f, err) -> result1, ... { LuaThread.onCall(this); try { return pcall(args.arg1(),NONE,args.checkvalue(2)); } finally { LuaThread.onReturn(); } } case 7: // "print", // (...) -> void { LuaValue tostring = LuaThread.getGlobals().get("tostring"); for ( int i=1, n=args.narg(); i<=n; i++ ) { if ( i>1 ) baselib.STDOUT.write( '\t' ); LuaString s = tostring.call( args.arg(i) ).strvalue(); int z = s.indexOf((byte)0, 0); baselib.STDOUT.write( s.m_bytes, s.m_offset, z>=0? z: s.m_length ); } baselib.STDOUT.println(); return NONE; } case 8: // "select", // (f, ...) -> value1, ... { int n = args.narg()-1; if ( args.arg1().equals(valueOf("#")) ) return valueOf(n); int i = args.checkint(1); if ( i == 0 || i < -n ) typerror(1,"index out of range"); return args.subargs(i<0? n+i+2: i+1); } case 9: // "unpack", // (list [,i [,j]]) -> result1, ... { int na = args.narg(); LuaTable t = args.checktable(1); int n = t.length(); int i = na>=2? args.checkint(2): 1; int j = na>=3? args.checkint(3): n; n = j-i+1; if ( n<0 ) return NONE; if ( n==1 ) return t.get(i); if ( n==2 ) return varargsOf(t.get(i),t.get(j)); LuaValue[] v = new LuaValue[n]; for ( int k=0; k<n; k++ ) v[k] = t.get(i+k); return varargsOf(v); } case 10: // "type", // (v) -> value return valueOf(args.checkvalue(1).typename()); case 11: // "rawget", // (table, index) -> value return args.checktable(1).rawget(args.checkvalue(2)); case 12: { // "rawset", // (table, index, value) -> table LuaTable t = args.checktable(1); t.rawset(args.checknotnil(2), args.checkvalue(3)); return t; } case 13: { // "setmetatable", // (table, metatable) -> table final LuaValue t = args.arg1(); final LuaValue mt = args.checkvalue(2); return t.setmetatable(mt.isnil()? null: mt.checktable()); } case 14: { // "tostring", // (e) -> value LuaValue arg = args.checkvalue(1); return arg.type() == LuaValue.TSTRING? arg: valueOf(arg.tojstring()); } case 15: { // "tonumber", // (e [,base]) -> value LuaValue arg1 = args.checkvalue(1); final int base = args.optint(2,10); if (base == 10) { /* standard conversion */ return arg1.tonumber(); } else { if ( base < 2 || base > 36 ) argerror(2, "base out of range"); final LuaString str = arg1.optstring(null); return str!=null? str.tonumber(base): NIL; } } case 16: // "pairs" (t) -> iter-func, t, nil return varargsOf( baselib.next, args.checktable(1) ); case 17: // "ipairs", // (t) -> iter-func, t, 0 return varargsOf( baselib.inext, args.checktable(1), ZERO ); case 18: // "next" ( table, [index] ) -> next-index, next-value return args.arg1().next(args.arg(2)); case 19: // "inext" ( table, [int-index] ) -> next-index, next-value return args.arg1().inext(args.arg(2)); } return NONE; }
diff --git a/src/com/matejdro/pebbledialer/PebbleUtil.java b/src/com/matejdro/pebbledialer/PebbleUtil.java index f8377c4..5ffe250 100644 --- a/src/com/matejdro/pebbledialer/PebbleUtil.java +++ b/src/com/matejdro/pebbledialer/PebbleUtil.java @@ -1,47 +1,47 @@ package com.matejdro.pebbledialer; public class PebbleUtil { public static String replaceInvalidCharacters(String data) { data = data.replace("\u010D", "c"); data = data.replace("\u010C", "C"); return data; } public static String prepareString(String text) { return prepareString(text, 20); } public static String prepareString(String text, int length) { if (text == null) return null; int targetLength = length - 3; text = text.trim(); if (text.getBytes().length > length) { if (text.length() > targetLength) text = text.substring(0, targetLength).trim(); while (text.getBytes().length > targetLength) { text = text.substring(0, text.length() - 1); } text = text + "..."; } text = replaceInvalidCharacters(text); if (RTLUtility.getInstance().isRTL(text)){ - RTLUtility.getInstance().format(text,15); + text = RTLUtility.getInstance().format(text,15); } return text; } }
true
true
public static String prepareString(String text, int length) { if (text == null) return null; int targetLength = length - 3; text = text.trim(); if (text.getBytes().length > length) { if (text.length() > targetLength) text = text.substring(0, targetLength).trim(); while (text.getBytes().length > targetLength) { text = text.substring(0, text.length() - 1); } text = text + "..."; } text = replaceInvalidCharacters(text); if (RTLUtility.getInstance().isRTL(text)){ RTLUtility.getInstance().format(text,15); } return text; }
public static String prepareString(String text, int length) { if (text == null) return null; int targetLength = length - 3; text = text.trim(); if (text.getBytes().length > length) { if (text.length() > targetLength) text = text.substring(0, targetLength).trim(); while (text.getBytes().length > targetLength) { text = text.substring(0, text.length() - 1); } text = text + "..."; } text = replaceInvalidCharacters(text); if (RTLUtility.getInstance().isRTL(text)){ text = RTLUtility.getInstance().format(text,15); } return text; }
diff --git a/src/org/eclipse/core/internal/resources/ResourceTree.java b/src/org/eclipse/core/internal/resources/ResourceTree.java index eff05753..c147ee15 100644 --- a/src/org/eclipse/core/internal/resources/ResourceTree.java +++ b/src/org/eclipse/core/internal/resources/ResourceTree.java @@ -1,1041 +1,1041 @@ /********************************************************************** * Copyright (c) 2002 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM - Initial API and implementation **********************************************************************/ package org.eclipse.core.internal.resources; import java.io.*; import org.eclipse.core.internal.localstore.*; import org.eclipse.core.internal.properties.PropertyManager; import org.eclipse.core.internal.utils.Assert; import org.eclipse.core.internal.utils.Policy; import org.eclipse.core.resources.*; import org.eclipse.core.resources.team.IResourceTree; import org.eclipse.core.runtime.*; /** * @since 2.0 */ class ResourceTree implements IResourceTree { MultiStatus status; boolean isValid = true; /** * Constructor for this class. */ public ResourceTree(MultiStatus status) { super(); this.status = status; } /** * The specific operation for which this tree was created has completed and this tree * should not be used anymore. Ensure that this is the case by making it invalid. This * is checked by all API methods. */ void makeInvalid() { this.isValid = false; } /** * @see IResourceTree#addToLocalHistory(IFile) */ public void addToLocalHistory(IFile file) { Assert.isLegal(isValid); if (!file.exists()) return; IPath path = file.getLocation(); if (path == null || !path.toFile().exists()) return; long lastModified = internalComputeTimestamp(path.toOSString()); ((Resource) file).getLocalManager().getHistoryStore().addState(file.getFullPath(), path, lastModified, false); } /** * @see IResourceTree#movedFile(IFile, IFile) */ public void movedFile(IFile source, IFile destination) { Assert.isLegal(isValid); // Do nothing if the resource doesn't exist. if (!source.exists()) return; // If the destination already exists then we have a problem. if (destination.exists()) { String message = Policy.bind("resources.mustNotExist", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message); // log the status but don't return until we try and move the rest of the resource information. failed(status); } // Move the resource's persistent properties. PropertyManager propertyManager = ((Resource) source).getPropertyManager(); try { propertyManager.copy(source, destination, IResource.DEPTH_ZERO); propertyManager.deleteProperties(source, IResource.DEPTH_ZERO); } catch (CoreException e) { String message = Policy.bind("resources.errorPropertiesMove", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource information. failed(status); } // Move the node in the workspace tree. Workspace workspace = (Workspace) source.getWorkspace(); try { workspace.move((Resource) source, destination.getFullPath(), IResource.DEPTH_ZERO, false); } catch (CoreException e) { String message = Policy.bind("resources.errorMoving", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource information. failed(status); } // Generate the marker deltas. try { workspace.getMarkerManager().moved(source, destination, IResource.DEPTH_ZERO); } catch (CoreException e) { String message = Policy.bind("resources.errorMarkersDelete", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); failed(status); } } /** * @see IResourceTree#movedFolderSubtree(IFolder, IFolder) */ public void movedFolderSubtree(IFolder source, IFolder destination) { Assert.isLegal(isValid); // Do nothing if the source resource doesn't exist. if (!source.exists()) return; // If the destination already exists then we have an error. if (destination.exists()) { String message = Policy.bind("resources.mustNotExist", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status= new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message); failed(status); return; } // Move the folder properties. int depth = IResource.DEPTH_INFINITE; PropertyManager propertyManager = ((Resource) source).getPropertyManager(); try { propertyManager.copy(source, destination, depth); propertyManager.deleteProperties(source, depth); } catch (CoreException e) { String message = Policy.bind("resources.errorPropertiesMove", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Create the destination node in the tree. Workspace workspace = (Workspace) source.getWorkspace(); try { workspace.move((Resource) source, destination.getFullPath(), depth, false); } catch (CoreException e) { String message = Policy.bind("resources.errorMoving", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Generate the marker deltas. try { workspace.getMarkerManager().moved(source, destination, depth); } catch (CoreException e) { String message = Policy.bind("resources.errorMarkersDelete", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); failed(status); } } /** * @see IResourceTree#movedProject(IProject, IProject) */ public boolean movedProjectSubtree(IProject project, IProjectDescription destDescription) { Assert.isLegal(isValid); // Do nothing if the source resource doesn't exist. if (!project.exists()) return true; Project source = (Project) project; Project destination = (Project) source.getWorkspace().getRoot().getProject(destDescription.getName()); IProjectDescription srcDescription = source.internalGetDescription(); Workspace workspace = (Workspace) source.getWorkspace(); int depth = IResource.DEPTH_INFINITE; // If the name of the source and destination projects are not the same then // rename the meta area and make changes in the tree. if (isNameChange(source, destDescription)) { if (destination.exists()) { String message = Policy.bind("resources.mustNotExist", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message); failed(status); return false; } // Rename the project metadata area. Close the property store so bogus values // aren't copied to the destination. // FIXME: do we need to do this? try { source.getPropertyManager().closePropertyStore(source); } catch (CoreException e) { String message = Policy.bind("properties.couldNotClose", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } java.io.File oldMetaArea = workspace.getMetaArea().locationFor(source).toFile(); java.io.File newMetaArea = workspace.getMetaArea().locationFor(destination).toFile(); try{ source.getLocalManager().getStore().move(oldMetaArea, newMetaArea, false, new NullProgressMonitor()); } catch (CoreException e) { String message = Policy.bind("resources.moveMeta", oldMetaArea.toString(), newMetaArea.toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_WRITE_METADATA, destination.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Move the workspace tree. try { workspace.move(source, destination.getFullPath(), depth, false); } catch (CoreException e) { String message = Policy.bind("resources.errorMoving", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Clear the natures and builders on the destination project. ProjectInfo info = (ProjectInfo) destination.getResourceInfo(false, true); info.clearNatures(); info.setBuilders(null); // Generate marker deltas. try { workspace.getMarkerManager().moved(source, destination, depth); } catch (CoreException e) { String message = Policy.bind("resources.errorMarkersMove", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } } // Set the new project description on the destination project. try { - destination.internalSetDescription(destDescription, false); + destination.internalSetDescription(destDescription, true); destination.writeDescription(IResource.FORCE); } catch (CoreException e) { String message = Policy.bind("resources.projectDesc"); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message, e); failed(status); } // If the locations are the not the same then make sure the new location is written to disk. // (or the old one removed) if (srcDescription.getLocation() == null) { if (destDescription.getLocation() != null) { try { workspace.getMetaArea().writeLocation(destination); } catch (CoreException e) { failed(e.getStatus()); } } } else { if (!srcDescription.getLocation().equals(destDescription.getLocation())) { try { workspace.getMetaArea().writeLocation(destination); } catch(CoreException e) { failed(e.getStatus()); } } } // Do a refresh on the destination project to pick up any newly discovered resources try { destination.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { String message = Policy.bind("resources.errorRefresh", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.ERROR, destination.getFullPath(), message, e); failed(status); return false; } return true; } /** * Returns the status object held onto by this resource tree. */ protected IStatus getStatus() { return status; } /** * @see IResourceTree#getTimestamp */ public long getTimestamp(IFile file) { Assert.isLegal(isValid); if (!file.exists()) return NULL_TIMESTAMP; ResourceInfo info = ((File) file).getResourceInfo(false, false); return info == null ? NULL_TIMESTAMP : info.getLocalSyncInfo(); } /** * @see IResourceTree#deletedFile(IFile) */ public void deletedFile(IFile file) { Assert.isLegal(isValid); // Do nothing if the resource doesn't exist. if (!file.exists()) return; try { // Delete properties, generate marker deltas, and remove the node from the workspace tree. ((Resource) file).deleteResource(true, null); } catch (CoreException e) { String message = Policy.bind("resources.errorDeleting", file.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, file.getFullPath(), message, e); failed(status); } } /** * @see IResourceTree#deletedFolder(IFolder) */ public void deletedFolder(IFolder folder) { Assert.isLegal(isValid); // Do nothing if the resource doesn't exist. if (!folder.exists()) return; try { // Delete properties, generate marker deltas, and remove the node from the workspace tree. ((Resource) folder).deleteResource(true, null); } catch (CoreException e) { String message = Policy.bind("resources.errorDeleting", folder.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, folder.getFullPath(), message, e); failed(status); } } /** * @see IResourceTree#deletedProject(IProject) */ public void deletedProject(IProject target) { Assert.isLegal(isValid); // Do nothing if the resource doesn't exist. if (!target.exists()) return; Project project = (Project) target; Workspace workspace = (Workspace) project.getWorkspace(); // Delete properties, generate marker deltas, and remove the node from the workspace tree. try { project.deleteResource(false, null); } catch (CoreException e) { String message = Policy.bind("resources.errorDeleting", project.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, project.getFullPath(), message, e); // log the status but don't return until we try and delete the rest of the project info failed(status); } // Delete the project metadata. try { workspace.getMetaArea().delete(project); } catch (CoreException e) { String message = Policy.bind("resources.deleteMeta", project.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_METADATA, project.getFullPath(), message, e); // log the status but don't return until we try and delete the rest of the project info failed(status); } // Clear the history store. try { project.clearHistory(null); } catch (CoreException e) { String message = Policy.bind("history.problemsRemoving", project.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, project.getFullPath(), message, e); failed(status); } } /** * This operation has failed for the given reason. Add it to this * resource tree's status. */ public void failed(IStatus reason) { Assert.isLegal(isValid); status.add(reason); } /** * Return <code>true</code> if there is a change in the name of the project. */ private boolean isNameChange(IProject project, IProjectDescription description) { return !project.getName().equals(description.getName()); } /** * Return <code>true</code> if there is a change in the content area for the project. */ private boolean isContentChange(IProject project, IProjectDescription destinationDescription) { IProjectDescription sourceDescription = ((Project) project).internalGetDescription(); if (sourceDescription.getLocation() == null || destinationDescription.getLocation() == null) return true; return !sourceDescription.getLocation().equals(destinationDescription.getLocation()); } /** * Returns <code>true</code> if we are doing a change in the case of the project name. */ private boolean isCaseChange(IProject project, IProjectDescription description) { return !project.getName().equals(description.getName()) && project.getName().equalsIgnoreCase(description.getName()); } /** * @see IResourceTree#isSynchronized(IResource, int) */ public boolean isSynchronized(IResource resource, int depth) { Assert.isLegal(isValid); UnifiedTree tree = new UnifiedTree(resource); String message = Policy.bind("resources.errorRefresh", resource.getFullPath().toString()); //$NON-NLS-1$ // FIXME: this visitor does too much work because it collects statuses for all // children who are out of sync. We could optimize by returning early when discovering // the first out of sync child. CollectSyncStatusVisitor visitor = new CollectSyncStatusVisitor(message, new NullProgressMonitor()); try { tree.accept(visitor, depth); } catch (CoreException e) { IStatus status = new ResourceStatus(IResourceStatus.FAILED_READ_LOCAL, resource.getFullPath(), message, e); failed(status); } return !visitor.resourcesChanged(); } /** * @see IResourceTree#computeTimestamp(IFile) */ public long computeTimestamp(IFile file) { Assert.isLegal(isValid); if (!file.getProject().exists()) return NULL_TIMESTAMP; return internalComputeTimestamp(file.getLocation().toOSString()); } /** * Return the timestamp of the file at the given location. */ protected long internalComputeTimestamp(String location) { return CoreFileSystemLibrary.getLastModified(location); } /** * @see IResourceTree#standardDeleteFile(IFile, int, IProgressMonitor) */ public void standardDeleteFile(IFile file, int updateFlags, IProgressMonitor monitor) { Assert.isLegal(isValid); internalDeleteFile(file, updateFlags, monitor); } /** * Helper method for #standardDeleteFile. Returns a boolean indicating whether or * not the delete was successful. */ private boolean internalDeleteFile(IFile file, int updateFlags, IProgressMonitor monitor) { try { String message = Policy.bind("resources.deleting", file.getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); // Do nothing if the file doesn't exist in the workspace. if (!file.exists()) { // Indicate that the delete was successful. return true; } // If the file doesn't exist on disk then signal to the workspace to delete the // file and return. java.io.File fileOnDisk = file.getLocation().toFile(); if (!fileOnDisk.exists()) { deletedFile(file); // Indicate that the delete was successful. return true; } boolean keepHistory = (updateFlags & IResource.KEEP_HISTORY) != 0; boolean force = (updateFlags & IResource.FORCE) != 0; // Add the file to the local history if requested by the user. if (keepHistory) addToLocalHistory(file); monitor.worked(Policy.totalWork/4); // We want to fail if force is false and the file is not synchronized with the // local file system. if (!force) { boolean inSync = isSynchronized(file, IResource.DEPTH_ZERO); // only want to fail if the file still exists. if (!inSync && file.getLocation().toFile().exists()) { message = Policy.bind("localstore.resourceIsOutOfSync", file.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.OUT_OF_SYNC_LOCAL, file.getFullPath(), message); failed(status); // Indicate that the delete was unsuccessful. return false; } } monitor.worked(Policy.totalWork/4); // Try to delete the file from the file system. boolean success = fileOnDisk.delete(); monitor.worked(Policy.totalWork/4); // If the file was successfully deleted from the file system the // workspace tree should be updated accordingly. Otherwise // we need to signal that a problem occurred. if (success) { deletedFile(file); // Indicate that the delete was successful. return true; } else { message = Policy.bind("resources.couldnotDelete", file.getLocation().toOSString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, file.getFullPath(), message); failed(status); // Indicate that the delete was unsuccessful. return false; } } finally { monitor.done(); } } /** * @see IResourceTree#standardDeleteFolder(IFolder, int, IProgressMonitor) */ public void standardDeleteFolder(IFolder folder, int updateFlags, IProgressMonitor monitor) { Assert.isLegal(isValid); try { String message = Policy.bind("resources.deleting", folder.getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); // Do nothing if the folder doesn't exist in the workspace. if (!folder.exists()) return; // If the folder doesn't exist on disk then update the tree and return. java.io.File folderOnDisk = folder.getLocation().toFile(); if (!folderOnDisk.exists()) { deletedFolder(folder); return; } // Check to see if we are synchronized with the local file system. If we are in sync then // we can short circuit this operation and delete all the files on disk, otherwise we have // to recursively try and delete them doing best-effort, thus leaving only the ones which // were out of sync. boolean force = (updateFlags & IResource.FORCE) != 0; if (!force && !isSynchronized(folder, IResource.DEPTH_INFINITE)) { // we are not in sync and force is false so delete via best effort boolean deletedChildren = internalDeleteFolder(folder, updateFlags, monitor); if (deletedChildren) { deletedFolder(folder); } else { message = Policy.bind("resources.couldnotDelete", folder.getLocation().toOSString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, folder.getFullPath(), message); failed(status); } return; } // Add the contents of the files to the local history if so requested by the user. boolean keepHistory = (updateFlags & IResource.KEEP_HISTORY) != 0; if (keepHistory) addToLocalHistory(folder, IResource.DEPTH_INFINITE); // If the folder was successfully deleted from the file system the // workspace tree should be updated accordingly. Otherwise // we need to signal that a problem occurred. boolean success = Workspace.clear(folder.getLocation().toFile()); if (success) { deletedFolder(folder); } else { message = Policy.bind("resources.couldnotDelete", folder.getLocation().toOSString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, folder.getFullPath(), message); failed(status); } } finally { monitor.done(); } } /** * Add this resource and all child files to the local history. Only adds content for * resources of type <code>IResource.FILE</code>. */ private void addToLocalHistory(IResource root, int depth) { IResourceVisitor visitor = new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { if (resource.getType() == IResource.FILE) addToLocalHistory((IFile) resource); return true; } }; try { root.accept(visitor, depth, false); } catch (CoreException e) { // We want to ignore any exceptions thrown by the history store because // they aren't enough to fail the operation as a whole. } } /** * Helper method for #standardDeleteFolder. Returns a boolean indicating * whether or not the deletion of this folder was successful. Does a best effort * delete of this resource and its children. */ private boolean internalDeleteFolder(IFolder folder, int updateFlags, IProgressMonitor monitor) { // Recursively delete each member of the folder. IResource[] members = null; try { members = folder.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); } catch (CoreException e) { String message = Policy.bind("resources.errorMembers", folder.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, folder.getFullPath(), message, e); failed(status); // Indicate that the delete was unsuccessful. return false; } boolean deletedChildren = true; for (int i=0; i<members.length; i++) { IResource child = members[i]; switch (child.getType()) { case IResource.FILE: deletedChildren &= internalDeleteFile((IFile) child, updateFlags, Policy.subMonitorFor(monitor, Policy.totalWork/members.length)); break; case IResource.FOLDER: deletedChildren &= internalDeleteFolder((IFolder) child, updateFlags, Policy.subMonitorFor(monitor, Policy.totalWork/members.length)); break; } } // Check to see if the children were deleted ok. If there was a problem // just return as the problem should have been logged by the recursive // call to the child. if (!deletedChildren) { // Indicate that the delete was unsuccessful. return false; } // Try to delete the folder from the local file system. This will fail // if the folder is not empty. No need to check the force flag since this is // an internal method and force is always false when we are here. java.io.File folderOnDisk = folder.getLocation().toFile(); boolean success = folderOnDisk.delete(); if (!success && !folderOnDisk.exists()) { // Indicate that the delete was successful. success = true; } if (success) { deletedFolder(folder); // Indicate that the delete was successful. return true; } else { String message = Policy.bind("resources.couldnotDelete", folder.getLocation().toOSString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, folder.getFullPath(), message); failed(status); // Indicate that the delete was unsuccessful. return false; } } /** * @see IResourceTree#standardDeleteProject(IProject, int, IProgressMonitor) */ public void standardDeleteProject(IProject project, int updateFlags, IProgressMonitor monitor) { Assert.isLegal(isValid); try { String message = Policy.bind("resources.deleting", project.getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); // Do nothing if the project doesn't exist in the workspace tree. if (!project.exists()) return; boolean alwaysDeleteContent = (updateFlags & IResource.ALWAYS_DELETE_PROJECT_CONTENT) != 0; // don't take force into account if we are always deleting the content boolean force = alwaysDeleteContent ? true : (updateFlags & IResource.FORCE) != 0; boolean neverDeleteContent = (updateFlags & IResource.NEVER_DELETE_PROJECT_CONTENT) != 0; boolean success = true; // Delete project content. Don't do anything if the user specified explicitly // not to delete the project content. if (alwaysDeleteContent || (project.isOpen() && !neverDeleteContent)) { // Check to see if we are synchronized with the local file system. If we are in sync then // we can short circuit this operation and delete all the files on disk, otherwise we have // to recursively try and delete them doing best-effort, thus leaving only the ones which // were out of sync. if (!force && !isSynchronized(project, IResource.DEPTH_INFINITE)) { // we are not in sync and force is false so delete via best effort success = internalDeleteProject(project, updateFlags, monitor); if (success) { deletedProject(project); } else { message = Policy.bind("resources.couldnotDelete", project.getLocation().toOSString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, project.getFullPath(), message); failed(status); } return; } // If the content area is in the default location then delete the directory and all its // children. If it is specified by the user then leave the directory itself but delete the children. java.io.File root = project.getLocation().toFile(); IProjectDescription description = ((Project) project).internalGetDescription(); if (description == null || description.getLocation() == null) { success = Workspace.clear(root); } else { success = true; String[] list = root.list(); // for some unknown reason, list() can return null. // Just skip the children If it does. if (list != null) for (int i = 0; i < list.length; i++) success &= Workspace.clear(new java.io.File(root, list[i])); } } // deleting project content is 75% of the work monitor.worked(Policy.totalWork*3/4); // Signal that the workspace tree should be updated that the project // has been deleted. if (success) { deletedProject(project); } else { message = Policy.bind("localstore.couldnotDelete", project.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, project.getFullPath(), message); failed(status); } } finally { monitor.done(); } } /** * Helper method for moving the project content. Determines the content location * based on the project description. (default location or user defined?) */ private void moveProjectContent(IProject source, IProjectDescription destDescription, int updateFlags, IProgressMonitor monitor) throws CoreException { try { IProjectDescription srcDescription = source.getDescription(); // If the locations are the same (and non-default) then there is nothing to do. if (srcDescription.getLocation() != null && srcDescription.getLocation().equals(destDescription)) return; IPath srcLocation = source.getLocation(); IPath destLocation = destDescription.getLocation(); // Use the default area if necessary for the destination. The source project // should already have a location assigned to it. if (destLocation == null) destLocation = Platform.getLocation().append(destDescription.getName()); // Move the contents on disk. moveInFileSystem(srcLocation.toFile(), destLocation.toFile(), updateFlags); } finally { monitor.done(); } } /** * @see IResourceTree#standardMoveFile(IFile, IFile, int, IProgressMonitor) */ public void standardMoveFile(IFile source, IFile destination, int updateFlags, IProgressMonitor monitor) { Assert.isLegal(isValid); try { String message = Policy.bind("resources.moving", source.getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); // These pre-conditions should all be ok but just in case... if (!source.exists() || destination.exists() || !destination.getParent().isAccessible()) throw new IllegalArgumentException(); boolean force = (updateFlags & IResource.FORCE) != 0; boolean keepHistory = (updateFlags & IResource.KEEP_HISTORY) != 0; // If the file is not in sync with the local file system and force is false, // then signal that we have an error. if (force && !source.getLocation().toFile().exists()) { message = Policy.bind("localstore.resourceIsOutOfSync", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.OUT_OF_SYNC_LOCAL, source.getFullPath(), message); failed(status); return; } else { boolean inSync = isSynchronized(source, IResource.DEPTH_ZERO); if (!inSync) { message = Policy.bind("localstore.resourceIsOutOfSync", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.OUT_OF_SYNC_LOCAL, source.getFullPath(), message); failed(status); return; } } monitor.worked(Policy.totalWork/4); // Add the file contents to the local history if requested by the user. if (keepHistory) addToLocalHistory(source); monitor.worked(Policy.totalWork/4); java.io.File sourceFile = source.getLocation().toFile(); java.io.File destFile = destination.getLocation().toFile(); // If the file was successfully moved in the file system then the workspace // tree needs to be updated accordingly. Otherwise signal that we have an error. try { moveInFileSystem(sourceFile, destFile, updateFlags); } catch (CoreException e) { message = Policy.bind("localstore.couldnotMove", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.ERROR, source.getFullPath(), message, e); failed(status); return; } movedFile(source, destination); updateMovedFileTimestamp(destination, computeTimestamp(destination)); monitor.worked(Policy.totalWork/4); return; } finally { monitor.done(); } } /** * @see IResourceTree#standardMoveFolder(IFolder, IFolder, int, IProgressMonitor) */ public void standardMoveFolder(IFolder source, IFolder destination, int updateFlags, IProgressMonitor monitor) { Assert.isLegal(isValid); try { String message = Policy.bind("resources.moving", source.getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); // These pre-conditions should all be ok but just in case... if (!source.exists() || destination.exists() || !destination.getParent().isAccessible()) throw new IllegalArgumentException(); // Check to see if we are synchronized with the local file system. If we are in sync then we can // short circuit this method and do a file system only move. Otherwise we have to recursively // try and move all resources, doing it in a best-effort manner. boolean force = (updateFlags & IResource.FORCE) != 0; if (!force && !isSynchronized(source, IResource.DEPTH_INFINITE)) { message = Policy.bind("localstore.resourceIsOutOfSync", source.getFullPath().toString());//$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.ERROR, source.getFullPath(), message); failed(status); return; } // keep history boolean keepHistory = (updateFlags & IResource.KEEP_HISTORY) != 0; if (keepHistory) addToLocalHistory(source, IResource.DEPTH_INFINITE); // Move the resources in the file system. Only the FORCE flag is valid here so don't // have to worry about clearing the KEEP_HISTORY flag. try { moveInFileSystem(source.getLocation().toFile(), destination.getLocation().toFile(), updateFlags); } catch (CoreException e) { message = Policy.bind("resources.errorMove"); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_WRITE_LOCAL, destination.getFullPath(), message, e); failed(status); return; } boolean success = destination.getLocation().toFile().exists(); success &= !source.getLocation().toFile().exists(); if (success) { movedFolderSubtree(source, destination); updateTimestamps(destination); } else { message = Policy.bind("localstore.couldNotCreateFolder", destination.getLocation().toOSString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_WRITE_LOCAL, destination.getFullPath(), message); failed(status); } } finally { monitor.done(); } } /** * Helper method to update all the timestamps in the tree to match * those in the file system. Used after a #move. */ private void updateTimestamps(IResource root) { IResourceVisitor visitor = new IResourceVisitor() { public boolean visit(IResource resource) { if (resource.getType() == IResource.FILE) { IFile file = (IFile) resource; long timestamp = computeTimestamp(file); updateMovedFileTimestamp(file, timestamp); } return true; } }; try { root.accept(visitor, IResource.DEPTH_INFINITE, IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); } catch(CoreException e) { // No exception should be thrown. } } /** * Does a best-effort delete on this resource and all its children. */ private boolean internalDeleteProject(IProject project, int updateFlags, IProgressMonitor monitor) { // Recursively delete each member of the project. IResource[] members = null; try { members = project.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); } catch (CoreException e) { String message = Policy.bind("resources.errorMembers", project.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, project.getFullPath(), message, e); failed(status); // Indicate that the delete was unsuccessful. return false; } boolean deletedChildren = true; for (int i=0; i<members.length; i++) { IResource child = members[i]; switch (child.getType()) { case IResource.FILE: if (child.getName().equals(IProjectDescription.DESCRIPTION_FILE_NAME)) { // ignore the .project file for now and delete it last } else { deletedChildren &= internalDeleteFile((IFile) child, updateFlags, Policy.subMonitorFor(monitor, Policy.totalWork/members.length)); } break; case IResource.FOLDER: deletedChildren &= internalDeleteFolder((IFolder) child, updateFlags, Policy.subMonitorFor(monitor, Policy.totalWork/members.length)); break; } } // Check to see if the children were deleted ok. If there was a problem // just return as the problem should have been logged by the recursive // call to the child. if (deletedChildren) { IResource file = project.findMember(IProjectDescription.DESCRIPTION_FILE_NAME); if (file == null) { // For some reason the .project file doesn't exist, so continue with the project // deletion and pretend we deleted it already. } else { if (file.getType() != IResource.FILE) { // We should never get here since the only reason we skipped it above was because // it was a file named .project. String message = Policy.bind("resources.couldnotDelete", file.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, file.getFullPath(), message); failed(status); // Indicate that the delete was unsuccessful. return false; } else { boolean deletedProjectFile = internalDeleteFile((IFile) file, updateFlags, Policy.monitorFor(null)); if (!deletedProjectFile) { String message = Policy.bind("resources.couldnotDelete", file.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, file.getFullPath(), message); failed(status); // Indicate that the delete was unsuccessful. return false; } } } } else { // Indicate that the delete was unsuccessful. return false; } // If the content area is in the default location then delete the directory and all its // children. If it is specified by the user then leave the directory itself but delete the children. // No need to check the force flag since this is an internal method and by the time we // get here we know that force is false. java.io.File root = project.getLocation().toFile(); IProjectDescription description = ((Project) project).internalGetDescription(); // If we have a user-defined location delete the directory, otherwise just see if its empty boolean success; if (description == null || description.getLocation() == null) { success = root.delete(); if (!success && !root.exists()) { success = true; } } else { String[] children = root.list(); success = children == null || children.length == 0; } if (success) { deletedProject(project); // Indicate that the delete was successful. return true; } else { String message = Policy.bind("resources.couldnotDelete", project.getLocation().toOSString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, project.getFullPath(), message); failed(status); // Indicate that the delete was unsuccessful. return false; } } /** * @see IResourceTree#standardMoveProject(IProject, IProjectDescription, int, IProgressMonitor) */ public void standardMoveProject(IProject source, IProjectDescription description, int updateFlags, IProgressMonitor monitor) { Assert.isLegal(isValid); try { String message = Policy.bind("resources.moving", source.getFullPath().toString()); //$NON-NLS-1$ monitor.beginTask(message, Policy.totalWork); // Double-check this pre-condition. if (!source.isAccessible()) throw new IllegalArgumentException(); // If there is nothing to do on disk then signal to make the workspace tree // changes. if (!isContentChange(source, description)) { movedProjectSubtree(source, description); return; } // Check to see if we are synchronized with the local file system. boolean force = (updateFlags & IResource.FORCE) != 0; if (!force && !isSynchronized(source, IResource.DEPTH_INFINITE)) { // FIXME: make this a best effort move? message = Policy.bind("localstore.resourceIsOutOfSync", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.OUT_OF_SYNC_LOCAL, source.getFullPath(), message); failed(status); return; } // Move the project content in the local file system. try { moveProjectContent(source, description, updateFlags, Policy.subMonitorFor(monitor, Policy.totalWork*3/4)); } catch (CoreException e) { message = Policy.bind("localstore.couldnotMove", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); failed(status); return; } // If we got this far the project content has been moved on disk (if necessary) // and we need to update the workspace tree. movedProjectSubtree(source, description); updateTimestamps(source.getWorkspace().getRoot().getProject(description.getName())); } finally { monitor.done(); } } /** * Move the contents of the specified file from the source location to the destination location. * If the source points to a directory then move that directory and all its contents. * * <code>IResource.FORCE</code> is the only valid flag. */ private void moveInFileSystem(java.io.File source, java.io.File destination, int updateFlags) throws CoreException { Assert.isLegal(isValid); FileSystemStore store = ((Resource) ResourcesPlugin.getWorkspace().getRoot()).getLocalManager().getStore(); boolean force = (updateFlags & IResource.FORCE) != 0; store.move(source, destination, force, Policy.monitorFor(null)); } /** * @see IResourceTree#updateMovedFileTimestamp(IFile, long) */ public void updateMovedFileTimestamp(IFile file, long timestamp) { Assert.isLegal(isValid); // Do nothing if the file doesn't exist in the workspace tree. if (!file.exists()) return; // Update the timestamp in the tree. ResourceInfo info = ((Resource) file).getResourceInfo(false, true); // The info should never be null since we just checked that the resource exists in the tree. ((Resource) file).getLocalManager().updateLocalSync(info, timestamp, true); } }
true
true
public boolean movedProjectSubtree(IProject project, IProjectDescription destDescription) { Assert.isLegal(isValid); // Do nothing if the source resource doesn't exist. if (!project.exists()) return true; Project source = (Project) project; Project destination = (Project) source.getWorkspace().getRoot().getProject(destDescription.getName()); IProjectDescription srcDescription = source.internalGetDescription(); Workspace workspace = (Workspace) source.getWorkspace(); int depth = IResource.DEPTH_INFINITE; // If the name of the source and destination projects are not the same then // rename the meta area and make changes in the tree. if (isNameChange(source, destDescription)) { if (destination.exists()) { String message = Policy.bind("resources.mustNotExist", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message); failed(status); return false; } // Rename the project metadata area. Close the property store so bogus values // aren't copied to the destination. // FIXME: do we need to do this? try { source.getPropertyManager().closePropertyStore(source); } catch (CoreException e) { String message = Policy.bind("properties.couldNotClose", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } java.io.File oldMetaArea = workspace.getMetaArea().locationFor(source).toFile(); java.io.File newMetaArea = workspace.getMetaArea().locationFor(destination).toFile(); try{ source.getLocalManager().getStore().move(oldMetaArea, newMetaArea, false, new NullProgressMonitor()); } catch (CoreException e) { String message = Policy.bind("resources.moveMeta", oldMetaArea.toString(), newMetaArea.toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_WRITE_METADATA, destination.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Move the workspace tree. try { workspace.move(source, destination.getFullPath(), depth, false); } catch (CoreException e) { String message = Policy.bind("resources.errorMoving", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Clear the natures and builders on the destination project. ProjectInfo info = (ProjectInfo) destination.getResourceInfo(false, true); info.clearNatures(); info.setBuilders(null); // Generate marker deltas. try { workspace.getMarkerManager().moved(source, destination, depth); } catch (CoreException e) { String message = Policy.bind("resources.errorMarkersMove", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } } // Set the new project description on the destination project. try { destination.internalSetDescription(destDescription, false); destination.writeDescription(IResource.FORCE); } catch (CoreException e) { String message = Policy.bind("resources.projectDesc"); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message, e); failed(status); } // If the locations are the not the same then make sure the new location is written to disk. // (or the old one removed) if (srcDescription.getLocation() == null) { if (destDescription.getLocation() != null) { try { workspace.getMetaArea().writeLocation(destination); } catch (CoreException e) { failed(e.getStatus()); } } } else { if (!srcDescription.getLocation().equals(destDescription.getLocation())) { try { workspace.getMetaArea().writeLocation(destination); } catch(CoreException e) { failed(e.getStatus()); } } } // Do a refresh on the destination project to pick up any newly discovered resources try { destination.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { String message = Policy.bind("resources.errorRefresh", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.ERROR, destination.getFullPath(), message, e); failed(status); return false; } return true; }
public boolean movedProjectSubtree(IProject project, IProjectDescription destDescription) { Assert.isLegal(isValid); // Do nothing if the source resource doesn't exist. if (!project.exists()) return true; Project source = (Project) project; Project destination = (Project) source.getWorkspace().getRoot().getProject(destDescription.getName()); IProjectDescription srcDescription = source.internalGetDescription(); Workspace workspace = (Workspace) source.getWorkspace(); int depth = IResource.DEPTH_INFINITE; // If the name of the source and destination projects are not the same then // rename the meta area and make changes in the tree. if (isNameChange(source, destDescription)) { if (destination.exists()) { String message = Policy.bind("resources.mustNotExist", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message); failed(status); return false; } // Rename the project metadata area. Close the property store so bogus values // aren't copied to the destination. // FIXME: do we need to do this? try { source.getPropertyManager().closePropertyStore(source); } catch (CoreException e) { String message = Policy.bind("properties.couldNotClose", source.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } java.io.File oldMetaArea = workspace.getMetaArea().locationFor(source).toFile(); java.io.File newMetaArea = workspace.getMetaArea().locationFor(destination).toFile(); try{ source.getLocalManager().getStore().move(oldMetaArea, newMetaArea, false, new NullProgressMonitor()); } catch (CoreException e) { String message = Policy.bind("resources.moveMeta", oldMetaArea.toString(), newMetaArea.toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.FAILED_WRITE_METADATA, destination.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Move the workspace tree. try { workspace.move(source, destination.getFullPath(), depth, false); } catch (CoreException e) { String message = Policy.bind("resources.errorMoving", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } // Clear the natures and builders on the destination project. ProjectInfo info = (ProjectInfo) destination.getResourceInfo(false, true); info.clearNatures(); info.setBuilders(null); // Generate marker deltas. try { workspace.getMarkerManager().moved(source, destination, depth); } catch (CoreException e) { String message = Policy.bind("resources.errorMarkersMove", source.getFullPath().toString(), destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, e); // log the status but don't return until we try and move the rest of the resource info failed(status); } } // Set the new project description on the destination project. try { destination.internalSetDescription(destDescription, true); destination.writeDescription(IResource.FORCE); } catch (CoreException e) { String message = Policy.bind("resources.projectDesc"); //$NON-NLS-1$ IStatus status = new ResourceStatus(IStatus.ERROR, destination.getFullPath(), message, e); failed(status); } // If the locations are the not the same then make sure the new location is written to disk. // (or the old one removed) if (srcDescription.getLocation() == null) { if (destDescription.getLocation() != null) { try { workspace.getMetaArea().writeLocation(destination); } catch (CoreException e) { failed(e.getStatus()); } } } else { if (!srcDescription.getLocation().equals(destDescription.getLocation())) { try { workspace.getMetaArea().writeLocation(destination); } catch(CoreException e) { failed(e.getStatus()); } } } // Do a refresh on the destination project to pick up any newly discovered resources try { destination.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { String message = Policy.bind("resources.errorRefresh", destination.getFullPath().toString()); //$NON-NLS-1$ IStatus status = new ResourceStatus(IResourceStatus.ERROR, destination.getFullPath(), message, e); failed(status); return false; } return true; }
diff --git a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/WebReset.java b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/WebReset.java index cd6bf939..6ffb33e6 100644 --- a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/WebReset.java +++ b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/WebReset.java @@ -1,216 +1,216 @@ package org.collectionspace.chain.csp.webui.misc; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.collectionspace.chain.csp.config.ConfigException; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.TTYOutputter; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WebReset implements WebMethod { private static final Logger log=LoggerFactory.getLogger(WebReset.class); private boolean quick; public WebReset(boolean in) { quick=in; } // XXX refactor private JSONObject getJSONResource(String in) throws IOException, JSONException { return new JSONObject(getResource(in)); } // XXX refactor private String getResource(String in) throws IOException, JSONException { String path=getClass().getPackage().getName().replaceAll("\\.","/"); InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream(path+"/"+in); log.debug(path); String data=IOUtils.toString(stream); stream.close(); return data; } private void reset(Storage storage,UIRequest request) throws UIException { //remember to log into the fornt end before trying to run this // Temporary hack to reset db try { TTYOutputter tty=request.getTTYOutputter(); // Delete existing records JSONObject data = storage.getPathsJSON("/",null); String[] paths = (String[]) data.get("listItems"); for(String dir : paths) { // XXX yuck! // ignore authorities if("place".equals(dir) || "vocab".equals(dir) || "contact".equals(dir) || "person".equals(dir) || "organization".equals(dir)){ continue; } // ignore authorization - if("rolePermission".equals(dir) || "accountrole".equals(dir) || "permrole".equals(dir) || "permission".equals(dir) || "role".equals(dir) || "users".equals(dir) ){ + if("rolePermission".equals(dir) || "accountrole".equals(dir) || "permrole".equals(dir) || "permission".equals(dir) || "role".equals(dir)|| "userrole".equals(dir) || "users".equals(dir) ){ continue; } // ignore other - tho we do need to clean these up if("relations".equals(dir) || "direct".equals(dir) || "id".equals(dir) ) continue; tty.line("dir : "+dir); data = storage.getPathsJSON(dir,null); paths = (String[]) data.get("listItems"); for(int i=0;i<paths.length;i++) { tty.line("path : "+dir+"/"+paths[i]); try { storage.deleteJSON(dir+"/"+paths[i]); } catch (UnimplementedException e) { // Never mind tty.line("ux"); } catch (UnderlyingStorageException e) { tty.line("UnderlyingStorageEception"); } tty.line("ok"); tty.flush(); } } // Create records anew tty.line("Create records anew"); String schedule=getResource("reset.txt"); for(String line : schedule.split("\n")) { String[] parts=line.split(" +",2); tty.line("Creating "+parts[0]); storage.autocreateJSON(parts[0],getJSONResource(parts[1])); tty.flush(); } // Delete existing vocab entries JSONObject myjs = new JSONObject(); myjs.put("pageSize", "100"); myjs.put("pageNum", "0"); int resultsize=1; int check = 0; String checkpagination = ""; tty.line("Delete existing vocab entries"); while(resultsize >0){ myjs.put("pageNum", check); //check++; //don't increment page num as need to call page 0 as //once you delete a page worth the next page is now the current page data = storage.getPathsJSON("/person/person",myjs); String[] res = (String[]) data.get("listItems"); if(res.length==0 || checkpagination.equals(res[0])){ resultsize=0; break; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = res[0]; } resultsize=res.length; for(String urn : res) { try { storage.deleteJSON("/person/person/"+urn); tty.line("Deleting Person "+urn); } catch(Exception e) { /* Sometimes records are wdged */ } tty.flush(); } } resultsize=1; check = 0; checkpagination = ""; while(resultsize >0){ myjs.put("pageNum", check); //check++; //don't increment page num as need to call page 0 as //once you delete a page worth the next page is now the current page data = storage.getPathsJSON("/organization/organization",myjs); String[] res = (String[]) data.get("listItems"); if(res.length==0 || checkpagination.equals(res[0])){ resultsize=0; break; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = res[0]; } resultsize=res.length; for(String urn : res) { try { storage.deleteJSON("/organization/organization/"+urn); tty.line("Deleting Organization "+urn); } catch(Exception e) { /* Sometimes records are wdged */ } tty.flush(); } } tty.line("Creating"); tty.flush(); // Create vocab entries String names=getResource("names.txt"); int i=0; for(String line : names.split("\n")) { i++; JSONObject name=new JSONObject(); name.put("displayName",line); storage.autocreateJSON("/person/person",name); tty.line("Created Person "+name); tty.flush(); if(quick && i>20) break; } // Create vocab entries String orgs=getResource("orgs.txt"); i=0; for(String line : orgs.split("\n")) { i++; JSONObject name=new JSONObject(); name.put("displayName",line); storage.autocreateJSON("/organization/organization",name); tty.line("Created Organisation "+line); tty.flush(); if(quick && i>20) break; } tty.line("done"); } catch (ExistException e) { throw new UIException("Existence problem",e); } catch (UnimplementedException e) { throw new UIException("Unimplemented ",e); } catch (UnderlyingStorageException e) { throw new UIException("Problem storing",e); } catch (JSONException e) { throw new UIException("Invalid JSON",e); } catch (IOException e) { throw new UIException("IOException",e); } } public void run(Object in,String[] tail) throws UIException { Request q=(Request)in; reset(q.getStorage(),q.getUIRequest()); } public void configure() throws ConfigException {} public void configure(WebUI ui,Spec spec) {} }
true
true
private void reset(Storage storage,UIRequest request) throws UIException { //remember to log into the fornt end before trying to run this // Temporary hack to reset db try { TTYOutputter tty=request.getTTYOutputter(); // Delete existing records JSONObject data = storage.getPathsJSON("/",null); String[] paths = (String[]) data.get("listItems"); for(String dir : paths) { // XXX yuck! // ignore authorities if("place".equals(dir) || "vocab".equals(dir) || "contact".equals(dir) || "person".equals(dir) || "organization".equals(dir)){ continue; } // ignore authorization if("rolePermission".equals(dir) || "accountrole".equals(dir) || "permrole".equals(dir) || "permission".equals(dir) || "role".equals(dir) || "users".equals(dir) ){ continue; } // ignore other - tho we do need to clean these up if("relations".equals(dir) || "direct".equals(dir) || "id".equals(dir) ) continue; tty.line("dir : "+dir); data = storage.getPathsJSON(dir,null); paths = (String[]) data.get("listItems"); for(int i=0;i<paths.length;i++) { tty.line("path : "+dir+"/"+paths[i]); try { storage.deleteJSON(dir+"/"+paths[i]); } catch (UnimplementedException e) { // Never mind tty.line("ux"); } catch (UnderlyingStorageException e) { tty.line("UnderlyingStorageEception"); } tty.line("ok"); tty.flush(); } } // Create records anew tty.line("Create records anew"); String schedule=getResource("reset.txt"); for(String line : schedule.split("\n")) { String[] parts=line.split(" +",2); tty.line("Creating "+parts[0]); storage.autocreateJSON(parts[0],getJSONResource(parts[1])); tty.flush(); } // Delete existing vocab entries JSONObject myjs = new JSONObject(); myjs.put("pageSize", "100"); myjs.put("pageNum", "0"); int resultsize=1; int check = 0; String checkpagination = ""; tty.line("Delete existing vocab entries"); while(resultsize >0){ myjs.put("pageNum", check); //check++; //don't increment page num as need to call page 0 as //once you delete a page worth the next page is now the current page data = storage.getPathsJSON("/person/person",myjs); String[] res = (String[]) data.get("listItems"); if(res.length==0 || checkpagination.equals(res[0])){ resultsize=0; break; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = res[0]; } resultsize=res.length; for(String urn : res) { try { storage.deleteJSON("/person/person/"+urn); tty.line("Deleting Person "+urn); } catch(Exception e) { /* Sometimes records are wdged */ } tty.flush(); } } resultsize=1; check = 0; checkpagination = ""; while(resultsize >0){ myjs.put("pageNum", check); //check++; //don't increment page num as need to call page 0 as //once you delete a page worth the next page is now the current page data = storage.getPathsJSON("/organization/organization",myjs); String[] res = (String[]) data.get("listItems"); if(res.length==0 || checkpagination.equals(res[0])){ resultsize=0; break; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = res[0]; } resultsize=res.length; for(String urn : res) { try { storage.deleteJSON("/organization/organization/"+urn); tty.line("Deleting Organization "+urn); } catch(Exception e) { /* Sometimes records are wdged */ } tty.flush(); } } tty.line("Creating"); tty.flush(); // Create vocab entries String names=getResource("names.txt"); int i=0; for(String line : names.split("\n")) { i++; JSONObject name=new JSONObject(); name.put("displayName",line); storage.autocreateJSON("/person/person",name); tty.line("Created Person "+name); tty.flush(); if(quick && i>20) break; } // Create vocab entries String orgs=getResource("orgs.txt"); i=0; for(String line : orgs.split("\n")) { i++; JSONObject name=new JSONObject(); name.put("displayName",line); storage.autocreateJSON("/organization/organization",name); tty.line("Created Organisation "+line); tty.flush(); if(quick && i>20) break; } tty.line("done"); } catch (ExistException e) { throw new UIException("Existence problem",e); } catch (UnimplementedException e) { throw new UIException("Unimplemented ",e); } catch (UnderlyingStorageException e) { throw new UIException("Problem storing",e); } catch (JSONException e) { throw new UIException("Invalid JSON",e); } catch (IOException e) { throw new UIException("IOException",e); } }
private void reset(Storage storage,UIRequest request) throws UIException { //remember to log into the fornt end before trying to run this // Temporary hack to reset db try { TTYOutputter tty=request.getTTYOutputter(); // Delete existing records JSONObject data = storage.getPathsJSON("/",null); String[] paths = (String[]) data.get("listItems"); for(String dir : paths) { // XXX yuck! // ignore authorities if("place".equals(dir) || "vocab".equals(dir) || "contact".equals(dir) || "person".equals(dir) || "organization".equals(dir)){ continue; } // ignore authorization if("rolePermission".equals(dir) || "accountrole".equals(dir) || "permrole".equals(dir) || "permission".equals(dir) || "role".equals(dir)|| "userrole".equals(dir) || "users".equals(dir) ){ continue; } // ignore other - tho we do need to clean these up if("relations".equals(dir) || "direct".equals(dir) || "id".equals(dir) ) continue; tty.line("dir : "+dir); data = storage.getPathsJSON(dir,null); paths = (String[]) data.get("listItems"); for(int i=0;i<paths.length;i++) { tty.line("path : "+dir+"/"+paths[i]); try { storage.deleteJSON(dir+"/"+paths[i]); } catch (UnimplementedException e) { // Never mind tty.line("ux"); } catch (UnderlyingStorageException e) { tty.line("UnderlyingStorageEception"); } tty.line("ok"); tty.flush(); } } // Create records anew tty.line("Create records anew"); String schedule=getResource("reset.txt"); for(String line : schedule.split("\n")) { String[] parts=line.split(" +",2); tty.line("Creating "+parts[0]); storage.autocreateJSON(parts[0],getJSONResource(parts[1])); tty.flush(); } // Delete existing vocab entries JSONObject myjs = new JSONObject(); myjs.put("pageSize", "100"); myjs.put("pageNum", "0"); int resultsize=1; int check = 0; String checkpagination = ""; tty.line("Delete existing vocab entries"); while(resultsize >0){ myjs.put("pageNum", check); //check++; //don't increment page num as need to call page 0 as //once you delete a page worth the next page is now the current page data = storage.getPathsJSON("/person/person",myjs); String[] res = (String[]) data.get("listItems"); if(res.length==0 || checkpagination.equals(res[0])){ resultsize=0; break; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = res[0]; } resultsize=res.length; for(String urn : res) { try { storage.deleteJSON("/person/person/"+urn); tty.line("Deleting Person "+urn); } catch(Exception e) { /* Sometimes records are wdged */ } tty.flush(); } } resultsize=1; check = 0; checkpagination = ""; while(resultsize >0){ myjs.put("pageNum", check); //check++; //don't increment page num as need to call page 0 as //once you delete a page worth the next page is now the current page data = storage.getPathsJSON("/organization/organization",myjs); String[] res = (String[]) data.get("listItems"); if(res.length==0 || checkpagination.equals(res[0])){ resultsize=0; break; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } else{ checkpagination = res[0]; } resultsize=res.length; for(String urn : res) { try { storage.deleteJSON("/organization/organization/"+urn); tty.line("Deleting Organization "+urn); } catch(Exception e) { /* Sometimes records are wdged */ } tty.flush(); } } tty.line("Creating"); tty.flush(); // Create vocab entries String names=getResource("names.txt"); int i=0; for(String line : names.split("\n")) { i++; JSONObject name=new JSONObject(); name.put("displayName",line); storage.autocreateJSON("/person/person",name); tty.line("Created Person "+name); tty.flush(); if(quick && i>20) break; } // Create vocab entries String orgs=getResource("orgs.txt"); i=0; for(String line : orgs.split("\n")) { i++; JSONObject name=new JSONObject(); name.put("displayName",line); storage.autocreateJSON("/organization/organization",name); tty.line("Created Organisation "+line); tty.flush(); if(quick && i>20) break; } tty.line("done"); } catch (ExistException e) { throw new UIException("Existence problem",e); } catch (UnimplementedException e) { throw new UIException("Unimplemented ",e); } catch (UnderlyingStorageException e) { throw new UIException("Problem storing",e); } catch (JSONException e) { throw new UIException("Invalid JSON",e); } catch (IOException e) { throw new UIException("IOException",e); } }
diff --git a/otp-rest-api/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java b/otp-rest-api/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java index ccda549a0..d457b6be9 100644 --- a/otp-rest-api/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java +++ b/otp-rest-api/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java @@ -1,1050 +1,1050 @@ /* 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 (props, at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentripplanner.api.ws; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Set; import java.util.TimeZone; import org.onebusaway.gtfs.model.Agency; import org.onebusaway.gtfs.model.Trip; import org.onebusaway.gtfs.model.calendar.CalendarServiceData; import org.opentripplanner.api.model.Itinerary; import org.opentripplanner.api.model.Leg; import org.opentripplanner.api.model.Place; import org.opentripplanner.api.model.RelativeDirection; import org.opentripplanner.api.model.TripPlan; import org.opentripplanner.api.model.WalkStep; import org.opentripplanner.common.geometry.DirectionUtils; import org.opentripplanner.common.geometry.GeometryUtils; import org.opentripplanner.common.geometry.PackedCoordinateSequence; import org.opentripplanner.common.model.P2; import org.opentripplanner.routing.core.RoutingContext; import org.opentripplanner.routing.core.RoutingRequest; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.TraverseMode; import org.opentripplanner.routing.edgetype.AreaEdge; import org.opentripplanner.routing.edgetype.DwellEdge; import org.opentripplanner.routing.edgetype.EdgeWithElevation; import org.opentripplanner.routing.edgetype.ElevatorAlightEdge; import org.opentripplanner.routing.edgetype.ElevatorBoardEdge; import org.opentripplanner.routing.edgetype.ElevatorEdge; import org.opentripplanner.routing.edgetype.FreeEdge; import org.opentripplanner.routing.edgetype.HopEdge; import org.opentripplanner.routing.edgetype.LegSwitchingEdge; import org.opentripplanner.routing.edgetype.OnBoardForwardEdge; import org.opentripplanner.routing.edgetype.PatternHop; import org.opentripplanner.routing.edgetype.PlainStreetEdge; import org.opentripplanner.routing.edgetype.PreAlightEdge; import org.opentripplanner.routing.edgetype.PreBoardEdge; import org.opentripplanner.routing.edgetype.StreetEdge; import org.opentripplanner.routing.error.PathNotFoundException; import org.opentripplanner.routing.error.TrivialPathException; import org.opentripplanner.routing.error.VertexNotFoundException; import org.opentripplanner.routing.graph.Edge; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.graph.Vertex; import org.opentripplanner.routing.patch.Alert; import org.opentripplanner.routing.services.FareService; import org.opentripplanner.routing.services.GraphService; import org.opentripplanner.routing.services.PathService; import org.opentripplanner.routing.services.TransitIndexService; import org.opentripplanner.routing.spt.GraphPath; import org.opentripplanner.routing.trippattern.TripTimes; import org.opentripplanner.routing.vertextype.ExitVertex; import org.opentripplanner.routing.vertextype.TransitVertex; import org.opentripplanner.util.PolylineEncoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; @Service @Scope("singleton") public class PlanGenerator { private static final Logger LOG = LoggerFactory.getLogger(PlanGenerator.class); private static final double MAX_ZAG_DISTANCE = 30; @Autowired public PathService pathService; @Autowired GraphService graphService; /** Generates a TripPlan from a Request */ public TripPlan generate(RoutingRequest options) { // TODO: this seems to only check the endpoints, which are usually auto-generated //if ( ! options.isAccessible()) // throw new LocationNotAccessible(); /* try to plan the trip */ List<GraphPath> paths = null; boolean tooSloped = false; try { paths = pathService.getPaths(options); if (paths == null && options.isWheelchairAccessible()) { // There are no paths that meet the user's slope restrictions. // Try again without slope restrictions (and warn user). options.maxSlope = Double.MAX_VALUE; paths = pathService.getPaths(options); tooSloped = true; } } catch (VertexNotFoundException e) { LOG.info("Vertex not found: " + options.getFrom() + " : " + options.getTo(), e); throw e; } if (paths == null || paths.size() == 0) { LOG.info("Path not found: " + options.getFrom() + " : " + options.getTo()); throw new PathNotFoundException(); } TripPlan plan = generatePlan(paths, options); if (plan != null) { for (Itinerary i : plan.itinerary) { i.tooSloped = tooSloped; /* fix up from/to on first/last legs */ if (i.legs.size() == 0) { LOG.warn("itinerary has no legs"); continue; } Leg firstLeg = i.legs.get(0); firstLeg.from.orig = options.getFrom().getName(); Leg lastLeg = i.legs.get(i.legs.size() - 1); lastLeg.to.orig = options.getTo().getName(); } } return plan; } /** * Generates a TripPlan from a set of paths */ public TripPlan generatePlan(List<GraphPath> paths, RoutingRequest request) { GraphPath exemplar = paths.get(0); Vertex tripStartVertex = exemplar.getStartVertex(); Vertex tripEndVertex = exemplar.getEndVertex(); String startName = tripStartVertex.getName(); String endName = tripEndVertex.getName(); // Use vertex labels if they don't have names if (startName == null) { startName = tripStartVertex.getLabel(); } if (endName == null) { endName = tripEndVertex.getLabel(); } Place from = new Place(tripStartVertex.getX(), tripStartVertex.getY(), startName); Place to = new Place(tripEndVertex.getX(), tripEndVertex.getY(), endName); TripPlan plan = new TripPlan(from, to, request.getDateTime()); for (GraphPath path : paths) { Itinerary itinerary = generateItinerary(path, request.isShowIntermediateStops()); plan.addItinerary(itinerary); } return plan; } /** * Generate an itinerary from a @{link GraphPath}. The algorithm here is to walk over each state * in the graph path, accumulating geometry, time, and length data from the incoming edge. When * the incoming edge and outgoing edge have different modes (or when a vehicle changes names due * to interlining) a new leg is generated. Street legs undergo an additional processing step to * generate turn-by-turn directions. * * @param path * @param showIntermediateStops whether intermediate stops are included in the generated * itinerary * @return itinerary */ private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Graph graph = path.getRoutingContext().graph; TransitIndexService transitIndex = graph.getService(TransitIndexService.class); Itinerary itinerary = makeEmptyItinerary(path); Set<Alert> postponedAlerts = null; Leg leg = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); double previousElevation = Double.MAX_VALUE; int startWalk = -1; int i = -1; boolean foldingElevatorLegIntoCycleLeg = false; PlanGenState pgstate = PlanGenState.START; String nextName = null; for (State state : path.states) { i += 1; Edge backEdge = state.getBackEdge(); if (backEdge == null) { continue; } TraverseMode mode = state.getBackMode(); if (mode != null) { long dt = state.getAbsTimeDeltaSeconds(); if (mode == TraverseMode.BOARDING || mode == TraverseMode.ALIGHTING || mode == TraverseMode.STL) { itinerary.waitingTime += dt; } else if (mode.isOnStreetNonTransit()) { itinerary.walkTime += dt; } else if (mode.isTransit()) { itinerary.transitTime += dt; } } if (backEdge instanceof FreeEdge) { if (backEdge instanceof PreBoardEdge) { // Add boarding alerts to the next leg postponedAlerts = state.getBackAlerts(); } else if (backEdge instanceof PreAlightEdge) { // Add alighting alerts to the previous leg, if any if (itinerary.legs.size() > 0) addNotesToLeg(itinerary.legs.get(itinerary.legs.size() - 1), state.getBackAlerts()); } continue; } if (backEdge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } switch (pgstate) { case START: if (mode == TraverseMode.WALK) { pgstate = PlanGenState.WALK; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.BICYCLE) { pgstate = PlanGenState.BICYCLE; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.CAR) { pgstate = PlanGenState.CAR; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.BOARDING) { // this itinerary starts with transit pgstate = PlanGenState.PRETRANSIT; leg = makeLeg(itinerary, state); leg.from.orig = nextName; itinerary.transfers++; startWalk = -1; } else if (mode == TraverseMode.STL) { // this comes after an alight; do nothing } else if (mode == TraverseMode.TRANSFER) { // handle the whole thing in one step leg = makeLeg(itinerary, state); coordinates = new CoordinateArrayListSequence(); coordinates.add(state.getBackState().getVertex().getCoordinate()); coordinates.add(state.getVertex().getCoordinate()); finalizeLeg(leg, state, path.states, i, i, coordinates, itinerary); coordinates.clear(); } else if (mode.isTransit()) { pgstate = PlanGenState.TRANSIT; leg = makeLeg(itinerary, state); leg.stop = new ArrayList<Place>(); leg.from.name = null; // TODO What name? "k.StopA + (1-k).StopB" ? :) itinerary.transfers++; startWalk = -1; fixupTransitLeg(leg, state, transitIndex); } else { LOG.error("Unexpected state (in START): " + mode); } break; case WALK: if (leg == null) { leg = makeLeg(itinerary, state); } if (mode == TraverseMode.WALK) { // do nothing } else if (mode == TraverseMode.BICYCLE) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); startWalk = i; leg = makeLeg(itinerary, state); pgstate = PlanGenState.BICYCLE; } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (mode == TraverseMode.BOARDING) { // this only happens in case of a timed transfer. pgstate = PlanGenState.PRETRANSIT; finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = makeLeg(itinerary, state); itinerary.transfers++; } else if (backEdge instanceof LegSwitchingEdge) { nextName = state.getBackState().getBackState().getBackState().getVertex() .getName(); finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in WALK): " + mode); } break; case BICYCLE: if (leg == null) { leg = makeLeg(itinerary, state); } // If there are elevator edges that have mode == BICYCLE on both sides, they should // be folded into the bicycle leg. But ones with walk on one side or the other should // not if (state.getBackEdge() instanceof ElevatorBoardEdge) { int j = i + 1; // proceed forward from the current state until we find one that isn't on an // elevator, and check the traverse mode while (path.states.get(j).getBackEdge() instanceof ElevatorEdge) j++; // path.states[j] is not an elevator edge if (path.states.get(j).getBackMode() == TraverseMode.BICYCLE) foldingElevatorLegIntoCycleLeg = true; } if (foldingElevatorLegIntoCycleLeg) { if (state.getBackEdge() instanceof ElevatorEdge) { break; // from the case } else { foldingElevatorLegIntoCycleLeg = false; // do not break but allow it to be processed below (which will do nothing) } } if (mode == TraverseMode.BICYCLE) { // do nothing } else if (mode == TraverseMode.WALK) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = makeLeg(itinerary, state); startWalk = i; pgstate = PlanGenState.WALK; } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); startWalk = i; leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (backEdge instanceof LegSwitchingEdge) { finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in BICYCLE): " + mode); } break; case CAR: if (leg == null) { leg = makeLeg(itinerary, state); } if (mode == TraverseMode.CAR) { // do nothing } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (backEdge instanceof LegSwitchingEdge) { finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in CAR): " + mode); } break; case PRETRANSIT: if (mode == TraverseMode.BOARDING) { if (leg != null) { LOG.error("leg unexpectedly not null (boarding loop)"); } else { leg = makeLeg(itinerary, state); leg.from.stopIndex = ((OnBoardForwardEdge)backEdge).getStopIndex(); TripTimes tt = state.getTripTimes(); - if ( ! tt.isScheduled()) { + if (tt != null && !tt.isScheduled()) { leg.realTime = true; leg.departureDelay = tt.getDepartureDelay(leg.from.stopIndex); } leg.stop = new ArrayList<Place>(); itinerary.transfers++; leg.boardRule = (String) state.getExtension("boardAlightRule"); } } else if (backEdge instanceof HopEdge) { pgstate = PlanGenState.TRANSIT; fixupTransitLeg(leg, state, transitIndex); leg.stop = new ArrayList<Place>(); } else { LOG.error("Unexpected state (in PRETRANSIT): " + mode); } break; case TRANSIT: String route = backEdge.getName(); if (mode == TraverseMode.ALIGHTING) { if (showIntermediateStops && leg.stop != null && leg.stop.size() > 0) { if (leg.stop.isEmpty()) { leg.stop = null; } } leg.alightRule = (String) state.getExtension("boardAlightRule"); finalizeLeg(leg, state, null, -1, -1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else if (mode.toString().equals(leg.mode)) { // no mode change, handle intermediate stops if (showIntermediateStops) { /* * any further transit edge, add "from" vertex to intermediate stops */ if (!(backEdge instanceof DwellEdge)) { Place stop = makePlace(state.getBackState(), state.getBackState().getVertex().getName(), true); leg.stop.add(stop); } else if (leg.stop.size() > 0) { leg.stop.get(leg.stop.size() - 1).departure = makeCalendar(state); } } if (!route.equals(leg.route)) { // interline dwell finalizeLeg(leg, state, null, -1, -1, coordinates, itinerary); leg = makeLeg(itinerary, state); leg.stop = new ArrayList<Place>(); fixupTransitLeg(leg, state, transitIndex); leg.startTime = makeCalendar(state); leg.interlineWithPreviousLeg = true; } } else { LOG.error("Unexpected state (in TRANSIT): " + mode); } break; } if (leg != null) { leg.distance += backEdge.getDistance(); Geometry edgeGeometry = backEdge.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } if (postponedAlerts != null) { addNotesToLeg(leg, postponedAlerts); postponedAlerts = null; } addNotesToLeg(leg, state.getBackAlerts()); } } /* end loop over graphPath edge list */ if (leg != null) { finalizeLeg(leg, path.states.getLast(), path.states, startWalk, i, coordinates, itinerary); } itinerary.removeBogusLegs(); itinerary.fixupDates(graph.getService(CalendarServiceData.class)); if (itinerary.legs.size() == 0) throw new TrivialPathException(); return itinerary; } private Calendar makeCalendar(State state) { RoutingContext rctx = state.getContext(); TimeZone timeZone = rctx.graph.getTimeZone(); Calendar calendar = Calendar.getInstance(timeZone); calendar.setTimeInMillis(state.getTimeInMillis()); return calendar; } private void fixupTransitLeg(Leg leg, State state, TransitIndexService transitIndex) { Edge en = state.getBackEdge(); leg.route = en.getName(); Trip trip = state.getBackTrip(); leg.headsign = state.getBackDirection(); if (trip != null) { // this is the stop headsign //leg.headsign = "This is the headsign"; // handle no stop headsign if (leg.headsign == null) leg.headsign = trip.getTripHeadsign(); leg.tripId = trip.getId().getId(); leg.agencyId = trip.getId().getAgencyId(); leg.tripShortName = trip.getTripShortName(); leg.routeShortName = trip.getRoute().getShortName(); leg.routeLongName = trip.getRoute().getLongName(); leg.routeColor = trip.getRoute().getColor(); leg.routeTextColor = trip.getRoute().getTextColor(); leg.routeId = trip.getRoute().getId().getId(); leg.routeType = trip.getRoute().getType(); if (transitIndex != null) { Agency agency = transitIndex.getAgency(leg.agencyId); leg.agencyName = agency.getName(); leg.agencyUrl = agency.getUrl(); } } leg.mode = state.getBackMode().toString(); leg.startTime = makeCalendar(state.getBackState()); } private void finalizeLeg(Leg leg, State state, List<State> states, int start, int end, CoordinateArrayListSequence coordinates, Itinerary itinerary) { //this leg has already been added to the itinerary, so we actually want the penultimate leg, if any if (states != null) { int extra = 0; WalkStep continuation = null; if (itinerary.legs.size() >= 2) { Leg previousLeg = itinerary.legs.get(itinerary.legs.size() - 2); if (previousLeg.walkSteps != null && !previousLeg.walkSteps.isEmpty()) { continuation = previousLeg.walkSteps.get(previousLeg.walkSteps.size() - 1); extra = 1; } } if (end == states.size() - 1) { extra = 1; } leg.walkSteps = getWalkSteps(states.subList(start, end + extra), continuation); } leg.endTime = makeCalendar(state.getBackState()); Geometry geometry = GeometryUtils.getGeometryFactory().createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); Edge backEdge = state.getBackEdge(); String name; if (backEdge instanceof StreetEdge) { name = backEdge.getName(); } else { name = state.getVertex().getName(); } if (backEdge instanceof PatternHop) { TripTimes tt = state.getTripTimes(); int hop = ((PatternHop)backEdge).stopIndex; leg.arrivalDelay = tt.getArrivalDelay(hop); } leg.to = makePlace(state, name, true); coordinates.clear(); } private Set<Alert> addNotesToLeg(Leg leg, Set<Alert> notes) { if (notes != null) { for (Alert note : notes) { leg.addAlert(note); } } return notes; } /** * Adjusts an Itinerary's elevation fields from an elevation profile * * @return the elevation at the end of the profile */ private double applyElevation(PackedCoordinateSequence profile, Itinerary itinerary, double previousElevation) { if (profile != null) { for (Coordinate coordinate : profile.toCoordinateArray()) { if (previousElevation == Double.MAX_VALUE) { previousElevation = coordinate.y; continue; } double elevationChange = previousElevation - coordinate.y; if (elevationChange > 0) { itinerary.elevationGained += elevationChange; } else { itinerary.elevationLost -= elevationChange; } previousElevation = coordinate.y; } } return previousElevation; } /** * Makes a new empty leg from a starting edge * * @param itinerary */ private Leg makeLeg(Itinerary itinerary, State s) { Leg leg = new Leg(); itinerary.addLeg(leg); leg.startTime = makeCalendar(s.getBackState()); leg.distance = 0.0; String name; Edge backEdge = s.getBackEdge(); if (backEdge instanceof StreetEdge) { name = backEdge.getName(); } else { name = s.getVertex().getName(); } leg.from = makePlace(s.getBackState(), name, false); leg.mode = s.getBackMode().toString(); if (s.isBikeRenting()) { leg.rentedBike = true; } return leg; } /** * Makes a new empty Itinerary for a given path. * * @return */ private Itinerary makeEmptyItinerary(GraphPath path) { Itinerary itinerary = new Itinerary(); State startState = path.states.getFirst(); State endState = path.states.getLast(); itinerary.startTime = makeCalendar(startState); itinerary.endTime = makeCalendar(endState); itinerary.duration = endState.getTimeInMillis() - startState.getTimeInMillis(); itinerary.walkDistance = path.getWalkDistance(); Graph graph = path.getRoutingContext().graph; FareService fareService = graph.getService(FareService.class); if (fareService != null) { itinerary.fare = fareService.getCost(path); } itinerary.transfers = -1; return itinerary; } /** * Makes a new Place from a state. Contains information about time. * * @return */ private Place makePlace(State state, String name, boolean time) { Vertex v = state.getVertex(); Coordinate endCoord = v.getCoordinate(); Place place; if (time) { Calendar timeAtState = makeCalendar(state); place = new Place(endCoord.x, endCoord.y, name, timeAtState); } else { place = new Place(endCoord.x, endCoord.y, name); } if (v instanceof TransitVertex) { TransitVertex transitVertex = (TransitVertex) v; Edge backEdge = state.getBackEdge(); if (backEdge instanceof OnBoardForwardEdge) { place.stopIndex = ((OnBoardForwardEdge)backEdge).getStopIndex() + 1; } place.stopId = transitVertex.getStopId(); place.stopCode = transitVertex.getStopCode(); place.zoneId = state.getZone(); } return place; } /** * Converts a list of street edges to a list of turn-by-turn directions. * * @param previous a non-transit leg that immediately precedes this one (bike-walking, say), or null * * @param edges : A list of street edges * @return */ private List<WalkStep> getWalkSteps(List<State> states, WalkStep previous) { List<WalkStep> steps = new ArrayList<WalkStep>(); WalkStep step = null; double lastAngle = 0, distance = 0; // distance used for appending elevation profiles int roundaboutExit = 0; // track whether we are in a roundabout, and if so the exit number String roundaboutPreviousStreet = null; for (State currState : states) { State backState = currState.getBackState(); Edge edge = currState.getBackEdge(); boolean createdNewStep = false, disableZagRemovalForThisStep = false; if (edge instanceof FreeEdge) { continue; } if (currState.getBackMode() == null || !currState.getBackMode().isOnStreetNonTransit()) { continue; // ignore STLs and the like } Geometry geom = edge.getGeometry(); if (geom == null) { continue; } // generate a step for getting off an elevator (all // elevator narrative generation occurs when alighting). We don't need to know what came // before or will come after if (edge instanceof ElevatorAlightEdge) { // don't care what came before or comes after step = createWalkStep(currState); createdNewStep = true; disableZagRemovalForThisStep = true; // tell the user where to get off the elevator using the exit notation, so the // i18n interface will say 'Elevator to <exit>' // what happens is that the webapp sees name == null and ignores that, and it sees // exit != null and uses to <exit> // the floor name is the AlightEdge name // reset to avoid confusion with 'Elevator on floor 1 to floor 1' step.streetName = ((ElevatorAlightEdge) edge).getName(); step.relativeDirection = RelativeDirection.ELEVATOR; steps.add(step); continue; } String streetName = edge.getName(); int idx = streetName.indexOf('('); String streetNameNoParens; if (idx > 0) streetNameNoParens = streetName.substring(0, idx - 1); else streetNameNoParens = streetName; if (step == null) { // first step step = createWalkStep(currState); createdNewStep = true; steps.add(step); double thisAngle = DirectionUtils.getFirstAngle(geom); if (previous == null) { step.setAbsoluteDirection(thisAngle); } else { step.setDirections(previous.angle, thisAngle, false); } // new step, set distance to length of first edge distance = edge.getDistance(); } else if (((step.streetName != null && !step.streetNameNoParens().equals(streetNameNoParens)) && (!step.bogusName || !edge.hasBogusName())) || // if we are on a roundabout now and weren't before, start a new step edge.isRoundabout() != (roundaboutExit > 0) || isLink(edge) && !isLink(backState.getBackEdge()) ) { /* street name has changed, or we've changed state from a roundabout to a street */ if (roundaboutExit > 0) { // if we were just on a roundabout, // make note of which exit was taken in the existing step step.exit = Integer.toString(roundaboutExit); // ordinal numbers from if (streetNameNoParens.equals(roundaboutPreviousStreet)) { step.stayOn = true; } // localization roundaboutExit = 0; } if (backState.getVertex() instanceof ExitVertex) { step.exit = ((ExitVertex) backState.getVertex()).getExitName(); } /* start a new step */ step = createWalkStep(currState); createdNewStep = true; steps.add(step); if (edge.isRoundabout()) { // indicate that we are now on a roundabout // and use one-based exit numbering roundaboutExit = 1; roundaboutPreviousStreet = backState.getBackEdge().getName(); idx = roundaboutPreviousStreet.indexOf('('); if (idx > 0) roundaboutPreviousStreet = roundaboutPreviousStreet.substring(0, idx - 1); } double thisAngle = DirectionUtils.getFirstAngle(geom); step.setDirections(lastAngle, thisAngle, edge.isRoundabout()); // new step, set distance to length of first edge distance = edge.getDistance(); } else { /* street name has not changed */ double thisAngle = DirectionUtils.getFirstAngle(geom); RelativeDirection direction = WalkStep.getRelativeDirection(lastAngle, thisAngle, edge.isRoundabout()); boolean optionsBefore = backState.multipleOptionsBefore(); if (edge.isRoundabout()) { // we are on a roundabout, and have already traversed at least one edge of it. if (optionsBefore) { // increment exit count if we passed one. roundaboutExit += 1; } } if (edge.isRoundabout() || direction == RelativeDirection.CONTINUE) { // we are continuing almost straight, or continuing along a roundabout. // just append elevation info onto the existing step. } else { // we are not on a roundabout, and not continuing straight through. // figure out if there were other plausible turn options at the last // intersection // to see if we should generate a "left to continue" instruction. boolean shouldGenerateContinue = false; if (edge instanceof PlainStreetEdge) { // the next edges will be PlainStreetEdges, we hope double angleDiff = getAbsoluteAngleDiff(thisAngle, lastAngle); for (Edge alternative : backState.getVertex().getOutgoingStreetEdges()) { if (alternative.getName().equals(streetName)) { // alternatives that have the same name // are usually caused by street splits continue; } double altAngle = DirectionUtils.getFirstAngle(alternative .getGeometry()); double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle); if (angleDiff > Math.PI / 4 || altAngleDiff - angleDiff < Math.PI / 16) { shouldGenerateContinue = true; break; } } } else { double angleDiff = getAbsoluteAngleDiff(lastAngle, thisAngle); // FIXME: this code might be wrong with the removal of the edge-based graph State twoStatesBack = backState.getBackState(); Vertex backVertex = twoStatesBack.getVertex(); for (Edge alternative : backVertex.getOutgoingStreetEdges()) { List<Edge> alternatives = alternative.getToVertex() .getOutgoingStreetEdges(); if (alternatives.size() == 0) { continue; // this is not an alternative } alternative = alternatives.get(0); if (alternative.getName().equals(streetName)) { // alternatives that have the same name // are usually caused by street splits continue; } double altAngle = DirectionUtils.getFirstAngle(alternative .getGeometry()); double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle); if (angleDiff > Math.PI / 4 || altAngleDiff - angleDiff < Math.PI / 16) { shouldGenerateContinue = true; break; } } } if (shouldGenerateContinue) { // turn to stay on same-named street step = createWalkStep(currState); createdNewStep = true; steps.add(step); step.setDirections(lastAngle, thisAngle, false); step.stayOn = true; // new step, set distance to length of first edge distance = edge.getDistance(); } } } if (createdNewStep && !disableZagRemovalForThisStep && currState.getBackMode() == backState.getBackMode()) { //check last three steps for zag int last = steps.size() - 1; if (last >= 2) { WalkStep threeBack = steps.get(last - 2); WalkStep twoBack = steps.get(last - 1); WalkStep lastStep = steps.get(last); if (twoBack.distance < MAX_ZAG_DISTANCE && lastStep.streetNameNoParens().equals(threeBack.streetNameNoParens())) { if (((lastStep.relativeDirection == RelativeDirection.RIGHT || lastStep.relativeDirection == RelativeDirection.HARD_RIGHT) && (twoBack.relativeDirection == RelativeDirection.RIGHT || twoBack.relativeDirection == RelativeDirection.HARD_RIGHT)) || ((lastStep.relativeDirection == RelativeDirection.LEFT || lastStep.relativeDirection == RelativeDirection.HARD_LEFT) && (twoBack.relativeDirection == RelativeDirection.LEFT || twoBack.relativeDirection == RelativeDirection.HARD_LEFT))) { // in this case, we have two left turns or two right turns in quick // succession; this is probably a U-turn. steps.remove(last - 1); lastStep.distance += twoBack.distance; // A U-turn to the left, typical in the US. if (lastStep.relativeDirection == RelativeDirection.LEFT || lastStep.relativeDirection == RelativeDirection.HARD_LEFT) lastStep.relativeDirection = RelativeDirection.UTURN_LEFT; else lastStep.relativeDirection = RelativeDirection.UTURN_RIGHT; // in this case, we're definitely staying on the same street // (since it's zag removal, the street names are the same) lastStep.stayOn = true; } else { // total hack to remove zags. steps.remove(last); steps.remove(last - 1); step = threeBack; step.distance += twoBack.distance; distance += step.distance; if (twoBack.elevation != null) { if (step.elevation == null) { step.elevation = twoBack.elevation; } else { for (P2<Double> d : twoBack.elevation) { step.elevation.add(new P2<Double>(d.getFirst() + step.distance, d.getSecond())); } } } } } } } else { if (!createdNewStep && step.elevation != null) { List<P2<Double>> s = encodeElevationProfile(edge, distance); if (step.elevation != null && step.elevation.size() > 0) { step.elevation.addAll(s); } else { step.elevation = s; } } distance += edge.getDistance(); } // increment the total length for this step step.distance += edge.getDistance(); step.addAlerts(currState.getBackAlerts()); lastAngle = DirectionUtils.getLastAngle(geom); } return steps; } private boolean isLink(Edge edge) { return edge instanceof StreetEdge && (((StreetEdge)edge).getStreetClass() & StreetEdge.CLASS_LINK) == StreetEdge.CLASS_LINK; } private double getAbsoluteAngleDiff(double thisAngle, double lastAngle) { double angleDiff = thisAngle - lastAngle; if (angleDiff < 0) { angleDiff += Math.PI * 2; } double ccwAngleDiff = Math.PI * 2 - angleDiff; if (ccwAngleDiff < angleDiff) { angleDiff = ccwAngleDiff; } return angleDiff; } private WalkStep createWalkStep(State s) { Edge en = s.getBackEdge(); WalkStep step; step = new WalkStep(); step.streetName = en.getName(); step.lon = en.getFromVertex().getX(); step.lat = en.getFromVertex().getY(); step.elevation = encodeElevationProfile(s.getBackEdge(), 0); step.bogusName = en.hasBogusName(); step.addAlerts(s.getBackAlerts()); step.angle = DirectionUtils.getFirstAngle(s.getBackEdge().getGeometry()); if (s.getBackEdge() instanceof AreaEdge) { step.area = true; } return step; } private List<P2<Double>> encodeElevationProfile(Edge edge, double offset) { if (!(edge instanceof EdgeWithElevation)) { return new ArrayList<P2<Double>>(); } EdgeWithElevation elevEdge = (EdgeWithElevation) edge; if (elevEdge.getElevationProfile() == null) { return new ArrayList<P2<Double>>(); } ArrayList<P2<Double>> out = new ArrayList<P2<Double>>(); Coordinate[] coordArr = elevEdge.getElevationProfile().toCoordinateArray(); for (int i = 0; i < coordArr.length; i++) { out.add(new P2<Double>(coordArr[i].x + offset, coordArr[i].y)); } return out; } /** Returns the first trip of the service day. */ public TripPlan generateFirstTrip(RoutingRequest request) { Graph graph = graphService.getGraph(request.getRouterId()); TransitIndexService transitIndex = graph.getService(TransitIndexService.class); transitIndexWithBreakRequired(transitIndex); request.setArriveBy(false); TimeZone tz = graph.getTimeZone(); GregorianCalendar calendar = new GregorianCalendar(tz); calendar.setTimeInMillis(request.dateTime * 1000); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.AM_PM, 0); calendar.set(Calendar.SECOND, transitIndex.getOvernightBreak()); request.dateTime = calendar.getTimeInMillis() / 1000; return generate(request); } /** Return the last trip of the service day */ public TripPlan generateLastTrip(RoutingRequest request) { Graph graph = graphService.getGraph(request.getRouterId()); TransitIndexService transitIndex = graph.getService(TransitIndexService.class); transitIndexWithBreakRequired(transitIndex); request.setArriveBy(true); TimeZone tz = graph.getTimeZone(); GregorianCalendar calendar = new GregorianCalendar(tz); calendar.setTimeInMillis(request.dateTime * 1000); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.AM_PM, 0); calendar.set(Calendar.SECOND, transitIndex.getOvernightBreak()); calendar.add(Calendar.DAY_OF_YEAR, 1); request.dateTime = calendar.getTimeInMillis() / 1000; return generate(request); } private void transitIndexWithBreakRequired(TransitIndexService transitIndex) { transitIndexRequired(transitIndex); if (transitIndex.getOvernightBreak() == -1) { throw new RuntimeException("TransitIndexBuilder could not find an overnight break " + "in the transit schedule; first/last trips are undefined"); } } private void transitIndexRequired(TransitIndexService transitIndex) { if (transitIndex == null) { throw new RuntimeException( "TransitIndexBuilder is required for first/last/next/previous trip"); } } }
true
true
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Graph graph = path.getRoutingContext().graph; TransitIndexService transitIndex = graph.getService(TransitIndexService.class); Itinerary itinerary = makeEmptyItinerary(path); Set<Alert> postponedAlerts = null; Leg leg = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); double previousElevation = Double.MAX_VALUE; int startWalk = -1; int i = -1; boolean foldingElevatorLegIntoCycleLeg = false; PlanGenState pgstate = PlanGenState.START; String nextName = null; for (State state : path.states) { i += 1; Edge backEdge = state.getBackEdge(); if (backEdge == null) { continue; } TraverseMode mode = state.getBackMode(); if (mode != null) { long dt = state.getAbsTimeDeltaSeconds(); if (mode == TraverseMode.BOARDING || mode == TraverseMode.ALIGHTING || mode == TraverseMode.STL) { itinerary.waitingTime += dt; } else if (mode.isOnStreetNonTransit()) { itinerary.walkTime += dt; } else if (mode.isTransit()) { itinerary.transitTime += dt; } } if (backEdge instanceof FreeEdge) { if (backEdge instanceof PreBoardEdge) { // Add boarding alerts to the next leg postponedAlerts = state.getBackAlerts(); } else if (backEdge instanceof PreAlightEdge) { // Add alighting alerts to the previous leg, if any if (itinerary.legs.size() > 0) addNotesToLeg(itinerary.legs.get(itinerary.legs.size() - 1), state.getBackAlerts()); } continue; } if (backEdge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } switch (pgstate) { case START: if (mode == TraverseMode.WALK) { pgstate = PlanGenState.WALK; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.BICYCLE) { pgstate = PlanGenState.BICYCLE; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.CAR) { pgstate = PlanGenState.CAR; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.BOARDING) { // this itinerary starts with transit pgstate = PlanGenState.PRETRANSIT; leg = makeLeg(itinerary, state); leg.from.orig = nextName; itinerary.transfers++; startWalk = -1; } else if (mode == TraverseMode.STL) { // this comes after an alight; do nothing } else if (mode == TraverseMode.TRANSFER) { // handle the whole thing in one step leg = makeLeg(itinerary, state); coordinates = new CoordinateArrayListSequence(); coordinates.add(state.getBackState().getVertex().getCoordinate()); coordinates.add(state.getVertex().getCoordinate()); finalizeLeg(leg, state, path.states, i, i, coordinates, itinerary); coordinates.clear(); } else if (mode.isTransit()) { pgstate = PlanGenState.TRANSIT; leg = makeLeg(itinerary, state); leg.stop = new ArrayList<Place>(); leg.from.name = null; // TODO What name? "k.StopA + (1-k).StopB" ? :) itinerary.transfers++; startWalk = -1; fixupTransitLeg(leg, state, transitIndex); } else { LOG.error("Unexpected state (in START): " + mode); } break; case WALK: if (leg == null) { leg = makeLeg(itinerary, state); } if (mode == TraverseMode.WALK) { // do nothing } else if (mode == TraverseMode.BICYCLE) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); startWalk = i; leg = makeLeg(itinerary, state); pgstate = PlanGenState.BICYCLE; } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (mode == TraverseMode.BOARDING) { // this only happens in case of a timed transfer. pgstate = PlanGenState.PRETRANSIT; finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = makeLeg(itinerary, state); itinerary.transfers++; } else if (backEdge instanceof LegSwitchingEdge) { nextName = state.getBackState().getBackState().getBackState().getVertex() .getName(); finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in WALK): " + mode); } break; case BICYCLE: if (leg == null) { leg = makeLeg(itinerary, state); } // If there are elevator edges that have mode == BICYCLE on both sides, they should // be folded into the bicycle leg. But ones with walk on one side or the other should // not if (state.getBackEdge() instanceof ElevatorBoardEdge) { int j = i + 1; // proceed forward from the current state until we find one that isn't on an // elevator, and check the traverse mode while (path.states.get(j).getBackEdge() instanceof ElevatorEdge) j++; // path.states[j] is not an elevator edge if (path.states.get(j).getBackMode() == TraverseMode.BICYCLE) foldingElevatorLegIntoCycleLeg = true; } if (foldingElevatorLegIntoCycleLeg) { if (state.getBackEdge() instanceof ElevatorEdge) { break; // from the case } else { foldingElevatorLegIntoCycleLeg = false; // do not break but allow it to be processed below (which will do nothing) } } if (mode == TraverseMode.BICYCLE) { // do nothing } else if (mode == TraverseMode.WALK) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = makeLeg(itinerary, state); startWalk = i; pgstate = PlanGenState.WALK; } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); startWalk = i; leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (backEdge instanceof LegSwitchingEdge) { finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in BICYCLE): " + mode); } break; case CAR: if (leg == null) { leg = makeLeg(itinerary, state); } if (mode == TraverseMode.CAR) { // do nothing } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (backEdge instanceof LegSwitchingEdge) { finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in CAR): " + mode); } break; case PRETRANSIT: if (mode == TraverseMode.BOARDING) { if (leg != null) { LOG.error("leg unexpectedly not null (boarding loop)"); } else { leg = makeLeg(itinerary, state); leg.from.stopIndex = ((OnBoardForwardEdge)backEdge).getStopIndex(); TripTimes tt = state.getTripTimes(); if ( ! tt.isScheduled()) { leg.realTime = true; leg.departureDelay = tt.getDepartureDelay(leg.from.stopIndex); } leg.stop = new ArrayList<Place>(); itinerary.transfers++; leg.boardRule = (String) state.getExtension("boardAlightRule"); } } else if (backEdge instanceof HopEdge) { pgstate = PlanGenState.TRANSIT; fixupTransitLeg(leg, state, transitIndex); leg.stop = new ArrayList<Place>(); } else { LOG.error("Unexpected state (in PRETRANSIT): " + mode); } break; case TRANSIT: String route = backEdge.getName(); if (mode == TraverseMode.ALIGHTING) { if (showIntermediateStops && leg.stop != null && leg.stop.size() > 0) { if (leg.stop.isEmpty()) { leg.stop = null; } } leg.alightRule = (String) state.getExtension("boardAlightRule"); finalizeLeg(leg, state, null, -1, -1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else if (mode.toString().equals(leg.mode)) { // no mode change, handle intermediate stops if (showIntermediateStops) { /* * any further transit edge, add "from" vertex to intermediate stops */ if (!(backEdge instanceof DwellEdge)) { Place stop = makePlace(state.getBackState(), state.getBackState().getVertex().getName(), true); leg.stop.add(stop); } else if (leg.stop.size() > 0) { leg.stop.get(leg.stop.size() - 1).departure = makeCalendar(state); } } if (!route.equals(leg.route)) { // interline dwell finalizeLeg(leg, state, null, -1, -1, coordinates, itinerary); leg = makeLeg(itinerary, state); leg.stop = new ArrayList<Place>(); fixupTransitLeg(leg, state, transitIndex); leg.startTime = makeCalendar(state); leg.interlineWithPreviousLeg = true; } } else { LOG.error("Unexpected state (in TRANSIT): " + mode); } break; } if (leg != null) { leg.distance += backEdge.getDistance(); Geometry edgeGeometry = backEdge.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } if (postponedAlerts != null) { addNotesToLeg(leg, postponedAlerts); postponedAlerts = null; } addNotesToLeg(leg, state.getBackAlerts()); } } /* end loop over graphPath edge list */ if (leg != null) { finalizeLeg(leg, path.states.getLast(), path.states, startWalk, i, coordinates, itinerary); } itinerary.removeBogusLegs(); itinerary.fixupDates(graph.getService(CalendarServiceData.class)); if (itinerary.legs.size() == 0) throw new TrivialPathException(); return itinerary; }
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Graph graph = path.getRoutingContext().graph; TransitIndexService transitIndex = graph.getService(TransitIndexService.class); Itinerary itinerary = makeEmptyItinerary(path); Set<Alert> postponedAlerts = null; Leg leg = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); double previousElevation = Double.MAX_VALUE; int startWalk = -1; int i = -1; boolean foldingElevatorLegIntoCycleLeg = false; PlanGenState pgstate = PlanGenState.START; String nextName = null; for (State state : path.states) { i += 1; Edge backEdge = state.getBackEdge(); if (backEdge == null) { continue; } TraverseMode mode = state.getBackMode(); if (mode != null) { long dt = state.getAbsTimeDeltaSeconds(); if (mode == TraverseMode.BOARDING || mode == TraverseMode.ALIGHTING || mode == TraverseMode.STL) { itinerary.waitingTime += dt; } else if (mode.isOnStreetNonTransit()) { itinerary.walkTime += dt; } else if (mode.isTransit()) { itinerary.transitTime += dt; } } if (backEdge instanceof FreeEdge) { if (backEdge instanceof PreBoardEdge) { // Add boarding alerts to the next leg postponedAlerts = state.getBackAlerts(); } else if (backEdge instanceof PreAlightEdge) { // Add alighting alerts to the previous leg, if any if (itinerary.legs.size() > 0) addNotesToLeg(itinerary.legs.get(itinerary.legs.size() - 1), state.getBackAlerts()); } continue; } if (backEdge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } switch (pgstate) { case START: if (mode == TraverseMode.WALK) { pgstate = PlanGenState.WALK; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.BICYCLE) { pgstate = PlanGenState.BICYCLE; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.CAR) { pgstate = PlanGenState.CAR; leg = makeLeg(itinerary, state); leg.from.orig = nextName; startWalk = i; } else if (mode == TraverseMode.BOARDING) { // this itinerary starts with transit pgstate = PlanGenState.PRETRANSIT; leg = makeLeg(itinerary, state); leg.from.orig = nextName; itinerary.transfers++; startWalk = -1; } else if (mode == TraverseMode.STL) { // this comes after an alight; do nothing } else if (mode == TraverseMode.TRANSFER) { // handle the whole thing in one step leg = makeLeg(itinerary, state); coordinates = new CoordinateArrayListSequence(); coordinates.add(state.getBackState().getVertex().getCoordinate()); coordinates.add(state.getVertex().getCoordinate()); finalizeLeg(leg, state, path.states, i, i, coordinates, itinerary); coordinates.clear(); } else if (mode.isTransit()) { pgstate = PlanGenState.TRANSIT; leg = makeLeg(itinerary, state); leg.stop = new ArrayList<Place>(); leg.from.name = null; // TODO What name? "k.StopA + (1-k).StopB" ? :) itinerary.transfers++; startWalk = -1; fixupTransitLeg(leg, state, transitIndex); } else { LOG.error("Unexpected state (in START): " + mode); } break; case WALK: if (leg == null) { leg = makeLeg(itinerary, state); } if (mode == TraverseMode.WALK) { // do nothing } else if (mode == TraverseMode.BICYCLE) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); startWalk = i; leg = makeLeg(itinerary, state); pgstate = PlanGenState.BICYCLE; } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (mode == TraverseMode.BOARDING) { // this only happens in case of a timed transfer. pgstate = PlanGenState.PRETRANSIT; finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = makeLeg(itinerary, state); itinerary.transfers++; } else if (backEdge instanceof LegSwitchingEdge) { nextName = state.getBackState().getBackState().getBackState().getVertex() .getName(); finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in WALK): " + mode); } break; case BICYCLE: if (leg == null) { leg = makeLeg(itinerary, state); } // If there are elevator edges that have mode == BICYCLE on both sides, they should // be folded into the bicycle leg. But ones with walk on one side or the other should // not if (state.getBackEdge() instanceof ElevatorBoardEdge) { int j = i + 1; // proceed forward from the current state until we find one that isn't on an // elevator, and check the traverse mode while (path.states.get(j).getBackEdge() instanceof ElevatorEdge) j++; // path.states[j] is not an elevator edge if (path.states.get(j).getBackMode() == TraverseMode.BICYCLE) foldingElevatorLegIntoCycleLeg = true; } if (foldingElevatorLegIntoCycleLeg) { if (state.getBackEdge() instanceof ElevatorEdge) { break; // from the case } else { foldingElevatorLegIntoCycleLeg = false; // do not break but allow it to be processed below (which will do nothing) } } if (mode == TraverseMode.BICYCLE) { // do nothing } else if (mode == TraverseMode.WALK) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = makeLeg(itinerary, state); startWalk = i; pgstate = PlanGenState.WALK; } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); startWalk = i; leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (backEdge instanceof LegSwitchingEdge) { finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in BICYCLE): " + mode); } break; case CAR: if (leg == null) { leg = makeLeg(itinerary, state); } if (mode == TraverseMode.CAR) { // do nothing } else if (mode == TraverseMode.STL) { finalizeLeg(leg, state, path.states, startWalk, i, coordinates, itinerary); leg = null; pgstate = PlanGenState.PRETRANSIT; } else if (backEdge instanceof LegSwitchingEdge) { finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else { LOG.error("Unexpected state (in CAR): " + mode); } break; case PRETRANSIT: if (mode == TraverseMode.BOARDING) { if (leg != null) { LOG.error("leg unexpectedly not null (boarding loop)"); } else { leg = makeLeg(itinerary, state); leg.from.stopIndex = ((OnBoardForwardEdge)backEdge).getStopIndex(); TripTimes tt = state.getTripTimes(); if (tt != null && !tt.isScheduled()) { leg.realTime = true; leg.departureDelay = tt.getDepartureDelay(leg.from.stopIndex); } leg.stop = new ArrayList<Place>(); itinerary.transfers++; leg.boardRule = (String) state.getExtension("boardAlightRule"); } } else if (backEdge instanceof HopEdge) { pgstate = PlanGenState.TRANSIT; fixupTransitLeg(leg, state, transitIndex); leg.stop = new ArrayList<Place>(); } else { LOG.error("Unexpected state (in PRETRANSIT): " + mode); } break; case TRANSIT: String route = backEdge.getName(); if (mode == TraverseMode.ALIGHTING) { if (showIntermediateStops && leg.stop != null && leg.stop.size() > 0) { if (leg.stop.isEmpty()) { leg.stop = null; } } leg.alightRule = (String) state.getExtension("boardAlightRule"); finalizeLeg(leg, state, null, -1, -1, coordinates, itinerary); leg = null; pgstate = PlanGenState.START; } else if (mode.toString().equals(leg.mode)) { // no mode change, handle intermediate stops if (showIntermediateStops) { /* * any further transit edge, add "from" vertex to intermediate stops */ if (!(backEdge instanceof DwellEdge)) { Place stop = makePlace(state.getBackState(), state.getBackState().getVertex().getName(), true); leg.stop.add(stop); } else if (leg.stop.size() > 0) { leg.stop.get(leg.stop.size() - 1).departure = makeCalendar(state); } } if (!route.equals(leg.route)) { // interline dwell finalizeLeg(leg, state, null, -1, -1, coordinates, itinerary); leg = makeLeg(itinerary, state); leg.stop = new ArrayList<Place>(); fixupTransitLeg(leg, state, transitIndex); leg.startTime = makeCalendar(state); leg.interlineWithPreviousLeg = true; } } else { LOG.error("Unexpected state (in TRANSIT): " + mode); } break; } if (leg != null) { leg.distance += backEdge.getDistance(); Geometry edgeGeometry = backEdge.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } if (postponedAlerts != null) { addNotesToLeg(leg, postponedAlerts); postponedAlerts = null; } addNotesToLeg(leg, state.getBackAlerts()); } } /* end loop over graphPath edge list */ if (leg != null) { finalizeLeg(leg, path.states.getLast(), path.states, startWalk, i, coordinates, itinerary); } itinerary.removeBogusLegs(); itinerary.fixupDates(graph.getService(CalendarServiceData.class)); if (itinerary.legs.size() == 0) throw new TrivialPathException(); return itinerary; }
diff --git a/glob-fire-reader/src/main/java/org/esa/glob/reader/worldfire/WorldFireReaderPlugIn.java b/glob-fire-reader/src/main/java/org/esa/glob/reader/worldfire/WorldFireReaderPlugIn.java index af75029..e2030a4 100644 --- a/glob-fire-reader/src/main/java/org/esa/glob/reader/worldfire/WorldFireReaderPlugIn.java +++ b/glob-fire-reader/src/main/java/org/esa/glob/reader/worldfire/WorldFireReaderPlugIn.java @@ -1,99 +1,99 @@ package org.esa.glob.reader.worldfire; import org.esa.beam.framework.dataio.DecodeQualification; import org.esa.beam.framework.dataio.ProductReaderPlugIn; import org.esa.beam.framework.dataio.ProductReader; import org.esa.beam.util.io.BeamFileFilter; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Locale; // TODO - TBD: really use the optional gif-file // TODO - read from zip files // TODO - consider reading zips in zip files (e.g. annual time series) // TODO - consider changeable filename convention /** * @author Marco Peters * @since GlobToolbox 2.0 */ public class WorldFireReaderPlugIn implements ProductReaderPlugIn { private static final String FORMAT_NAME = "ATSR World Fire"; private static final String[] FORMAT_NAMES = new String[]{FORMAT_NAME}; private static final String DESCRIPTION = "ATSR2/AATSR based Global Fire Maps (Level 3)"; private static final Class[] INPUT_TYPES = new Class[]{String.class, File.class}; private static final String FIRE_FILE_EXTENSION = "FIRE"; private static final String[] DEFAULT_FILE_EXTENSIONS = new String[]{FIRE_FILE_EXTENSION}; public DecodeQualification getDecodeQualification(Object input) { - File inputFile = new File(input.toString()); + File inputFile = new File(String.valueOf(input)); if(!inputFile.getName().toUpperCase().endsWith(FIRE_FILE_EXTENSION)) { return DecodeQualification.UNABLE; } InputStream inputStream = null; try { inputStream = new FileInputStream(inputFile); return getDecodeQualification(inputStream); } catch (IOException ignored) { return DecodeQualification.UNABLE; }finally { if(inputStream != null) { try { inputStream.close(); } catch (IOException ignored) {} } } } public Class[] getInputTypes() { return INPUT_TYPES; } public ProductReader createReaderInstance() { return new WorldFireReader(this); } public String[] getFormatNames() { return FORMAT_NAMES; } public String[] getDefaultFileExtensions() { return DEFAULT_FILE_EXTENSIONS; } public String getDescription(Locale locale) { return DESCRIPTION; } public BeamFileFilter getProductFileFilter() { return new BeamFileFilter(FORMAT_NAME, getDefaultFileExtensions(), getDescription(null)); } @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"}) private DecodeQualification getDecodeQualification(InputStream inputStream) { if(inputStream == null) { return DecodeQualification.UNABLE; } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); try { final String line = bufferedReader.readLine(); if (line != null && !line.isEmpty() && line.length() < 100) { final int columnsCount = line.split("[\\s]++").length; if (columnsCount == 5 || columnsCount == 6) { return DecodeQualification.INTENDED; } } return DecodeQualification.UNABLE; } catch (IOException ignored) { return DecodeQualification.UNABLE; } } }
true
true
public DecodeQualification getDecodeQualification(Object input) { File inputFile = new File(input.toString()); if(!inputFile.getName().toUpperCase().endsWith(FIRE_FILE_EXTENSION)) { return DecodeQualification.UNABLE; } InputStream inputStream = null; try { inputStream = new FileInputStream(inputFile); return getDecodeQualification(inputStream); } catch (IOException ignored) { return DecodeQualification.UNABLE; }finally { if(inputStream != null) { try { inputStream.close(); } catch (IOException ignored) {} } } }
public DecodeQualification getDecodeQualification(Object input) { File inputFile = new File(String.valueOf(input)); if(!inputFile.getName().toUpperCase().endsWith(FIRE_FILE_EXTENSION)) { return DecodeQualification.UNABLE; } InputStream inputStream = null; try { inputStream = new FileInputStream(inputFile); return getDecodeQualification(inputStream); } catch (IOException ignored) { return DecodeQualification.UNABLE; }finally { if(inputStream != null) { try { inputStream.close(); } catch (IOException ignored) {} } } }
diff --git a/src/PrimerDesign/src/view/FinalTemperaturePanel.java b/src/PrimerDesign/src/view/FinalTemperaturePanel.java index ca4aaea..20509fd 100644 --- a/src/PrimerDesign/src/view/FinalTemperaturePanel.java +++ b/src/PrimerDesign/src/view/FinalTemperaturePanel.java @@ -1,222 +1,223 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package view; import controller.PrimerDesign; import javax.swing.SwingConstants; /** * * @author 0907822r */ public class FinalTemperaturePanel extends javax.swing.JPanel { /** * Creates new form FinalTemperaturePanel */ public FinalTemperaturePanel() { 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() { titleLabel = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(SwingConstants.VERTICAL); reversePrimerNameLabel = new javax.swing.JLabel(); forwardPrimerNameLabel1 = new javax.swing.JLabel(); meltTempNameLabelL = new javax.swing.JLabel(); meltTempNameLabelR = new javax.swing.JLabel(); meltTempLabelForward = new javax.swing.JLabel(); meltTempLabelReverse = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); backButton = new javax.swing.JButton(); nextButton = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); forwardPrimerTextArea = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); reversePrimerTextArea = new javax.swing.JTextArea(); setPreferredSize(new java.awt.Dimension(800, 600)); titleLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); titleLabel.setText("Melting Temperatures"); reversePrimerNameLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N reversePrimerNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); reversePrimerNameLabel.setText("Reverse Primer"); forwardPrimerNameLabel1.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N forwardPrimerNameLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); forwardPrimerNameLabel1.setText("Forward Primer"); meltTempNameLabelL.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N meltTempNameLabelL.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempNameLabelL.setText("Melting Temperature"); meltTempNameLabelR.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N meltTempNameLabelR.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempNameLabelR.setText("Melting Temperature"); meltTempLabelForward.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N meltTempLabelForward.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempLabelForward.setText(Integer.toString(PrimerDesign.start.getInSequence().getFPrimer().getMeltingTemp()) + "\u2103"); meltTempLabelForward.setVerticalAlignment(javax.swing.SwingConstants.TOP); meltTempLabelReverse.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N meltTempLabelReverse.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempLabelReverse.setText(Integer.toString(PrimerDesign.start.getInSequence().getRPrimer().getMeltingTemp()) + "\u2103"); meltTempLabelReverse.setVerticalAlignment(javax.swing.SwingConstants.TOP); jTextPane1.setEditable(false); jTextPane1.setText("\n\nCongratulations, your primers meet all requirements!\n\nYou should now go to the NCBI website and perform a \"Primer Blast\" on your primers by going to the following website, (insert link here), or by following instructions on your worksheet.\n\nClick the back button to return to earlier stages if you wish to review anything you have done.\n\nClick the next button to see an animation of the results you have provided.\n\nWhen you are done, close this program by closing the window. "); jTextPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jScrollPane1.setViewportView(jTextPane1); backButton.setText("Back"); backButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backButtonActionPerformed(evt); } }); nextButton.setText("See Animation"); nextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nextButtonActionPerformed(evt); } }); forwardPrimerTextArea.setEditable(false); forwardPrimerTextArea.setColumns(20); forwardPrimerTextArea.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N forwardPrimerTextArea.setRows(1); + forwardPrimerTextArea.setToolTipText("Your Forward Primer"); jScrollPane3.setViewportView(forwardPrimerTextArea); forwardPrimerTextArea.setText(PrimerDesign.start.getInSequence().getFPrimer().toString()); reversePrimerTextArea.setEditable(false); reversePrimerTextArea.setColumns(20); reversePrimerTextArea.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N reversePrimerTextArea.setRows(1); jScrollPane4.setViewportView(reversePrimerTextArea); - forwardPrimerTextArea.setText(PrimerDesign.start.getInSequence().getRPrimer().toString()); + reversePrimerTextArea.setText(PrimerDesign.start.getInSequence().getRPrimer().toString()); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(forwardPrimerNameLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(meltTempNameLabelL, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempLabelForward, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(reversePrimerNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempNameLabelR, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempLabelReverse, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(jScrollPane4)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(titleLabel) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(reversePrimerNameLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(meltTempNameLabelR) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(meltTempLabelReverse)) .addGroup(layout.createSequentialGroup() .addComponent(forwardPrimerNameLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(meltTempNameLabelL) .addGap(12, 12, 12) .addComponent(meltTempLabelForward))) - .addGap(0, 12, Short.MAX_VALUE))) + .addGap(0, 16, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backButton) .addComponent(nextButton)) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed PrimerDesign.window.getContentPane().remove(PrimerDesign.temperature); PrimerDesign.window.setVisible(false); PrimerDesign.window.getContentPane().add(PrimerDesign.primerSelect); PrimerDesign.window.pack(); PrimerDesign.window.setVisible(true); }//GEN-LAST:event_backButtonActionPerformed private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed String[] x = new String [1]; // What does this do? -Dan x[0] = ""; PrimerDesign.window.remove(PrimerDesign.temperature); PrimerDesign.window.setVisible(false); view.PCRAnimation.main(x); }//GEN-LAST:event_nextButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backButton; private javax.swing.JLabel forwardPrimerNameLabel1; private javax.swing.JTextArea forwardPrimerTextArea; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextPane jTextPane1; private javax.swing.JLabel meltTempLabelForward; private javax.swing.JLabel meltTempLabelReverse; private javax.swing.JLabel meltTempNameLabelL; private javax.swing.JLabel meltTempNameLabelR; private javax.swing.JButton nextButton; private javax.swing.JLabel reversePrimerNameLabel; private javax.swing.JTextArea reversePrimerTextArea; private javax.swing.JLabel titleLabel; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { titleLabel = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(SwingConstants.VERTICAL); reversePrimerNameLabel = new javax.swing.JLabel(); forwardPrimerNameLabel1 = new javax.swing.JLabel(); meltTempNameLabelL = new javax.swing.JLabel(); meltTempNameLabelR = new javax.swing.JLabel(); meltTempLabelForward = new javax.swing.JLabel(); meltTempLabelReverse = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); backButton = new javax.swing.JButton(); nextButton = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); forwardPrimerTextArea = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); reversePrimerTextArea = new javax.swing.JTextArea(); setPreferredSize(new java.awt.Dimension(800, 600)); titleLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); titleLabel.setText("Melting Temperatures"); reversePrimerNameLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N reversePrimerNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); reversePrimerNameLabel.setText("Reverse Primer"); forwardPrimerNameLabel1.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N forwardPrimerNameLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); forwardPrimerNameLabel1.setText("Forward Primer"); meltTempNameLabelL.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N meltTempNameLabelL.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempNameLabelL.setText("Melting Temperature"); meltTempNameLabelR.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N meltTempNameLabelR.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempNameLabelR.setText("Melting Temperature"); meltTempLabelForward.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N meltTempLabelForward.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempLabelForward.setText(Integer.toString(PrimerDesign.start.getInSequence().getFPrimer().getMeltingTemp()) + "\u2103"); meltTempLabelForward.setVerticalAlignment(javax.swing.SwingConstants.TOP); meltTempLabelReverse.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N meltTempLabelReverse.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempLabelReverse.setText(Integer.toString(PrimerDesign.start.getInSequence().getRPrimer().getMeltingTemp()) + "\u2103"); meltTempLabelReverse.setVerticalAlignment(javax.swing.SwingConstants.TOP); jTextPane1.setEditable(false); jTextPane1.setText("\n\nCongratulations, your primers meet all requirements!\n\nYou should now go to the NCBI website and perform a \"Primer Blast\" on your primers by going to the following website, (insert link here), or by following instructions on your worksheet.\n\nClick the back button to return to earlier stages if you wish to review anything you have done.\n\nClick the next button to see an animation of the results you have provided.\n\nWhen you are done, close this program by closing the window. "); jTextPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jScrollPane1.setViewportView(jTextPane1); backButton.setText("Back"); backButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backButtonActionPerformed(evt); } }); nextButton.setText("See Animation"); nextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nextButtonActionPerformed(evt); } }); forwardPrimerTextArea.setEditable(false); forwardPrimerTextArea.setColumns(20); forwardPrimerTextArea.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N forwardPrimerTextArea.setRows(1); jScrollPane3.setViewportView(forwardPrimerTextArea); forwardPrimerTextArea.setText(PrimerDesign.start.getInSequence().getFPrimer().toString()); reversePrimerTextArea.setEditable(false); reversePrimerTextArea.setColumns(20); reversePrimerTextArea.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N reversePrimerTextArea.setRows(1); jScrollPane4.setViewportView(reversePrimerTextArea); forwardPrimerTextArea.setText(PrimerDesign.start.getInSequence().getRPrimer().toString()); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(forwardPrimerNameLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(meltTempNameLabelL, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempLabelForward, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(reversePrimerNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempNameLabelR, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempLabelReverse, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(jScrollPane4)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(titleLabel) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(reversePrimerNameLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(meltTempNameLabelR) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(meltTempLabelReverse)) .addGroup(layout.createSequentialGroup() .addComponent(forwardPrimerNameLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(meltTempNameLabelL) .addGap(12, 12, 12) .addComponent(meltTempLabelForward))) .addGap(0, 12, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backButton) .addComponent(nextButton)) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { titleLabel = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(SwingConstants.VERTICAL); reversePrimerNameLabel = new javax.swing.JLabel(); forwardPrimerNameLabel1 = new javax.swing.JLabel(); meltTempNameLabelL = new javax.swing.JLabel(); meltTempNameLabelR = new javax.swing.JLabel(); meltTempLabelForward = new javax.swing.JLabel(); meltTempLabelReverse = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); backButton = new javax.swing.JButton(); nextButton = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); forwardPrimerTextArea = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); reversePrimerTextArea = new javax.swing.JTextArea(); setPreferredSize(new java.awt.Dimension(800, 600)); titleLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); titleLabel.setText("Melting Temperatures"); reversePrimerNameLabel.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N reversePrimerNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); reversePrimerNameLabel.setText("Reverse Primer"); forwardPrimerNameLabel1.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N forwardPrimerNameLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); forwardPrimerNameLabel1.setText("Forward Primer"); meltTempNameLabelL.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N meltTempNameLabelL.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempNameLabelL.setText("Melting Temperature"); meltTempNameLabelR.setFont(new java.awt.Font("DejaVu Sans", 0, 16)); // NOI18N meltTempNameLabelR.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempNameLabelR.setText("Melting Temperature"); meltTempLabelForward.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N meltTempLabelForward.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempLabelForward.setText(Integer.toString(PrimerDesign.start.getInSequence().getFPrimer().getMeltingTemp()) + "\u2103"); meltTempLabelForward.setVerticalAlignment(javax.swing.SwingConstants.TOP); meltTempLabelReverse.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N meltTempLabelReverse.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); meltTempLabelReverse.setText(Integer.toString(PrimerDesign.start.getInSequence().getRPrimer().getMeltingTemp()) + "\u2103"); meltTempLabelReverse.setVerticalAlignment(javax.swing.SwingConstants.TOP); jTextPane1.setEditable(false); jTextPane1.setText("\n\nCongratulations, your primers meet all requirements!\n\nYou should now go to the NCBI website and perform a \"Primer Blast\" on your primers by going to the following website, (insert link here), or by following instructions on your worksheet.\n\nClick the back button to return to earlier stages if you wish to review anything you have done.\n\nClick the next button to see an animation of the results you have provided.\n\nWhen you are done, close this program by closing the window. "); jTextPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jScrollPane1.setViewportView(jTextPane1); backButton.setText("Back"); backButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backButtonActionPerformed(evt); } }); nextButton.setText("See Animation"); nextButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nextButtonActionPerformed(evt); } }); forwardPrimerTextArea.setEditable(false); forwardPrimerTextArea.setColumns(20); forwardPrimerTextArea.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N forwardPrimerTextArea.setRows(1); forwardPrimerTextArea.setToolTipText("Your Forward Primer"); jScrollPane3.setViewportView(forwardPrimerTextArea); forwardPrimerTextArea.setText(PrimerDesign.start.getInSequence().getFPrimer().toString()); reversePrimerTextArea.setEditable(false); reversePrimerTextArea.setColumns(20); reversePrimerTextArea.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N reversePrimerTextArea.setRows(1); jScrollPane4.setViewportView(reversePrimerTextArea); reversePrimerTextArea.setText(PrimerDesign.start.getInSequence().getRPrimer().toString()); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(forwardPrimerNameLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(meltTempNameLabelL, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempLabelForward, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(reversePrimerNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempNameLabelR, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(meltTempLabelReverse, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) .addComponent(jScrollPane4)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 777, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(titleLabel) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(reversePrimerNameLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(12, 12, 12) .addComponent(meltTempNameLabelR) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(meltTempLabelReverse)) .addGroup(layout.createSequentialGroup() .addComponent(forwardPrimerNameLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(meltTempNameLabelL) .addGap(12, 12, 12) .addComponent(meltTempLabelForward))) .addGap(0, 16, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backButton) .addComponent(nextButton)) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/main/java/net/pms/configuration/FormatConfiguration.java b/src/main/java/net/pms/configuration/FormatConfiguration.java index 6d57a35b4..4078e6c8a 100644 --- a/src/main/java/net/pms/configuration/FormatConfiguration.java +++ b/src/main/java/net/pms/configuration/FormatConfiguration.java @@ -1,536 +1,536 @@ package net.pms.configuration; import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import net.pms.dlna.DLNAMediaAudio; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.InputFile; import net.pms.dlna.LibMediaInfoParser; import net.pms.formats.Format; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FormatConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(FormatConfiguration.class); private ArrayList<SupportSpec> supportSpecs; // Use old parser for JPEG files (MediaInfo does not support EXIF) private static final String[] PARSER_V1_EXTENSIONS = new String[]{".jpg", ".jpe", ".jpeg"}; public static final String AAC = "aac"; public static final String AAC_HE = "aac-he"; public static final String AC3 = "ac3"; public static final String AIFF = "aiff"; public static final String ALAC = "alac"; public static final String APE = "ape"; public static final String ATRAC = "atrac"; public static final String AVI = "avi"; public static final String BMP = "bmp"; public static final String DIVX = "divx"; public static final String DTS = "dts"; public static final String DTSHD = "dtshd"; public static final String DV = "dv"; public static final String EAC3 = "eac3"; public static final String FLAC = "flac"; public static final String FLV = "flv"; public static final String GIF = "gif"; public static final String H264 = "h264"; public static final String JPG = "jpg"; public static final String LPCM = "lpcm"; public static final String MATROSKA = "mkv"; public static final String MI_GMC = "gmc"; public static final String MI_GOP = "gop"; public static final String MI_QPEL = "qpel"; public static final String MJPEG = "mjpeg"; public static final String MLP = "mlp"; public static final String MOV = "mov"; public static final String MP3 = "mp3"; public static final String MP4 = "mp4"; public static final String MPA = "mpa"; public static final String MPC = "mpc"; public static final String MPEG1 = "mpeg1"; public static final String MPEG2 = "mpeg2"; public static final String MPEGPS = "mpegps"; public static final String MPEGTS = "mpegts"; public static final String OGG = "ogg"; public static final String PNG = "png"; public static final String RA = "ra"; public static final String RM = "rm"; public static final String SHORTEN = "shn"; public static final String TIFF = "tiff"; public static final String TRUEHD = "truehd"; public static final String VC1 = "vc1"; public static final String WAVPACK = "wavpack"; public static final String WAV = "wav"; public static final String WEBM = "WebM"; public static final String WMA = "wma"; public static final String WMV = "wmv"; public static final String MIMETYPE_AUTO = "MIMETYPE_AUTO"; public static final String und = "und"; private static class SupportSpec { private int iMaxBitrate = Integer.MAX_VALUE; private int iMaxFrequency = Integer.MAX_VALUE; private int iMaxNbChannels = Integer.MAX_VALUE; private int iMaxVideoHeight = Integer.MAX_VALUE; private int iMaxVideoWidth = Integer.MAX_VALUE; private Map<String, Pattern> miExtras; private Pattern pAudioCodec; private Pattern pFormat; private Pattern pVideoCodec; private String audioCodec; private String format; private String maxBitrate; private String maxFrequency; private String maxNbChannels; private String maxVideoHeight; private String maxVideoWidth; private String mimeType; private String videoCodec; private String supportLine; SupportSpec() { this.mimeType = MIMETYPE_AUTO; } boolean isValid() { if (StringUtils.isBlank(format)) { // required LOGGER.warn("No format supplied"); return false; } else { try { pFormat = Pattern.compile(format); } catch (PatternSyntaxException pse) { LOGGER.error("Error parsing format: " + format, pse); return false; } } if (videoCodec != null) { try { pVideoCodec = Pattern.compile(videoCodec); } catch (PatternSyntaxException pse) { LOGGER.error("Error parsing video codec: " + videoCodec, pse); return false; } } if (audioCodec != null) { try { pAudioCodec = Pattern.compile(audioCodec); } catch (PatternSyntaxException pse) { LOGGER.error("Error parsing audio codec: " + audioCodec, pse); return false; } } if (maxNbChannels != null) { try { iMaxNbChannels = Integer.parseInt(maxNbChannels); } catch (NumberFormatException nfe) { LOGGER.error("Error parsing number of channels: " + maxNbChannels, nfe); return false; } } if (maxFrequency != null) { try { iMaxFrequency = Integer.parseInt(maxFrequency); } catch (NumberFormatException nfe) { LOGGER.error("Error parsing maximum frequency: " + maxFrequency, nfe); return false; } } if (maxBitrate != null) { try { iMaxBitrate = Integer.parseInt(maxBitrate); } catch (NumberFormatException nfe) { LOGGER.error("Error parsing maximum bitrate: " + maxBitrate, nfe); return false; } } if (maxVideoWidth != null) { try { iMaxVideoWidth = Integer.parseInt(maxVideoWidth); } catch (NumberFormatException nfe) { LOGGER.error("Error parsing maximum video width: " + maxVideoWidth, nfe); return false; } } if (maxVideoHeight != null) { try { iMaxVideoHeight = Integer.parseInt(maxVideoHeight); } catch (NumberFormatException nfe) { LOGGER.error("Error parsing maximum video height: " + maxVideoHeight, nfe); return false; } } return true; } public boolean match(String container, String videoCodec, String audioCodec) { return match(container, videoCodec, audioCodec, 0, 0, 0, 0, 0, null); } /** * Determine whether or not the provided parameters match the * "Supported" lines for this configuration. If a parameter is null * or 0, its value is skipped for making the match. If any of the * non-null parameters does not match, false is returned. For example, * assume a configuration that contains only the following line: * * Supported = f:mp4 n:2 * * match("mp4", null, null, 2, 0, 0, 0, 0, null) = true * match("mp4", null, null, 6, 0, 0, 0, 0, null) = false * match("wav", null, null, 2, 0, 0, 0, 0, null) = false * * @param format * @param videoCodec * @param audioCodec * @param nbAudioChannels * @param frequency * @param bitrate * @param videoWidth * @param videoHeight * @param extras * @return False if any of the provided non-null parameters is not a * match, true otherwise. */ public boolean match( String format, String videoCodec, String audioCodec, int nbAudioChannels, int frequency, int bitrate, int videoWidth, int videoHeight, Map<String, String> extras ) { // Satisfy a minimum threshold if (format == null && videoCodec == null && audioCodec == null) { // We have no matchable info. This can happen with unparsed // mediainfo objects (e.g. from WEB.conf or plugins). return false; } // Assume a match, until proven otherwise if (format != null && !pFormat.matcher(format).matches()) { LOGGER.trace("Format \"{}\" failed to match supported line {}", format, supportLine); return false; } if (videoCodec != null && pVideoCodec != null && !pVideoCodec.matcher(videoCodec).matches()) { LOGGER.trace("Video codec \"{}\" failed to match support line {}", videoCodec, supportLine); return false; } if (audioCodec != null && pAudioCodec != null && !pAudioCodec.matcher(audioCodec).matches()) { LOGGER.trace("Audio codec \"{}\" failed to match support line {}", audioCodec, supportLine); return false; } if (nbAudioChannels > 0 && iMaxNbChannels > 0 && nbAudioChannels > iMaxNbChannels) { LOGGER.trace("Number of channels \"{}\" failed to match support line {}", nbAudioChannels, supportLine); return false; } if (frequency > 0 && iMaxFrequency > 0 && frequency > iMaxFrequency) { LOGGER.trace("Frequency \"{}\" failed to match support line {}", frequency, supportLine); return false; } if (bitrate > 0 && iMaxBitrate > 0 && bitrate > iMaxBitrate) { LOGGER.trace("Bit rate \"{}\" failed to match support line {}", bitrate, supportLine); return false; } if (videoWidth > 0 && iMaxVideoWidth > 0 && videoWidth > iMaxVideoWidth) { LOGGER.trace("Video width \"{}\" failed to match support line {}", videoWidth, supportLine); return false; } if (videoHeight > 0 && iMaxVideoHeight > 0 && videoHeight > iMaxVideoHeight) { LOGGER.trace("Video height \"{}\" failed to match support line {}", videoHeight, supportLine); return false; } if (extras != null && miExtras != null) { Iterator<Entry<String, String>> keyIt = extras.entrySet().iterator(); while (keyIt.hasNext()) { - Entry<String, String> key = keyIt.next(); + String key = keyIt.next().getKey(); String value = extras.get(key); if (key.equals(MI_QPEL) && miExtras.get(MI_QPEL) != null && !miExtras.get(MI_QPEL).matcher(value).matches()) { LOGGER.trace("Qpel value \"{}\" failed to match support line {}", miExtras.get(MI_QPEL), supportLine); return false; } if (key.equals(MI_GMC) && miExtras.get(MI_GMC) != null && !miExtras.get(MI_GMC).matcher(value).matches()) { LOGGER.trace("Gmc value \"{}\" failed to match support line {}", miExtras.get(MI_GMC), supportLine); return false; } if (key.equals(MI_GOP) && miExtras.get(MI_GOP) != null && miExtras.get(MI_GOP).matcher("static").matches() && value.equals("variable")) { LOGGER.trace("GOP value \"{}\" failed to match support line {}", value, supportLine); return false; } } } LOGGER.trace("Matched support line {}", supportLine); return true; } } public FormatConfiguration(List<?> lines) { supportSpecs = new ArrayList<>(); for (Object line : lines) { if (line != null) { SupportSpec supportSpec = parseSupportLine(line.toString()); if (supportSpec.isValid()) { supportSpecs.add(supportSpec); } else { LOGGER.warn("Invalid configuration line: " + line); } } } } public void parse(DLNAMediaInfo media, InputFile file, Format ext, int type) { boolean forceV1 = false; if (file.getFile() != null) { String fName = file.getFile().getName().toLowerCase(); for (String e : PARSER_V1_EXTENSIONS) { if (fName.endsWith(e)) { forceV1 = true; break; } } if (forceV1) { // XXX this path generates thumbnails media.parse(file, ext, type, false); } else { // XXX this path doesn't generate thumbnails LibMediaInfoParser.parse(media, file, type); } } else { media.parse(file, ext, type, false); } } // XXX Unused @Deprecated public boolean isDVDVideoRemuxSupported() { return match(MPEGPS, MPEG2, null) != null; } public boolean isFormatSupported(String container) { return match(container, null, null) != null; } public boolean isDTSSupported() { return match(MPEGPS, null, DTS) != null || match(MPEGTS, null, DTS) != null; } public boolean isLPCMSupported() { return match(MPEGPS, null, LPCM) != null || match(MPEGTS, null, LPCM) != null; } public boolean isMpeg2Supported() { return match(MPEGPS, MPEG2, null) != null || match(MPEGTS, MPEG2, null) != null; } // XXX Unused @Deprecated public boolean isHiFiMusicFileSupported() { return match(WAV, null, null, 0, 96000, 0, 0, 0, null) != null || match(MP3, null, null, 0, 96000, 0, 0, 0, null) != null; } public String getPrimaryVideoTranscoder() { for (SupportSpec supportSpec : supportSpecs) { if (supportSpec.match(MPEGPS, MPEG2, AC3)) { return MPEGPS; } if (supportSpec.match(MPEGTS, MPEG2, AC3)) { return MPEGTS; } if (supportSpec.match(WMV, WMV, WMA)) { return WMV; } } return null; } // XXX Unused @Deprecated public String getPrimaryAudioTranscoder() { for (SupportSpec supportSpec : supportSpecs) { if (supportSpec.match(WAV, null, null)) { return WAV; } if (supportSpec.match(MP3, null, null)) { return MP3; } // FIXME LPCM? } return null; } /** * Match media information to audio codecs supported by the renderer and * return its MIME-type if the match is successful. Returns null if the * media is not natively supported by the renderer, which means it has * to be transcoded. * * @param media The MediaInfo metadata * @return The MIME type or null if no match was found. */ public String match(DLNAMediaInfo media) { if (media.getFirstAudioTrack() == null) { // no sound return match( media.getContainer(), media.getCodecV(), null, 0, 0, media.getBitrate(), media.getWidth(), media.getHeight(), media.getExtras() ); } else { String finalMimeType = null; for (DLNAMediaAudio audio : media.getAudioTracksList()) { String mimeType = match( media.getContainer(), media.getCodecV(), audio.getCodecA(), audio.getAudioProperties().getNumberOfChannels(), audio.getSampleRate(), media.getBitrate(), media.getWidth(), media.getHeight(), media.getExtras() ); finalMimeType = mimeType; if (mimeType == null) { // if at least one audio track is not compatible, the file must be transcoded. return null; } } return finalMimeType; } } public String match(String container, String videoCodec, String audioCodec) { return match( container, videoCodec, audioCodec, 0, 0, 0, 0, 0, null ); } public String match( String container, String videoCodec, String audioCodec, int nbAudioChannels, int frequency, int bitrate, int videoWidth, int videoHeight, Map<String, String> extras ) { String matchedMimeType = null; for (SupportSpec supportSpec : supportSpecs) { if (supportSpec.match( container, videoCodec, audioCodec, nbAudioChannels, frequency, bitrate, videoWidth, videoHeight, extras )) { matchedMimeType = supportSpec.mimeType; break; } } return matchedMimeType; } private SupportSpec parseSupportLine(String line) { StringTokenizer st = new StringTokenizer(line, "\t "); SupportSpec supportSpec = new SupportSpec(); supportSpec.supportLine = line; while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.startsWith("f:")) { supportSpec.format = token.substring(2).trim(); } else if (token.startsWith("v:")) { supportSpec.videoCodec = token.substring(2).trim(); } else if (token.startsWith("a:")) { supportSpec.audioCodec = token.substring(2).trim(); } else if (token.startsWith("n:")) { supportSpec.maxNbChannels = token.substring(2).trim(); } else if (token.startsWith("s:")) { supportSpec.maxFrequency = token.substring(2).trim(); } else if (token.startsWith("w:")) { supportSpec.maxVideoWidth = token.substring(2).trim(); } else if (token.startsWith("h:")) { supportSpec.maxVideoHeight = token.substring(2).trim(); } else if (token.startsWith("m:")) { supportSpec.mimeType = token.substring(2).trim(); } else if (token.startsWith("b:")) { supportSpec.maxBitrate = token.substring(2).trim(); } else if (token.contains(":")) { // Extra MediaInfo stuff if (supportSpec.miExtras == null) { supportSpec.miExtras = new HashMap<>(); } String key = token.substring(0, token.indexOf(':')); String value = token.substring(token.indexOf(':') + 1); supportSpec.miExtras.put(key, Pattern.compile(value)); } } return supportSpec; } }
true
true
public boolean match( String format, String videoCodec, String audioCodec, int nbAudioChannels, int frequency, int bitrate, int videoWidth, int videoHeight, Map<String, String> extras ) { // Satisfy a minimum threshold if (format == null && videoCodec == null && audioCodec == null) { // We have no matchable info. This can happen with unparsed // mediainfo objects (e.g. from WEB.conf or plugins). return false; } // Assume a match, until proven otherwise if (format != null && !pFormat.matcher(format).matches()) { LOGGER.trace("Format \"{}\" failed to match supported line {}", format, supportLine); return false; } if (videoCodec != null && pVideoCodec != null && !pVideoCodec.matcher(videoCodec).matches()) { LOGGER.trace("Video codec \"{}\" failed to match support line {}", videoCodec, supportLine); return false; } if (audioCodec != null && pAudioCodec != null && !pAudioCodec.matcher(audioCodec).matches()) { LOGGER.trace("Audio codec \"{}\" failed to match support line {}", audioCodec, supportLine); return false; } if (nbAudioChannels > 0 && iMaxNbChannels > 0 && nbAudioChannels > iMaxNbChannels) { LOGGER.trace("Number of channels \"{}\" failed to match support line {}", nbAudioChannels, supportLine); return false; } if (frequency > 0 && iMaxFrequency > 0 && frequency > iMaxFrequency) { LOGGER.trace("Frequency \"{}\" failed to match support line {}", frequency, supportLine); return false; } if (bitrate > 0 && iMaxBitrate > 0 && bitrate > iMaxBitrate) { LOGGER.trace("Bit rate \"{}\" failed to match support line {}", bitrate, supportLine); return false; } if (videoWidth > 0 && iMaxVideoWidth > 0 && videoWidth > iMaxVideoWidth) { LOGGER.trace("Video width \"{}\" failed to match support line {}", videoWidth, supportLine); return false; } if (videoHeight > 0 && iMaxVideoHeight > 0 && videoHeight > iMaxVideoHeight) { LOGGER.trace("Video height \"{}\" failed to match support line {}", videoHeight, supportLine); return false; } if (extras != null && miExtras != null) { Iterator<Entry<String, String>> keyIt = extras.entrySet().iterator(); while (keyIt.hasNext()) { Entry<String, String> key = keyIt.next(); String value = extras.get(key); if (key.equals(MI_QPEL) && miExtras.get(MI_QPEL) != null && !miExtras.get(MI_QPEL).matcher(value).matches()) { LOGGER.trace("Qpel value \"{}\" failed to match support line {}", miExtras.get(MI_QPEL), supportLine); return false; } if (key.equals(MI_GMC) && miExtras.get(MI_GMC) != null && !miExtras.get(MI_GMC).matcher(value).matches()) { LOGGER.trace("Gmc value \"{}\" failed to match support line {}", miExtras.get(MI_GMC), supportLine); return false; } if (key.equals(MI_GOP) && miExtras.get(MI_GOP) != null && miExtras.get(MI_GOP).matcher("static").matches() && value.equals("variable")) { LOGGER.trace("GOP value \"{}\" failed to match support line {}", value, supportLine); return false; } } } LOGGER.trace("Matched support line {}", supportLine); return true; }
public boolean match( String format, String videoCodec, String audioCodec, int nbAudioChannels, int frequency, int bitrate, int videoWidth, int videoHeight, Map<String, String> extras ) { // Satisfy a minimum threshold if (format == null && videoCodec == null && audioCodec == null) { // We have no matchable info. This can happen with unparsed // mediainfo objects (e.g. from WEB.conf or plugins). return false; } // Assume a match, until proven otherwise if (format != null && !pFormat.matcher(format).matches()) { LOGGER.trace("Format \"{}\" failed to match supported line {}", format, supportLine); return false; } if (videoCodec != null && pVideoCodec != null && !pVideoCodec.matcher(videoCodec).matches()) { LOGGER.trace("Video codec \"{}\" failed to match support line {}", videoCodec, supportLine); return false; } if (audioCodec != null && pAudioCodec != null && !pAudioCodec.matcher(audioCodec).matches()) { LOGGER.trace("Audio codec \"{}\" failed to match support line {}", audioCodec, supportLine); return false; } if (nbAudioChannels > 0 && iMaxNbChannels > 0 && nbAudioChannels > iMaxNbChannels) { LOGGER.trace("Number of channels \"{}\" failed to match support line {}", nbAudioChannels, supportLine); return false; } if (frequency > 0 && iMaxFrequency > 0 && frequency > iMaxFrequency) { LOGGER.trace("Frequency \"{}\" failed to match support line {}", frequency, supportLine); return false; } if (bitrate > 0 && iMaxBitrate > 0 && bitrate > iMaxBitrate) { LOGGER.trace("Bit rate \"{}\" failed to match support line {}", bitrate, supportLine); return false; } if (videoWidth > 0 && iMaxVideoWidth > 0 && videoWidth > iMaxVideoWidth) { LOGGER.trace("Video width \"{}\" failed to match support line {}", videoWidth, supportLine); return false; } if (videoHeight > 0 && iMaxVideoHeight > 0 && videoHeight > iMaxVideoHeight) { LOGGER.trace("Video height \"{}\" failed to match support line {}", videoHeight, supportLine); return false; } if (extras != null && miExtras != null) { Iterator<Entry<String, String>> keyIt = extras.entrySet().iterator(); while (keyIt.hasNext()) { String key = keyIt.next().getKey(); String value = extras.get(key); if (key.equals(MI_QPEL) && miExtras.get(MI_QPEL) != null && !miExtras.get(MI_QPEL).matcher(value).matches()) { LOGGER.trace("Qpel value \"{}\" failed to match support line {}", miExtras.get(MI_QPEL), supportLine); return false; } if (key.equals(MI_GMC) && miExtras.get(MI_GMC) != null && !miExtras.get(MI_GMC).matcher(value).matches()) { LOGGER.trace("Gmc value \"{}\" failed to match support line {}", miExtras.get(MI_GMC), supportLine); return false; } if (key.equals(MI_GOP) && miExtras.get(MI_GOP) != null && miExtras.get(MI_GOP).matcher("static").matches() && value.equals("variable")) { LOGGER.trace("GOP value \"{}\" failed to match support line {}", value, supportLine); return false; } } } LOGGER.trace("Matched support line {}", supportLine); return true; }
diff --git a/astCreator/src/main/java/com/lausdahl/ast/creator/methods/RemoveChildMethod.java b/astCreator/src/main/java/com/lausdahl/ast/creator/methods/RemoveChildMethod.java index 621013f..39fd409 100644 --- a/astCreator/src/main/java/com/lausdahl/ast/creator/methods/RemoveChildMethod.java +++ b/astCreator/src/main/java/com/lausdahl/ast/creator/methods/RemoveChildMethod.java @@ -1,142 +1,142 @@ package com.lausdahl.ast.creator.methods; import java.util.List; import java.util.Vector; import com.lausdahl.ast.creator.definitions.ExternalJavaClassDefinition; import com.lausdahl.ast.creator.definitions.Field; import com.lausdahl.ast.creator.definitions.Field.StructureType; import com.lausdahl.ast.creator.definitions.IClassDefinition; import com.lausdahl.ast.creator.definitions.JavaTypes; import com.lausdahl.ast.creator.env.Environment; public class RemoveChildMethod extends Method { List<Field> fields = new Vector<Field>(); public RemoveChildMethod(IClassDefinition c, Environment env) { super(c, env); this.env = env; } @Override protected void prepare() { fields.clear(); fields.addAll(classDefinition.getInheritedFields()); fields.addAll(classDefinition.getFields()); javaDoc = "\t/**\n"; javaDoc += "\t * Removes the {@link " + env.iNode.getName().getName() + "} {@code child} as a child of this {@link " + classDefinition.getName().getName() + "} node.\n"; javaDoc += "\t * Do not call this method with any graph fields of this node. This will cause any child's\n\t * with the same reference to be removed unintentionally or {@link RuntimeException}will be thrown.\n"; javaDoc += "\t * @param child the child node to be removed from this {@link " + classDefinition.getName().getName() + "} node\n"; javaDoc += "\t * @throws RuntimeException if {@code child} is not a child of this {@link " + classDefinition.getName().getName() + "} node\n"; javaDoc += "\t */"; this.name = "removeChild"; this.arguments.add(new Argument(env.iNode.getName().getName(), "child")); StringBuilder sb = new StringBuilder(); for (Field field : fields) { if (JavaTypes.isPrimitiveType(field.type.getName().getName())) { continue; } if (field.structureType == StructureType.Graph) { if (!field.isList) { // We need to ignore this since the parent might have been set to this node as a lack of a better // parent sb.append("\t\tif (this." + field.getName() + " == child) {\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); continue; } else { sb.append("\t\tif (this." + field.getName() - + ".remove(child)) {\n"); + + ".contains(child)) {\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); continue; } } if ((field.isTokenField && !(field.type instanceof ExternalJavaClassDefinition && ((ExternalJavaClassDefinition) field.type).extendsNode))) { continue; } if (!field.isList) { sb.append("\t\tif (this." + field.getName() + " == child) {\n"); sb.append("\t\t\tthis." + field.getName() + " = null;\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); } else { sb.append("\t\tif (this." + field.getName() + ".remove(child)) {\n"); sb.append("\t\t\t return;\n"); sb.append("\t\t}\n"); } } sb.append("\t\tthrow new RuntimeException(\"Not a child.\");"); this.body = sb.toString(); } @Override protected void prepareVdm() { fields.clear(); fields.addAll(classDefinition.getInheritedFields()); fields.addAll(classDefinition.getFields()); javaDoc = "\t/**\n"; javaDoc += "\t * Removes the {@link Node} {@code child} as a child of this {@link " + classDefinition.getName() + "} node.\n"; javaDoc += "\t * @param child the child node to be removed from this {@link " + classDefinition.getName() + "} node\n"; javaDoc += "\t * @throws RuntimeException if {@code child} is not a child of this {@link " + classDefinition.getName() + "} node\n"; javaDoc += "\t */"; this.name = "removeChild"; this.arguments.add(new Argument("Node", "child")); StringBuilder sb = new StringBuilder(); for (Field field : fields) { if (field.isTokenField || field.isAspect) { continue; } if (!field.isList) { sb.append("\t\tif this." + field.getName() + " = child then (\n"); sb.append("\t\t\tthis." + field.getName() + " := null;\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t);\n\n"); } else { sb.append("\t\tif this." + field.getName() + ".remove(child) then (\n"); sb.append("\t\t\t return;\n"); sb.append("\t\t);\n"); } } sb.append("\t\texit new RuntimeException(\"Not a child.\");"); this.body = sb.toString(); } }
true
true
protected void prepare() { fields.clear(); fields.addAll(classDefinition.getInheritedFields()); fields.addAll(classDefinition.getFields()); javaDoc = "\t/**\n"; javaDoc += "\t * Removes the {@link " + env.iNode.getName().getName() + "} {@code child} as a child of this {@link " + classDefinition.getName().getName() + "} node.\n"; javaDoc += "\t * Do not call this method with any graph fields of this node. This will cause any child's\n\t * with the same reference to be removed unintentionally or {@link RuntimeException}will be thrown.\n"; javaDoc += "\t * @param child the child node to be removed from this {@link " + classDefinition.getName().getName() + "} node\n"; javaDoc += "\t * @throws RuntimeException if {@code child} is not a child of this {@link " + classDefinition.getName().getName() + "} node\n"; javaDoc += "\t */"; this.name = "removeChild"; this.arguments.add(new Argument(env.iNode.getName().getName(), "child")); StringBuilder sb = new StringBuilder(); for (Field field : fields) { if (JavaTypes.isPrimitiveType(field.type.getName().getName())) { continue; } if (field.structureType == StructureType.Graph) { if (!field.isList) { // We need to ignore this since the parent might have been set to this node as a lack of a better // parent sb.append("\t\tif (this." + field.getName() + " == child) {\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); continue; } else { sb.append("\t\tif (this." + field.getName() + ".remove(child)) {\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); continue; } } if ((field.isTokenField && !(field.type instanceof ExternalJavaClassDefinition && ((ExternalJavaClassDefinition) field.type).extendsNode))) { continue; } if (!field.isList) { sb.append("\t\tif (this." + field.getName() + " == child) {\n"); sb.append("\t\t\tthis." + field.getName() + " = null;\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); } else { sb.append("\t\tif (this." + field.getName() + ".remove(child)) {\n"); sb.append("\t\t\t return;\n"); sb.append("\t\t}\n"); } } sb.append("\t\tthrow new RuntimeException(\"Not a child.\");"); this.body = sb.toString(); }
protected void prepare() { fields.clear(); fields.addAll(classDefinition.getInheritedFields()); fields.addAll(classDefinition.getFields()); javaDoc = "\t/**\n"; javaDoc += "\t * Removes the {@link " + env.iNode.getName().getName() + "} {@code child} as a child of this {@link " + classDefinition.getName().getName() + "} node.\n"; javaDoc += "\t * Do not call this method with any graph fields of this node. This will cause any child's\n\t * with the same reference to be removed unintentionally or {@link RuntimeException}will be thrown.\n"; javaDoc += "\t * @param child the child node to be removed from this {@link " + classDefinition.getName().getName() + "} node\n"; javaDoc += "\t * @throws RuntimeException if {@code child} is not a child of this {@link " + classDefinition.getName().getName() + "} node\n"; javaDoc += "\t */"; this.name = "removeChild"; this.arguments.add(new Argument(env.iNode.getName().getName(), "child")); StringBuilder sb = new StringBuilder(); for (Field field : fields) { if (JavaTypes.isPrimitiveType(field.type.getName().getName())) { continue; } if (field.structureType == StructureType.Graph) { if (!field.isList) { // We need to ignore this since the parent might have been set to this node as a lack of a better // parent sb.append("\t\tif (this." + field.getName() + " == child) {\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); continue; } else { sb.append("\t\tif (this." + field.getName() + ".contains(child)) {\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); continue; } } if ((field.isTokenField && !(field.type instanceof ExternalJavaClassDefinition && ((ExternalJavaClassDefinition) field.type).extendsNode))) { continue; } if (!field.isList) { sb.append("\t\tif (this." + field.getName() + " == child) {\n"); sb.append("\t\t\tthis." + field.getName() + " = null;\n"); sb.append("\t\t\treturn;\n"); sb.append("\t\t}\n\n"); } else { sb.append("\t\tif (this." + field.getName() + ".remove(child)) {\n"); sb.append("\t\t\t return;\n"); sb.append("\t\t}\n"); } } sb.append("\t\tthrow new RuntimeException(\"Not a child.\");"); this.body = sb.toString(); }
diff --git a/source/de/anomic/data/WorkTables.java b/source/de/anomic/data/WorkTables.java index 4420ea2bc..a1280f811 100644 --- a/source/de/anomic/data/WorkTables.java +++ b/source/de/anomic/data/WorkTables.java @@ -1,71 +1,73 @@ // Work.java // (C) 2010 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany // first published 04.02.2010 on http://yacy.net // // This is a part of YaCy, a peer-to-peer based web search engine // // $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $ // $LastChangedRevision: 6539 $ // $LastChangedBy: low012 $ // // LICENSE // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package de.anomic.data; import java.io.File; import java.io.IOException; import java.util.Date; import net.yacy.kelondro.blob.Tables; import net.yacy.kelondro.logging.Log; import net.yacy.kelondro.util.DateFormatter; import de.anomic.server.serverObjects; public class WorkTables extends Tables { public final static String TABLE_API_NAME = "api"; public final static String TABLE_API_TYPE_STEERING = "steering"; public final static String TABLE_API_TYPE_CONFIGURATION = "configuration"; public final static String TABLE_API_TYPE_CRAWLER = "crawler"; public final static String TABLE_API_COL_TYPE = "type"; public final static String TABLE_API_COL_COMMENT = "comment"; public final static String TABLE_API_COL_DATE = "date"; public final static String TABLE_API_COL_URL = "url"; public WorkTables(File workPath) { super(workPath, 12); } public void recordAPICall(final serverObjects post, final String servletName, String type, String comment) { String apiurl = /*"http://localhost:" + getConfig("port", "8080") +*/ "/" + servletName + "?" + post.toString(); try { super.insert( TABLE_API_NAME, TABLE_API_COL_TYPE, type.getBytes(), TABLE_API_COL_COMMENT, comment.getBytes(), TABLE_API_COL_DATE, DateFormatter.formatShortMilliSecond(new Date()).getBytes(), TABLE_API_COL_URL, apiurl.getBytes() ); } catch (IOException e) { Log.logException(e); + } catch (NullPointerException e) { + Log.logException(e); } Log.logInfo("APICALL", apiurl); } }
true
true
public void recordAPICall(final serverObjects post, final String servletName, String type, String comment) { String apiurl = /*"http://localhost:" + getConfig("port", "8080") +*/ "/" + servletName + "?" + post.toString(); try { super.insert( TABLE_API_NAME, TABLE_API_COL_TYPE, type.getBytes(), TABLE_API_COL_COMMENT, comment.getBytes(), TABLE_API_COL_DATE, DateFormatter.formatShortMilliSecond(new Date()).getBytes(), TABLE_API_COL_URL, apiurl.getBytes() ); } catch (IOException e) { Log.logException(e); } Log.logInfo("APICALL", apiurl); }
public void recordAPICall(final serverObjects post, final String servletName, String type, String comment) { String apiurl = /*"http://localhost:" + getConfig("port", "8080") +*/ "/" + servletName + "?" + post.toString(); try { super.insert( TABLE_API_NAME, TABLE_API_COL_TYPE, type.getBytes(), TABLE_API_COL_COMMENT, comment.getBytes(), TABLE_API_COL_DATE, DateFormatter.formatShortMilliSecond(new Date()).getBytes(), TABLE_API_COL_URL, apiurl.getBytes() ); } catch (IOException e) { Log.logException(e); } catch (NullPointerException e) { Log.logException(e); } Log.logInfo("APICALL", apiurl); }
diff --git a/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/editor/SyntaxErrorsHighlightingTask.java b/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/editor/SyntaxErrorsHighlightingTask.java index bc3e0a80..358107ff 100644 --- a/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/editor/SyntaxErrorsHighlightingTask.java +++ b/javafx.fxd/src/org/netbeans/modules/javafx/fxd/composer/editor/SyntaxErrorsHighlightingTask.java @@ -1,135 +1,138 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.fxd.composer.editor; import com.sun.javafx.tools.fxd.container.scene.fxd.FXDSyntaxErrorException; import java.util.ArrayList; import java.util.List; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.netbeans.editor.BaseDocument; import org.netbeans.editor.Utilities; import org.netbeans.modules.editor.indent.api.IndentUtils; import org.netbeans.modules.javafx.fxd.composer.editor.parser.FXDSyntaxErrorParser.FXDParserResult; import org.netbeans.modules.parsing.spi.Parser.Result; import org.netbeans.modules.parsing.spi.ParserResultTask; import org.netbeans.modules.parsing.spi.Scheduler; import org.netbeans.modules.parsing.spi.SchedulerEvent; import org.netbeans.spi.editor.hints.ErrorDescription; import org.netbeans.spi.editor.hints.ErrorDescriptionFactory; import org.netbeans.spi.editor.hints.HintsController; import org.netbeans.spi.editor.hints.Severity; import org.openide.util.Exceptions; /** * * @author Andrey Korostelev */ public class SyntaxErrorsHighlightingTask extends ParserResultTask { public SyntaxErrorsHighlightingTask() { } @Override public void run(Result result, SchedulerEvent event) { try { + Document document = result.getSnapshot().getSource().getDocument(false); + if(document == null){ + return; + } FXDParserResult fxdResult = (FXDParserResult) result; List<FXDSyntaxErrorException> syntaxErrors = fxdResult.getSyntaxErrors(); - Document document = result.getSnapshot().getSource().getDocument(false); List<ErrorDescription> errors = new ArrayList<ErrorDescription>(); for (FXDSyntaxErrorException syntaxError : syntaxErrors) { int ErrRow = getRow(syntaxError, (BaseDocument) document); int ErrPosition = getPosition(syntaxError, (BaseDocument) document); ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription( Severity.ERROR, syntaxError.getMessage() + " at [" + ErrRow + "," + ErrPosition + "]", document, ErrRow); errors.add(errorDescription); } if (document != null) { HintsController.setErrors(document, "simple-java", errors); } } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } catch (org.netbeans.modules.parsing.spi.ParseException ex1) { Exceptions.printStackTrace (ex1); } } private int getRow(FXDSyntaxErrorException syntaxError, BaseDocument document) throws BadLocationException { return Utilities.getRowCount(document, 0, syntaxError.getOffset()); } private int getPosition(FXDSyntaxErrorException syntaxError, BaseDocument document) throws BadLocationException { int offset = syntaxError.getOffset(); if (offset > -1) { int rowStart = Utilities.getRowStart((BaseDocument) document, offset); int position = offset - rowStart; int tabs = syntaxError.getTabsInLastRow(); if (tabs > 0) { // replace 1 tab char by number of spaces in tab position = position - tabs + (tabs * IndentUtils.tabSize(document)); } return position; } return 0; } @Override public int getPriority() { return 100; } @Override public Class<? extends Scheduler> getSchedulerClass() { return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER; } @Override public void cancel() { } }
false
true
public void run(Result result, SchedulerEvent event) { try { FXDParserResult fxdResult = (FXDParserResult) result; List<FXDSyntaxErrorException> syntaxErrors = fxdResult.getSyntaxErrors(); Document document = result.getSnapshot().getSource().getDocument(false); List<ErrorDescription> errors = new ArrayList<ErrorDescription>(); for (FXDSyntaxErrorException syntaxError : syntaxErrors) { int ErrRow = getRow(syntaxError, (BaseDocument) document); int ErrPosition = getPosition(syntaxError, (BaseDocument) document); ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription( Severity.ERROR, syntaxError.getMessage() + " at [" + ErrRow + "," + ErrPosition + "]", document, ErrRow); errors.add(errorDescription); } if (document != null) { HintsController.setErrors(document, "simple-java", errors); } } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } catch (org.netbeans.modules.parsing.spi.ParseException ex1) { Exceptions.printStackTrace (ex1); } }
public void run(Result result, SchedulerEvent event) { try { Document document = result.getSnapshot().getSource().getDocument(false); if(document == null){ return; } FXDParserResult fxdResult = (FXDParserResult) result; List<FXDSyntaxErrorException> syntaxErrors = fxdResult.getSyntaxErrors(); List<ErrorDescription> errors = new ArrayList<ErrorDescription>(); for (FXDSyntaxErrorException syntaxError : syntaxErrors) { int ErrRow = getRow(syntaxError, (BaseDocument) document); int ErrPosition = getPosition(syntaxError, (BaseDocument) document); ErrorDescription errorDescription = ErrorDescriptionFactory.createErrorDescription( Severity.ERROR, syntaxError.getMessage() + " at [" + ErrRow + "," + ErrPosition + "]", document, ErrRow); errors.add(errorDescription); } if (document != null) { HintsController.setErrors(document, "simple-java", errors); } } catch (BadLocationException ex1) { Exceptions.printStackTrace(ex1); } catch (org.netbeans.modules.parsing.spi.ParseException ex1) { Exceptions.printStackTrace (ex1); } }
diff --git a/luni/src/main/java/java/math/Multiplication.java b/luni/src/main/java/java/math/Multiplication.java index 25fd31c55..b932704f0 100644 --- a/luni/src/main/java/java/math/Multiplication.java +++ b/luni/src/main/java/java/math/Multiplication.java @@ -1,194 +1,194 @@ /* * 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 java.math; /** * Static library that provides all multiplication of {@link BigInteger} methods. */ class Multiplication { /** Just to denote that this class can't be instantiated. */ private Multiplication() {} // BEGIN android-removed // /** // * Break point in digits (number of {@code int} elements) // * between Karatsuba and Pencil and Paper multiply. // */ // static final int whenUseKaratsuba = 63; // an heuristic value // END android-removed /** * An array with powers of ten that fit in the type {@code int}. * ({@code 10^0,10^1,...,10^9}) */ static final int tenPows[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; /** * An array with powers of five that fit in the type {@code int}. * ({@code 5^0,5^1,...,5^13}) */ static final int fivePows[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625, 1220703125 }; /** * An array with the first powers of ten in {@code BigInteger} version. * ({@code 10^0,10^1,...,10^31}) */ static final BigInteger[] bigTenPows = new BigInteger[32]; /** * An array with the first powers of five in {@code BigInteger} version. * ({@code 5^0,5^1,...,5^31}) */ static final BigInteger bigFivePows[] = new BigInteger[32]; static { int i; long fivePow = 1L; for (i = 0; i <= 18; i++) { bigFivePows[i] = BigInteger.valueOf(fivePow); bigTenPows[i] = BigInteger.valueOf(fivePow << i); fivePow *= 5; } for (; i < bigTenPows.length; i++) { bigFivePows[i] = bigFivePows[i - 1].multiply(bigFivePows[1]); bigTenPows[i] = bigTenPows[i - 1].multiply(BigInteger.TEN); } } // BEGIN android-note // The method multiply has been removed in favor of using OpenSSL BIGNUM // END android-note /** * Multiplies a number by a positive integer. * @param val an arbitrary {@code BigInteger} * @param factor a positive {@code int} number * @return {@code val * factor} */ static BigInteger multiplyByPositiveInt(BigInteger val, int factor) { // BEGIN android-changed BigInt bi = val.bigInt.copy(); bi.multiplyByPositiveInt(factor); return new BigInteger(bi); // END android-changed } /** * Multiplies a number by a power of ten. * This method is used in {@code BigDecimal} class. * @param val the number to be multiplied * @param exp a positive {@code long} exponent * @return {@code val * 10<sup>exp</sup>} */ static BigInteger multiplyByTenPow(BigInteger val, long exp) { // PRE: exp >= 0 return ((exp < tenPows.length) ? multiplyByPositiveInt(val, tenPows[(int)exp]) : val.multiply(powerOf10(exp))); } /** * It calculates a power of ten, which exponent could be out of 32-bit range. * Note that internally this method will be used in the worst case with * an exponent equals to: {@code Integer.MAX_VALUE - Integer.MIN_VALUE}. * @param exp the exponent of power of ten, it must be positive. * @return a {@code BigInteger} with value {@code 10<sup>exp</sup>}. */ static BigInteger powerOf10(long exp) { // PRE: exp >= 0 int intExp = (int)exp; // "SMALL POWERS" if (exp < bigTenPows.length) { // The largest power that fit in 'long' type return bigTenPows[intExp]; } else if (exp <= 50) { // To calculate: 10^exp return BigInteger.TEN.pow(intExp); } else if (exp <= 1000) { // To calculate: 5^exp * 2^exp return bigFivePows[1].pow(intExp).shiftLeft(intExp); } // "LARGE POWERS" /* * To check if there is free memory to allocate a BigInteger of the * estimated size, measured in bytes: 1 + [exp / log10(2)] */ long byteArraySize = 1 + (long)(exp / 2.4082399653118496); if (byteArraySize > Runtime.getRuntime().freeMemory()) { - throw new OutOfMemoryError(); + throw new ArithmeticException(); } if (exp <= Integer.MAX_VALUE) { // To calculate: 5^exp * 2^exp return bigFivePows[1].pow(intExp).shiftLeft(intExp); } /* * "HUGE POWERS" * * This branch probably won't be executed since the power of ten is too * big. */ // To calculate: 5^exp BigInteger powerOfFive = bigFivePows[1].pow(Integer.MAX_VALUE); BigInteger res = powerOfFive; long longExp = exp - Integer.MAX_VALUE; intExp = (int)(exp % Integer.MAX_VALUE); while (longExp > Integer.MAX_VALUE) { res = res.multiply(powerOfFive); longExp -= Integer.MAX_VALUE; } res = res.multiply(bigFivePows[1].pow(intExp)); // To calculate: 5^exp << exp res = res.shiftLeft(Integer.MAX_VALUE); longExp = exp - Integer.MAX_VALUE; while (longExp > Integer.MAX_VALUE) { res = res.shiftLeft(Integer.MAX_VALUE); longExp -= Integer.MAX_VALUE; } res = res.shiftLeft(intExp); return res; } /** * Multiplies a number by a power of five. * This method is used in {@code BigDecimal} class. * @param val the number to be multiplied * @param exp a positive {@code int} exponent * @return {@code val * 5<sup>exp</sup>} */ static BigInteger multiplyByFivePow(BigInteger val, int exp) { // PRE: exp >= 0 if (exp < fivePows.length) { return multiplyByPositiveInt(val, fivePows[exp]); } else if (exp < bigFivePows.length) { return val.multiply(bigFivePows[exp]); } else {// Large powers of five return val.multiply(bigFivePows[1].pow(exp)); } } }
true
true
static BigInteger powerOf10(long exp) { // PRE: exp >= 0 int intExp = (int)exp; // "SMALL POWERS" if (exp < bigTenPows.length) { // The largest power that fit in 'long' type return bigTenPows[intExp]; } else if (exp <= 50) { // To calculate: 10^exp return BigInteger.TEN.pow(intExp); } else if (exp <= 1000) { // To calculate: 5^exp * 2^exp return bigFivePows[1].pow(intExp).shiftLeft(intExp); } // "LARGE POWERS" /* * To check if there is free memory to allocate a BigInteger of the * estimated size, measured in bytes: 1 + [exp / log10(2)] */ long byteArraySize = 1 + (long)(exp / 2.4082399653118496); if (byteArraySize > Runtime.getRuntime().freeMemory()) { throw new OutOfMemoryError(); } if (exp <= Integer.MAX_VALUE) { // To calculate: 5^exp * 2^exp return bigFivePows[1].pow(intExp).shiftLeft(intExp); } /* * "HUGE POWERS" * * This branch probably won't be executed since the power of ten is too * big. */ // To calculate: 5^exp BigInteger powerOfFive = bigFivePows[1].pow(Integer.MAX_VALUE); BigInteger res = powerOfFive; long longExp = exp - Integer.MAX_VALUE; intExp = (int)(exp % Integer.MAX_VALUE); while (longExp > Integer.MAX_VALUE) { res = res.multiply(powerOfFive); longExp -= Integer.MAX_VALUE; } res = res.multiply(bigFivePows[1].pow(intExp)); // To calculate: 5^exp << exp res = res.shiftLeft(Integer.MAX_VALUE); longExp = exp - Integer.MAX_VALUE; while (longExp > Integer.MAX_VALUE) { res = res.shiftLeft(Integer.MAX_VALUE); longExp -= Integer.MAX_VALUE; } res = res.shiftLeft(intExp); return res; }
static BigInteger powerOf10(long exp) { // PRE: exp >= 0 int intExp = (int)exp; // "SMALL POWERS" if (exp < bigTenPows.length) { // The largest power that fit in 'long' type return bigTenPows[intExp]; } else if (exp <= 50) { // To calculate: 10^exp return BigInteger.TEN.pow(intExp); } else if (exp <= 1000) { // To calculate: 5^exp * 2^exp return bigFivePows[1].pow(intExp).shiftLeft(intExp); } // "LARGE POWERS" /* * To check if there is free memory to allocate a BigInteger of the * estimated size, measured in bytes: 1 + [exp / log10(2)] */ long byteArraySize = 1 + (long)(exp / 2.4082399653118496); if (byteArraySize > Runtime.getRuntime().freeMemory()) { throw new ArithmeticException(); } if (exp <= Integer.MAX_VALUE) { // To calculate: 5^exp * 2^exp return bigFivePows[1].pow(intExp).shiftLeft(intExp); } /* * "HUGE POWERS" * * This branch probably won't be executed since the power of ten is too * big. */ // To calculate: 5^exp BigInteger powerOfFive = bigFivePows[1].pow(Integer.MAX_VALUE); BigInteger res = powerOfFive; long longExp = exp - Integer.MAX_VALUE; intExp = (int)(exp % Integer.MAX_VALUE); while (longExp > Integer.MAX_VALUE) { res = res.multiply(powerOfFive); longExp -= Integer.MAX_VALUE; } res = res.multiply(bigFivePows[1].pow(intExp)); // To calculate: 5^exp << exp res = res.shiftLeft(Integer.MAX_VALUE); longExp = exp - Integer.MAX_VALUE; while (longExp > Integer.MAX_VALUE) { res = res.shiftLeft(Integer.MAX_VALUE); longExp -= Integer.MAX_VALUE; } res = res.shiftLeft(intExp); return res; }
diff --git a/SimpleAndroidApp/src/org/ivan/simple/game/hero/Hero.java b/SimpleAndroidApp/src/org/ivan/simple/game/hero/Hero.java index d90a404..f4c622d 100644 --- a/SimpleAndroidApp/src/org/ivan/simple/game/hero/Hero.java +++ b/SimpleAndroidApp/src/org/ivan/simple/game/hero/Hero.java @@ -1,565 +1,565 @@ package org.ivan.simple.game.hero; import org.ivan.simple.game.motion.Motion; import org.ivan.simple.game.motion.MotionType; import org.ivan.simple.game.level.LevelCell; import org.ivan.simple.game.level.PlatformType; import android.graphics.Canvas; public class Hero { /** * Save prev motion after set changed. Prev motion used to get proper animation. * For example, if prev motion was STEP_LEFT and next motion will be STAY, * Panda schould turn 90 degrees right in air while jumping on place. */ private boolean finishingState = false; private LevelCell prevCell; private Sprite activeSprite; private TPSprite tpSprite; private SpriteSet sprites; public int x; public int y; private int prevX; private int prevY; public final HeroModel model; public Hero(HeroModel model) { this.model = model; sprites = SpriteSet.getPandaSprites(); activeSprite = sprites.getSprite("stay"); tpSprite = sprites.getTPSprite("stepleft_tp"); } public boolean isFinishing() { return finishingState; } /* properly 'was', 'has been'? */ public boolean isFinishingMotionEnded(/*Motion prevMotion*/) { if(activeSprite.getFrame() == 0 || (model.finishingMotion.getType() == MotionType.FLY_LEFT && activeSprite.getFrame() == 4) || (model.finishingMotion.getType() == MotionType.FLY_RIGHT && activeSprite.getFrame() == 4)) { finishingState = false; return true; } else { return false; } } /** * Check if hero is in control state: ready for begin new motion type. * Used each game loop iteration to know is it time to process user controls * and achieve new motion type. * More often there is control state when next frame is first frame of animation. * @return */ public boolean isInControlState() { if((model.finishingMotion.getType() == MotionType.FLY_LEFT || model.finishingMotion.getType() == MotionType.FLY_RIGHT) && finishingState) { return activeSprite.getFrame() == 4; } if(model.currentMotion.getType() == MotionType.FALL_BLANSH) { return activeSprite.getFrame() % 8 == 0; } if(prevCell != null && prevCell.getFloor().getType() == PlatformType.GLUE) { return activeSprite.getFrame() % 8 == 0; } return activeSprite.getFrame() == 0 && tpSprite.getFrame() == 0; } /** * Change hero behavior (animation) depending on motion type. * Used after new motion type is obtained. * Goal is to play start/end animations of motions. * @param prevCell */ public void finishPrevMotion(LevelCell prevCell) { this.prevCell = prevCell; prevX = x; prevY = y; // model.finishingMotion = prevMotion; // model.currentMotion = newMotion; if (model.finishingMotion.getChildMotion().isFinishing()) { finishingState = true; switch(model.finishingMotion.getChildMotion().getType()) { case MAGNET: activeSprite = sprites.getSprite("postmagnet"); // activeSprite.changeSet(17); break; case STICK_LEFT: activeSprite = sprites.getSprite("poststickleft"); // activeSprite.changeSet(30); break; case STICK_RIGHT: activeSprite = sprites.getSprite("poststickright"); // activeSprite.changeSet(33); break; case FLY_LEFT: // skip finishing fall down after FLY if finish because wall if(model.currentMotion.getType() == MotionType.JUMP_LEFT_WALL || model.currentMotion.getType() == MotionType.STICK_LEFT || model.currentMotion.getType() == MotionType.FLY_RIGHT) { finishingState = false; } else { activeSprite = sprites.getSprite("fallfly"); activeSprite.changeSet(0); // activeSprite.changeSet(26); } break; case FLY_RIGHT: // skip finishing fall down after FLY if finish because wall if(model.currentMotion.getType() == MotionType.JUMP_RIGHT_WALL || model.currentMotion.getType() == MotionType.STICK_RIGHT || model.currentMotion.getType() == MotionType.FLY_LEFT) { finishingState = false; } else { activeSprite = sprites.getSprite("fallfly"); activeSprite.changeSet(0); // activeSprite.changeSet(26); } break; default: break; } } else { finishingState = false; } } /** * Begins main animation, after finish/start animations became complete */ public void switchToCurrentMotion() { pickActiveSprite(model.currentMotion.getType()); MotionType mt = model.currentMotion.getType(); int curStage = model.currentMotion.getStage(); MotionType prevMt = model.finishingMotion.getChildMotion().getType(); // if(prevMt == MotionType.TP_LEFT || prevMt == MotionType.TP_RIGHT) { // prevMt = finishingMotion.getChildMotion().getType(); // prevStage = finishingMotion.getChildMotion().getStage(); // } // if(mt == MotionType.TP_LEFT || mt == MotionType.TP_RIGHT) { // prevMt = currentMotion.getChildMotion().getType(); // prevStage = currentMotion.getChildMotion().getStage(); // } switch (mt) { case STAY: if(prevCell.getFloor().getType() == PlatformType.GLUE){ activeSprite = sprites.getSprite("glue"); // activeSprite.changeSet(0); } else if(prevMt == MotionType.THROW_LEFT || prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } else if(prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } else { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } break; case FALL: if(Math.random() > 0.5) { activeSprite = sprites.getSprite("fall"); // activeSprite.changeSet(5); } else { activeSprite = sprites.getSprite("fall2"); // activeSprite.changeSet(6); } break; case FALL_BLANSH: // if(curStage == 0) { activeSprite = sprites.getSprite("fallblansh"); // activeSprite.changeSet(1); // } break; case JUMP_LEFT: if(prevMt == MotionType.JUMP || prevMt == MotionType.TP) { activeSprite = sprites.getSprite("jumpleft"); // activeSprite.changeSet(8); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_RIGHT_WALL) { activeSprite = sprites.getSprite("startslickleft"); } else { activeSprite = sprites.getSprite("slickleft"); } } else if(prevMt == mt || prevMt == MotionType.THROW_LEFT || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("stepleft"); // activeSprite.changeSet(2); } else if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud_out_left"); } else { activeSprite = sprites.getSprite("stepleft"); // activeSprite.changeSet(3); } break; case JUMP_RIGHT: if(prevMt == MotionType.JUMP || prevMt == MotionType.TP) { activeSprite = sprites.getSprite("jumpright"); // activeSprite.changeSet(7); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_LEFT_WALL) { activeSprite = sprites.getSprite("startslickright"); } else { activeSprite = sprites.getSprite("slickright"); } } else if(prevMt == mt || prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("stepright"); // activeSprite.changeSet(0); } else if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud_out_right"); } else { activeSprite = sprites.getSprite("stepright"); // activeSprite.changeSet(1); } break; case JUMP: if(curStage != 0) { activeSprite = sprites.getSprite("jump"); // activeSprite.changeSet(4); } else { activeSprite = sprites.getSprite("prejump"); // activeSprite.changeSet(9); } break; case THROW_LEFT: if(curStage == 1) { activeSprite = sprites.getSprite("throwleft2"); // activeSprite.changeSet(24); } else if(prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.THROW_LEFT) { activeSprite = sprites.getSprite("throwleft1"); // activeSprite.changeSet(21); } else { activeSprite = sprites.getSprite("throwleft1"); // activeSprite.changeSet(20); } break; case THROW_RIGHT: if(curStage == 1) { activeSprite = sprites.getSprite("throwright2"); // activeSprite.changeSet(25); } else if(prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.THROW_RIGHT) { activeSprite = sprites.getSprite("throwright1"); // activeSprite.changeSet(19); } else { activeSprite = sprites.getSprite("throwright1"); // activeSprite.changeSet(18); } break; case JUMP_LEFT_WALL: switch(prevMt) { case JUMP: case THROW_LEFT: case FLY_LEFT: case TP: // case JUMP_RIGHT_WALL: activeSprite = sprites.getSprite("jumpleftwall"); // activeSprite.changeSet(12); break; default: if(prevCell.getFloor().getType() == PlatformType.THROW_OUT_LEFT) { activeSprite = sprites.getSprite("jumpleftwall"); // activeSprite.changeSet(12); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { activeSprite = sprites.getSprite("slickleftwall"); } else { activeSprite = sprites.getSprite("stepleftwall"); // activeSprite.changeSet(3); } break; } break; case JUMP_RIGHT_WALL: switch(prevMt) { case JUMP: case THROW_RIGHT: case FLY_RIGHT: case TP: // case JUMP_LEFT_WALL: activeSprite = sprites.getSprite("jumprightwall"); // activeSprite.changeSet(11); break; default: if(prevCell.getFloor().getType() == PlatformType.THROW_OUT_RIGHT) { activeSprite = sprites.getSprite("jumprightwall"); // activeSprite.changeSet(11); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { activeSprite = sprites.getSprite("slickrightwall"); } else { activeSprite = sprites.getSprite("steprightwall"); // activeSprite.changeSet(2); } break; } break; case BEAT_ROOF: activeSprite = sprites.getSprite("beatroof"); // activeSprite.changeSet(10); break; case MAGNET: if(curStage == 0) { activeSprite = sprites.getSprite("premagnet"); // activeSprite.changeSet(13); } else { activeSprite = sprites.getSprite("magnet"); // activeSprite.changeSet(14); } break; case FLY_LEFT: if(prevMt == mt || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("flyleft"); // activeSprite.changeSet(22); } else if(prevMt == MotionType.FLY_RIGHT || prevMt == MotionType.THROW_RIGHT) { activeSprite = sprites.getSprite("jumprightwall"); } else if(prevMt == MotionType.JUMP || prevMt == MotionType.TP || prevCell.getFloor().getType() == PlatformType.THROW_OUT_RIGHT) { activeSprite = sprites.getSprite("beginflyleft8"); // activeSprite.changeSet(11); } else { activeSprite = sprites.getSprite("beginflyleft"); // activeSprite.changeSet(7); } break; case FLY_RIGHT: if(prevMt == mt || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("flyright"); // activeSprite.changeSet(23); } else if(prevMt == MotionType.FLY_LEFT || prevMt == MotionType.THROW_LEFT ) { activeSprite = sprites.getSprite("jumpleftwall"); } else if(prevMt == MotionType.JUMP || prevMt == MotionType.TP || prevCell.getFloor().getType() == PlatformType.THROW_OUT_LEFT) { activeSprite = sprites.getSprite("beginflyright8"); // activeSprite.changeSet(12); } else { activeSprite = sprites.getSprite("beginflyright"); // activeSprite.changeSet(6); } break; case TP_LEFT: MotionType childMt = model.currentMotion.getChildMotion().getType(); int childStage = model.currentMotion.getChildMotion().getStage(); if(childMt == MotionType.JUMP_LEFT) { if(prevMt == MotionType.JUMP) { tpSprite = sprites.getTPSprite("jumpleft_tp"); // activeSprite = sprites.getSprite("jumpleft_tp"); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_RIGHT_WALL) { tpSprite = sprites.getTPSprite("startslickleft_tp"); // activeSprite = sprites.getSprite("startslickleft_tp"); } else { tpSprite = sprites.getTPSprite("slickleft_tp"); // activeSprite = sprites.getSprite("slickleft_tp"); } } else if(prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.THROW_LEFT) { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } else { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } } else if(childMt == MotionType.THROW_LEFT && childStage == 0) { if(prevMt == MotionType.THROW_LEFT || prevMt == MotionType.JUMP_LEFT) { tpSprite = sprites.getTPSprite("throwleft1_tp"); // activeSprite = sprites.getSprite("throwleft1_tp"); } else { tpSprite = sprites.getTPSprite("throwleft1_tp"); // activeSprite = sprites.getSprite("throwleft1_tp"); } } else if(childMt == MotionType.THROW_LEFT) { tpSprite = sprites.getTPSprite("throwleft2_tp"); // activeSprite = sprites.getSprite("throwleft2_tp"); } else if(childMt == MotionType.FLY_LEFT) { tpSprite = sprites.getTPSprite("flyleft_tp"); // activeSprite = sprites.getSprite("flyleft_tp"); } else { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } break; case TP_RIGHT: MotionType childMt1 = model.currentMotion.getChildMotion().getType(); int childStage1 = model.currentMotion.getChildMotion().getStage(); if(childMt1 == MotionType.JUMP_RIGHT) { if(prevMt == MotionType.JUMP) { tpSprite = sprites.getTPSprite("jumpright_tp"); // activeSprite = sprites.getSprite("jumpright_tp"); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_LEFT_WALL) { tpSprite = sprites.getTPSprite("startslickright_tp"); // activeSprite = sprites.getSprite("startslickright_tp"); } else { tpSprite = sprites.getTPSprite("slickright_tp"); // activeSprite = sprites.getSprite("slickright_tp"); } } else if(prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.THROW_RIGHT) { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } else { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } } else if(childMt1 == MotionType.THROW_RIGHT && childStage1 == 0) { if(prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.JUMP_RIGHT) { tpSprite = sprites.getTPSprite("throwright1_tp"); // activeSprite = sprites.getSprite("throwright1_tp"); } else { tpSprite = sprites.getTPSprite("throwright1_tp"); // activeSprite = sprites.getSprite("throwright1_tp"); } } else if(childMt1 == MotionType.THROW_RIGHT) { tpSprite = sprites.getTPSprite("throwright2_tp"); // activeSprite = sprites.getSprite("throwright2_tp"); } else if(childMt1 == MotionType.FLY_RIGHT) { tpSprite = sprites.getTPSprite("flyright_tp"); // activeSprite = sprites.getSprite("flyright_tp"); } else { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } break; case STICK_LEFT: if(curStage == 0) { if(prevMt == MotionType.JUMP) { - activeSprite = sprites.getSprite("prestickleft"); + activeSprite = sprites.getSprite("prestickleftjump"); } else { - activeSprite = sprites.getSprite("prestickleftjump"); + activeSprite = sprites.getSprite("prestickleft"); } // activeSprite.changeSet(28); } else { activeSprite = sprites.getSprite("stickleft"); // activeSprite.changeSet(29); } break; case STICK_RIGHT: if(curStage == 0) { if(prevMt == MotionType.JUMP) { activeSprite = sprites.getSprite("prestickrightjump"); } else { activeSprite = sprites.getSprite("prestickright"); } // activeSprite.changeSet(31); } else { activeSprite = sprites.getSprite("stickright"); // activeSprite.changeSet(32); } break; case TP: if(curStage == 0) { activeSprite = sprites.getSprite("fallinto"); // activeSprite.changeSet(34); } else { activeSprite = sprites.getSprite("flyout"); // activeSprite.changeSet(35); } break; case CLOUD_IDLE: if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud"); } else { activeSprite = sprites.getSprite("cloud_prepare"); } break; case CLOUD_LEFT: activeSprite = sprites.getSprite("cloud_left"); break; case CLOUD_RIGHT: activeSprite = sprites.getSprite("cloud_right"); break; case CLOUD_UP: activeSprite = sprites.getSprite("cloud_up"); break; case CLOUD_DOWN: activeSprite = sprites.getSprite("cloud_down"); break; default: activeSprite = sprites.getSprite("glue"); // activeSprite.changeSet(0); break; } } /** * Used to get proper bitmap for motion * @param mt */ private void pickActiveSprite(MotionType mt) { switch(mt) { case NONE: case STAY: case FALL_BLANSH: activeSprite = sprites.getSprite("fallblansh"); break; case TP_LEFT: case TP_RIGHT: // activeSprite = tpSprite; break; default: // activeSprite = sprite8; break; } } /** * Draw proper hero animation frame by center coordinates * @param canvas */ public void onDraw(Canvas canvas, boolean update) { if(!finishingState && (model.currentMotion.getType() == MotionType.TP_LEFT || model.currentMotion.getType() == MotionType.TP_RIGHT)) { tpSprite.onDraw(canvas, prevX, prevY, x, y, update); } else { activeSprite.onDraw(canvas, x, y, update); } } /** * Real motion type used to get proper hero speed on start/finish/main animations * @return */ public Motion getRealMotion() { if(finishingState) { return new Motion(MotionType.NONE); } else { return model.currentMotion; } } /** * Play loose animation */ public boolean playLoseAnimation() { // activeSprite = sprites.getSprite("fall"); activeSprite = sprites.getSprite("detonate"); activeSprite.setPlayOnce(true); if(!activeSprite.isAnimatingOrDelayed()) { return false; } return true; } /** * Play win animation * @return is sprite animating? */ public boolean playWinAnimation() { activeSprite = sprites.getSprite("fallinto"); activeSprite.setPlayOnce(true); if(!activeSprite.isAnimatingOrDelayed()) { activeSprite.goToFrame(7); return false; } return true; } }
false
true
public void switchToCurrentMotion() { pickActiveSprite(model.currentMotion.getType()); MotionType mt = model.currentMotion.getType(); int curStage = model.currentMotion.getStage(); MotionType prevMt = model.finishingMotion.getChildMotion().getType(); // if(prevMt == MotionType.TP_LEFT || prevMt == MotionType.TP_RIGHT) { // prevMt = finishingMotion.getChildMotion().getType(); // prevStage = finishingMotion.getChildMotion().getStage(); // } // if(mt == MotionType.TP_LEFT || mt == MotionType.TP_RIGHT) { // prevMt = currentMotion.getChildMotion().getType(); // prevStage = currentMotion.getChildMotion().getStage(); // } switch (mt) { case STAY: if(prevCell.getFloor().getType() == PlatformType.GLUE){ activeSprite = sprites.getSprite("glue"); // activeSprite.changeSet(0); } else if(prevMt == MotionType.THROW_LEFT || prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } else if(prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } else { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } break; case FALL: if(Math.random() > 0.5) { activeSprite = sprites.getSprite("fall"); // activeSprite.changeSet(5); } else { activeSprite = sprites.getSprite("fall2"); // activeSprite.changeSet(6); } break; case FALL_BLANSH: // if(curStage == 0) { activeSprite = sprites.getSprite("fallblansh"); // activeSprite.changeSet(1); // } break; case JUMP_LEFT: if(prevMt == MotionType.JUMP || prevMt == MotionType.TP) { activeSprite = sprites.getSprite("jumpleft"); // activeSprite.changeSet(8); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_RIGHT_WALL) { activeSprite = sprites.getSprite("startslickleft"); } else { activeSprite = sprites.getSprite("slickleft"); } } else if(prevMt == mt || prevMt == MotionType.THROW_LEFT || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("stepleft"); // activeSprite.changeSet(2); } else if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud_out_left"); } else { activeSprite = sprites.getSprite("stepleft"); // activeSprite.changeSet(3); } break; case JUMP_RIGHT: if(prevMt == MotionType.JUMP || prevMt == MotionType.TP) { activeSprite = sprites.getSprite("jumpright"); // activeSprite.changeSet(7); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_LEFT_WALL) { activeSprite = sprites.getSprite("startslickright"); } else { activeSprite = sprites.getSprite("slickright"); } } else if(prevMt == mt || prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("stepright"); // activeSprite.changeSet(0); } else if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud_out_right"); } else { activeSprite = sprites.getSprite("stepright"); // activeSprite.changeSet(1); } break; case JUMP: if(curStage != 0) { activeSprite = sprites.getSprite("jump"); // activeSprite.changeSet(4); } else { activeSprite = sprites.getSprite("prejump"); // activeSprite.changeSet(9); } break; case THROW_LEFT: if(curStage == 1) { activeSprite = sprites.getSprite("throwleft2"); // activeSprite.changeSet(24); } else if(prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.THROW_LEFT) { activeSprite = sprites.getSprite("throwleft1"); // activeSprite.changeSet(21); } else { activeSprite = sprites.getSprite("throwleft1"); // activeSprite.changeSet(20); } break; case THROW_RIGHT: if(curStage == 1) { activeSprite = sprites.getSprite("throwright2"); // activeSprite.changeSet(25); } else if(prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.THROW_RIGHT) { activeSprite = sprites.getSprite("throwright1"); // activeSprite.changeSet(19); } else { activeSprite = sprites.getSprite("throwright1"); // activeSprite.changeSet(18); } break; case JUMP_LEFT_WALL: switch(prevMt) { case JUMP: case THROW_LEFT: case FLY_LEFT: case TP: // case JUMP_RIGHT_WALL: activeSprite = sprites.getSprite("jumpleftwall"); // activeSprite.changeSet(12); break; default: if(prevCell.getFloor().getType() == PlatformType.THROW_OUT_LEFT) { activeSprite = sprites.getSprite("jumpleftwall"); // activeSprite.changeSet(12); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { activeSprite = sprites.getSprite("slickleftwall"); } else { activeSprite = sprites.getSprite("stepleftwall"); // activeSprite.changeSet(3); } break; } break; case JUMP_RIGHT_WALL: switch(prevMt) { case JUMP: case THROW_RIGHT: case FLY_RIGHT: case TP: // case JUMP_LEFT_WALL: activeSprite = sprites.getSprite("jumprightwall"); // activeSprite.changeSet(11); break; default: if(prevCell.getFloor().getType() == PlatformType.THROW_OUT_RIGHT) { activeSprite = sprites.getSprite("jumprightwall"); // activeSprite.changeSet(11); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { activeSprite = sprites.getSprite("slickrightwall"); } else { activeSprite = sprites.getSprite("steprightwall"); // activeSprite.changeSet(2); } break; } break; case BEAT_ROOF: activeSprite = sprites.getSprite("beatroof"); // activeSprite.changeSet(10); break; case MAGNET: if(curStage == 0) { activeSprite = sprites.getSprite("premagnet"); // activeSprite.changeSet(13); } else { activeSprite = sprites.getSprite("magnet"); // activeSprite.changeSet(14); } break; case FLY_LEFT: if(prevMt == mt || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("flyleft"); // activeSprite.changeSet(22); } else if(prevMt == MotionType.FLY_RIGHT || prevMt == MotionType.THROW_RIGHT) { activeSprite = sprites.getSprite("jumprightwall"); } else if(prevMt == MotionType.JUMP || prevMt == MotionType.TP || prevCell.getFloor().getType() == PlatformType.THROW_OUT_RIGHT) { activeSprite = sprites.getSprite("beginflyleft8"); // activeSprite.changeSet(11); } else { activeSprite = sprites.getSprite("beginflyleft"); // activeSprite.changeSet(7); } break; case FLY_RIGHT: if(prevMt == mt || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("flyright"); // activeSprite.changeSet(23); } else if(prevMt == MotionType.FLY_LEFT || prevMt == MotionType.THROW_LEFT ) { activeSprite = sprites.getSprite("jumpleftwall"); } else if(prevMt == MotionType.JUMP || prevMt == MotionType.TP || prevCell.getFloor().getType() == PlatformType.THROW_OUT_LEFT) { activeSprite = sprites.getSprite("beginflyright8"); // activeSprite.changeSet(12); } else { activeSprite = sprites.getSprite("beginflyright"); // activeSprite.changeSet(6); } break; case TP_LEFT: MotionType childMt = model.currentMotion.getChildMotion().getType(); int childStage = model.currentMotion.getChildMotion().getStage(); if(childMt == MotionType.JUMP_LEFT) { if(prevMt == MotionType.JUMP) { tpSprite = sprites.getTPSprite("jumpleft_tp"); // activeSprite = sprites.getSprite("jumpleft_tp"); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_RIGHT_WALL) { tpSprite = sprites.getTPSprite("startslickleft_tp"); // activeSprite = sprites.getSprite("startslickleft_tp"); } else { tpSprite = sprites.getTPSprite("slickleft_tp"); // activeSprite = sprites.getSprite("slickleft_tp"); } } else if(prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.THROW_LEFT) { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } else { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } } else if(childMt == MotionType.THROW_LEFT && childStage == 0) { if(prevMt == MotionType.THROW_LEFT || prevMt == MotionType.JUMP_LEFT) { tpSprite = sprites.getTPSprite("throwleft1_tp"); // activeSprite = sprites.getSprite("throwleft1_tp"); } else { tpSprite = sprites.getTPSprite("throwleft1_tp"); // activeSprite = sprites.getSprite("throwleft1_tp"); } } else if(childMt == MotionType.THROW_LEFT) { tpSprite = sprites.getTPSprite("throwleft2_tp"); // activeSprite = sprites.getSprite("throwleft2_tp"); } else if(childMt == MotionType.FLY_LEFT) { tpSprite = sprites.getTPSprite("flyleft_tp"); // activeSprite = sprites.getSprite("flyleft_tp"); } else { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } break; case TP_RIGHT: MotionType childMt1 = model.currentMotion.getChildMotion().getType(); int childStage1 = model.currentMotion.getChildMotion().getStage(); if(childMt1 == MotionType.JUMP_RIGHT) { if(prevMt == MotionType.JUMP) { tpSprite = sprites.getTPSprite("jumpright_tp"); // activeSprite = sprites.getSprite("jumpright_tp"); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_LEFT_WALL) { tpSprite = sprites.getTPSprite("startslickright_tp"); // activeSprite = sprites.getSprite("startslickright_tp"); } else { tpSprite = sprites.getTPSprite("slickright_tp"); // activeSprite = sprites.getSprite("slickright_tp"); } } else if(prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.THROW_RIGHT) { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } else { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } } else if(childMt1 == MotionType.THROW_RIGHT && childStage1 == 0) { if(prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.JUMP_RIGHT) { tpSprite = sprites.getTPSprite("throwright1_tp"); // activeSprite = sprites.getSprite("throwright1_tp"); } else { tpSprite = sprites.getTPSprite("throwright1_tp"); // activeSprite = sprites.getSprite("throwright1_tp"); } } else if(childMt1 == MotionType.THROW_RIGHT) { tpSprite = sprites.getTPSprite("throwright2_tp"); // activeSprite = sprites.getSprite("throwright2_tp"); } else if(childMt1 == MotionType.FLY_RIGHT) { tpSprite = sprites.getTPSprite("flyright_tp"); // activeSprite = sprites.getSprite("flyright_tp"); } else { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } break; case STICK_LEFT: if(curStage == 0) { if(prevMt == MotionType.JUMP) { activeSprite = sprites.getSprite("prestickleft"); } else { activeSprite = sprites.getSprite("prestickleftjump"); } // activeSprite.changeSet(28); } else { activeSprite = sprites.getSprite("stickleft"); // activeSprite.changeSet(29); } break; case STICK_RIGHT: if(curStage == 0) { if(prevMt == MotionType.JUMP) { activeSprite = sprites.getSprite("prestickrightjump"); } else { activeSprite = sprites.getSprite("prestickright"); } // activeSprite.changeSet(31); } else { activeSprite = sprites.getSprite("stickright"); // activeSprite.changeSet(32); } break; case TP: if(curStage == 0) { activeSprite = sprites.getSprite("fallinto"); // activeSprite.changeSet(34); } else { activeSprite = sprites.getSprite("flyout"); // activeSprite.changeSet(35); } break; case CLOUD_IDLE: if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud"); } else { activeSprite = sprites.getSprite("cloud_prepare"); } break; case CLOUD_LEFT: activeSprite = sprites.getSprite("cloud_left"); break; case CLOUD_RIGHT: activeSprite = sprites.getSprite("cloud_right"); break; case CLOUD_UP: activeSprite = sprites.getSprite("cloud_up"); break; case CLOUD_DOWN: activeSprite = sprites.getSprite("cloud_down"); break; default: activeSprite = sprites.getSprite("glue"); // activeSprite.changeSet(0); break; } }
public void switchToCurrentMotion() { pickActiveSprite(model.currentMotion.getType()); MotionType mt = model.currentMotion.getType(); int curStage = model.currentMotion.getStage(); MotionType prevMt = model.finishingMotion.getChildMotion().getType(); // if(prevMt == MotionType.TP_LEFT || prevMt == MotionType.TP_RIGHT) { // prevMt = finishingMotion.getChildMotion().getType(); // prevStage = finishingMotion.getChildMotion().getStage(); // } // if(mt == MotionType.TP_LEFT || mt == MotionType.TP_RIGHT) { // prevMt = currentMotion.getChildMotion().getType(); // prevStage = currentMotion.getChildMotion().getStage(); // } switch (mt) { case STAY: if(prevCell.getFloor().getType() == PlatformType.GLUE){ activeSprite = sprites.getSprite("glue"); // activeSprite.changeSet(0); } else if(prevMt == MotionType.THROW_LEFT || prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } else if(prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } else { activeSprite = sprites.getSprite("stay"); // activeSprite.changeSet(0); } break; case FALL: if(Math.random() > 0.5) { activeSprite = sprites.getSprite("fall"); // activeSprite.changeSet(5); } else { activeSprite = sprites.getSprite("fall2"); // activeSprite.changeSet(6); } break; case FALL_BLANSH: // if(curStage == 0) { activeSprite = sprites.getSprite("fallblansh"); // activeSprite.changeSet(1); // } break; case JUMP_LEFT: if(prevMt == MotionType.JUMP || prevMt == MotionType.TP) { activeSprite = sprites.getSprite("jumpleft"); // activeSprite.changeSet(8); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_RIGHT_WALL) { activeSprite = sprites.getSprite("startslickleft"); } else { activeSprite = sprites.getSprite("slickleft"); } } else if(prevMt == mt || prevMt == MotionType.THROW_LEFT || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("stepleft"); // activeSprite.changeSet(2); } else if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud_out_left"); } else { activeSprite = sprites.getSprite("stepleft"); // activeSprite.changeSet(3); } break; case JUMP_RIGHT: if(prevMt == MotionType.JUMP || prevMt == MotionType.TP) { activeSprite = sprites.getSprite("jumpright"); // activeSprite.changeSet(7); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_LEFT_WALL) { activeSprite = sprites.getSprite("startslickright"); } else { activeSprite = sprites.getSprite("slickright"); } } else if(prevMt == mt || prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("stepright"); // activeSprite.changeSet(0); } else if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud_out_right"); } else { activeSprite = sprites.getSprite("stepright"); // activeSprite.changeSet(1); } break; case JUMP: if(curStage != 0) { activeSprite = sprites.getSprite("jump"); // activeSprite.changeSet(4); } else { activeSprite = sprites.getSprite("prejump"); // activeSprite.changeSet(9); } break; case THROW_LEFT: if(curStage == 1) { activeSprite = sprites.getSprite("throwleft2"); // activeSprite.changeSet(24); } else if(prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.THROW_LEFT) { activeSprite = sprites.getSprite("throwleft1"); // activeSprite.changeSet(21); } else { activeSprite = sprites.getSprite("throwleft1"); // activeSprite.changeSet(20); } break; case THROW_RIGHT: if(curStage == 1) { activeSprite = sprites.getSprite("throwright2"); // activeSprite.changeSet(25); } else if(prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.THROW_RIGHT) { activeSprite = sprites.getSprite("throwright1"); // activeSprite.changeSet(19); } else { activeSprite = sprites.getSprite("throwright1"); // activeSprite.changeSet(18); } break; case JUMP_LEFT_WALL: switch(prevMt) { case JUMP: case THROW_LEFT: case FLY_LEFT: case TP: // case JUMP_RIGHT_WALL: activeSprite = sprites.getSprite("jumpleftwall"); // activeSprite.changeSet(12); break; default: if(prevCell.getFloor().getType() == PlatformType.THROW_OUT_LEFT) { activeSprite = sprites.getSprite("jumpleftwall"); // activeSprite.changeSet(12); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { activeSprite = sprites.getSprite("slickleftwall"); } else { activeSprite = sprites.getSprite("stepleftwall"); // activeSprite.changeSet(3); } break; } break; case JUMP_RIGHT_WALL: switch(prevMt) { case JUMP: case THROW_RIGHT: case FLY_RIGHT: case TP: // case JUMP_LEFT_WALL: activeSprite = sprites.getSprite("jumprightwall"); // activeSprite.changeSet(11); break; default: if(prevCell.getFloor().getType() == PlatformType.THROW_OUT_RIGHT) { activeSprite = sprites.getSprite("jumprightwall"); // activeSprite.changeSet(11); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { activeSprite = sprites.getSprite("slickrightwall"); } else { activeSprite = sprites.getSprite("steprightwall"); // activeSprite.changeSet(2); } break; } break; case BEAT_ROOF: activeSprite = sprites.getSprite("beatroof"); // activeSprite.changeSet(10); break; case MAGNET: if(curStage == 0) { activeSprite = sprites.getSprite("premagnet"); // activeSprite.changeSet(13); } else { activeSprite = sprites.getSprite("magnet"); // activeSprite.changeSet(14); } break; case FLY_LEFT: if(prevMt == mt || prevMt == MotionType.TP_LEFT) { activeSprite = sprites.getSprite("flyleft"); // activeSprite.changeSet(22); } else if(prevMt == MotionType.FLY_RIGHT || prevMt == MotionType.THROW_RIGHT) { activeSprite = sprites.getSprite("jumprightwall"); } else if(prevMt == MotionType.JUMP || prevMt == MotionType.TP || prevCell.getFloor().getType() == PlatformType.THROW_OUT_RIGHT) { activeSprite = sprites.getSprite("beginflyleft8"); // activeSprite.changeSet(11); } else { activeSprite = sprites.getSprite("beginflyleft"); // activeSprite.changeSet(7); } break; case FLY_RIGHT: if(prevMt == mt || prevMt == MotionType.TP_RIGHT) { activeSprite = sprites.getSprite("flyright"); // activeSprite.changeSet(23); } else if(prevMt == MotionType.FLY_LEFT || prevMt == MotionType.THROW_LEFT ) { activeSprite = sprites.getSprite("jumpleftwall"); } else if(prevMt == MotionType.JUMP || prevMt == MotionType.TP || prevCell.getFloor().getType() == PlatformType.THROW_OUT_LEFT) { activeSprite = sprites.getSprite("beginflyright8"); // activeSprite.changeSet(12); } else { activeSprite = sprites.getSprite("beginflyright"); // activeSprite.changeSet(6); } break; case TP_LEFT: MotionType childMt = model.currentMotion.getChildMotion().getType(); int childStage = model.currentMotion.getChildMotion().getStage(); if(childMt == MotionType.JUMP_LEFT) { if(prevMt == MotionType.JUMP) { tpSprite = sprites.getTPSprite("jumpleft_tp"); // activeSprite = sprites.getSprite("jumpleft_tp"); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_RIGHT_WALL) { tpSprite = sprites.getTPSprite("startslickleft_tp"); // activeSprite = sprites.getSprite("startslickleft_tp"); } else { tpSprite = sprites.getTPSprite("slickleft_tp"); // activeSprite = sprites.getSprite("slickleft_tp"); } } else if(prevMt == MotionType.JUMP_LEFT || prevMt == MotionType.THROW_LEFT) { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } else { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } } else if(childMt == MotionType.THROW_LEFT && childStage == 0) { if(prevMt == MotionType.THROW_LEFT || prevMt == MotionType.JUMP_LEFT) { tpSprite = sprites.getTPSprite("throwleft1_tp"); // activeSprite = sprites.getSprite("throwleft1_tp"); } else { tpSprite = sprites.getTPSprite("throwleft1_tp"); // activeSprite = sprites.getSprite("throwleft1_tp"); } } else if(childMt == MotionType.THROW_LEFT) { tpSprite = sprites.getTPSprite("throwleft2_tp"); // activeSprite = sprites.getSprite("throwleft2_tp"); } else if(childMt == MotionType.FLY_LEFT) { tpSprite = sprites.getTPSprite("flyleft_tp"); // activeSprite = sprites.getSprite("flyleft_tp"); } else { tpSprite = sprites.getTPSprite("stepleft_tp"); // activeSprite = sprites.getSprite("stepleft_tp"); } break; case TP_RIGHT: MotionType childMt1 = model.currentMotion.getChildMotion().getType(); int childStage1 = model.currentMotion.getChildMotion().getStage(); if(childMt1 == MotionType.JUMP_RIGHT) { if(prevMt == MotionType.JUMP) { tpSprite = sprites.getTPSprite("jumpright_tp"); // activeSprite = sprites.getSprite("jumpright_tp"); } else if(prevCell.getFloor().getType() == PlatformType.SLICK) { if(prevMt != mt && prevMt != MotionType.JUMP_LEFT_WALL) { tpSprite = sprites.getTPSprite("startslickright_tp"); // activeSprite = sprites.getSprite("startslickright_tp"); } else { tpSprite = sprites.getTPSprite("slickright_tp"); // activeSprite = sprites.getSprite("slickright_tp"); } } else if(prevMt == MotionType.JUMP_RIGHT || prevMt == MotionType.THROW_RIGHT) { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } else { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } } else if(childMt1 == MotionType.THROW_RIGHT && childStage1 == 0) { if(prevMt == MotionType.THROW_RIGHT || prevMt == MotionType.JUMP_RIGHT) { tpSprite = sprites.getTPSprite("throwright1_tp"); // activeSprite = sprites.getSprite("throwright1_tp"); } else { tpSprite = sprites.getTPSprite("throwright1_tp"); // activeSprite = sprites.getSprite("throwright1_tp"); } } else if(childMt1 == MotionType.THROW_RIGHT) { tpSprite = sprites.getTPSprite("throwright2_tp"); // activeSprite = sprites.getSprite("throwright2_tp"); } else if(childMt1 == MotionType.FLY_RIGHT) { tpSprite = sprites.getTPSprite("flyright_tp"); // activeSprite = sprites.getSprite("flyright_tp"); } else { tpSprite = sprites.getTPSprite("stepright_tp"); // activeSprite = sprites.getSprite("stepright_tp"); } break; case STICK_LEFT: if(curStage == 0) { if(prevMt == MotionType.JUMP) { activeSprite = sprites.getSprite("prestickleftjump"); } else { activeSprite = sprites.getSprite("prestickleft"); } // activeSprite.changeSet(28); } else { activeSprite = sprites.getSprite("stickleft"); // activeSprite.changeSet(29); } break; case STICK_RIGHT: if(curStage == 0) { if(prevMt == MotionType.JUMP) { activeSprite = sprites.getSprite("prestickrightjump"); } else { activeSprite = sprites.getSprite("prestickright"); } // activeSprite.changeSet(31); } else { activeSprite = sprites.getSprite("stickright"); // activeSprite.changeSet(32); } break; case TP: if(curStage == 0) { activeSprite = sprites.getSprite("fallinto"); // activeSprite.changeSet(34); } else { activeSprite = sprites.getSprite("flyout"); // activeSprite.changeSet(35); } break; case CLOUD_IDLE: if(prevMt.isCLOUD()) { activeSprite = sprites.getSprite("cloud"); } else { activeSprite = sprites.getSprite("cloud_prepare"); } break; case CLOUD_LEFT: activeSprite = sprites.getSprite("cloud_left"); break; case CLOUD_RIGHT: activeSprite = sprites.getSprite("cloud_right"); break; case CLOUD_UP: activeSprite = sprites.getSprite("cloud_up"); break; case CLOUD_DOWN: activeSprite = sprites.getSprite("cloud_down"); break; default: activeSprite = sprites.getSprite("glue"); // activeSprite.changeSet(0); break; } }
diff --git a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java index 87171543d..6c938172a 100644 --- a/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java +++ b/src/contributions/resources/data-repo-sitetree/src/java/org/wyona/yanel/impl/resources/navigation/DataRepoSitetreeResource.java @@ -1,192 +1,192 @@ /* * Copyright 2011 Wyona */ package org.wyona.yanel.impl.resources.navigation; import org.wyona.yanel.core.navigation.Node; import org.wyona.yanel.core.navigation.Sitetree; import org.wyona.yanel.impl.resources.BasicXMLResource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.apache.log4j.Logger; import java.io.InputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.Transformer; /** * Data repository site tree generator. */ public class DataRepoSitetreeResource extends BasicXMLResource { private static Logger log = Logger.getLogger(DataRepoSitetreeResource.class); /** * Get size. * @see org.wyona.yanel.core.Resource */ @Override public long getSize() throws Exception { return -1; } /** * Does resource exist? * @see org.wyona.yanel.core.Resource */ @Override public boolean exists() throws Exception { return true; } /** * Get content as XML. * @param viewId Ignored by this function. * @see org.wyona.yanel.impl.BasicXMLResource */ @Override public InputStream getContentXML(String viewId) throws Exception { Document doc = null; try { doc = org.wyona.commons.xml.XMLHelper.createDocument(null, "sitetree"); } catch (Exception e) { throw new Exception(e.getMessage(), e); } Element rootElement = doc.getDocumentElement(); getSitetreeAsXML(doc, rootElement); ByteArrayOutputStream baout = new ByteArrayOutputStream(); org.wyona.commons.xml.XMLHelper.writeDocument(doc, baout); return new ByteArrayInputStream(baout.toByteArray()); } /** * Get sitetree as XML. * @param doc The result document. * @param root The root element of the result document. */ private void getSitetreeAsXML(Document doc, Element root) throws Exception { // Get name4path parameter String name4pathParameter = "path"; if(getResourceConfigProperty("name4path-parameter") != null) { name4pathParameter = getResourceConfigProperty("name4path-parameter"); } // Get node as XML. if(getEnvironment().getRequest().getParameter(name4pathParameter) != null) { getNodeAsXML(request.getParameter(name4pathParameter), doc, root); } else { getNodeAsXML("/", doc, root); } } /** * Get either children of node as XML (show-all-subnodes=false) or whole sitetree (show-all-subnodes=true). * * @param path Path of node * @param doc The result document. * @param root The root element of the result document. */ private void getNodeAsXML(String path, Document doc, Element root) { // Should we show all subnodes? boolean showAllSubnodes = true; try { if(getResourceConfigProperty("show-all-subnodes") != null) { showAllSubnodes = Boolean.valueOf(getResourceConfigProperty("show-all-subnodes")).booleanValue(); } } catch (Exception e) { log.info("Could not get property show-all-subnodes. Falling back to default value (true)."); } String showAllSubnodesParameter = getParameterAsString("show-all-subnodes"); if(showAllSubnodesParameter != null && Boolean.valueOf(showAllSubnodesParameter).booleanValue()) { showAllSubnodes = true; } // Get nodes from repository Sitetree sitetree = getRealm().getRepoNavigation(); Node node = sitetree.getNode(getRealm(), path); // Construct XML. if(node != null) { if(node.isCollection()) { Element collectionElement = null; if(showAllSubnodes) { collectionElement = (Element) root.appendChild(doc.createElement("collection")); collectionElement.setAttribute("path", node.getPath()); collectionElement.setAttribute("name", node.getName()); Element labelElement = (Element) collectionElement.appendChild(doc.createElement("label")); labelElement.appendChild(doc.createTextNode(node.getName())); } // Get all children Node[] children = node.getChildren(); for(Node child : children) { if(child.isCollection()) { if(collectionElement == null) { Element childCollectionElement = (Element) root.appendChild(doc.createElement("collection")); - childCollectionElement.setAttribute("path", node.getPath()); - childCollectionElement.setAttribute("name", node.getName()); + childCollectionElement.setAttribute("path", child.getPath()); + childCollectionElement.setAttribute("name", child.getName()); Element labelElement = (Element) childCollectionElement.appendChild(doc.createElement("label")); - //labelElement.appendChild(doc.createTextNode(node.getName())); - labelElement.appendChild(doc.createTextNode(node.getName() + " (" + node.getLabel() + ")")); + //labelElement.appendChild(doc.createTextNode(child.getName())); + labelElement.appendChild(doc.createTextNode(child.getName() + " (" + child.getLabel() + ")")); } else { getNodeAsXML(child.getPath(), doc, collectionElement); } } else if(child.isResource()) { Element resourceElement; if (collectionElement == null) { resourceElement = (Element) root.appendChild(doc.createElement("resource")); } else { resourceElement = (Element) collectionElement.appendChild(doc.createElement("resource")); } resourceElement.setAttribute("path", child.getPath()); resourceElement.setAttribute("name", child.getName()); Element labelElement = (Element) resourceElement.appendChild(doc.createElement("label")); //labelElement.appendChild(doc.createTextNode(child.getName())); labelElement.appendChild(doc.createTextNode(child.getName() + " (" + child.getLabel() + ")")); } else { Element nothingElement = (Element) root.appendChild(doc.createElement("neither-resource-nor-collection")); nothingElement.setAttribute("path", child.getPath()); nothingElement.setAttribute("name", child.getName()); } } } else { Element resourceElement = (Element) root.appendChild(doc.createElement("resource")); resourceElement.setAttribute("path", node.getPath()); resourceElement.setAttribute("name", node.getName()); Element labelElement = (Element) resourceElement.appendChild(doc.createElement("label")); labelElement.appendChild(doc.createTextNode(node.getName())); } } else { String errorMessage = "Node is null! (For path: " + path + ")"; Element exceptionElement = (Element) root.appendChild(doc.createElement("resource")); exceptionElement.appendChild(doc.createTextNode(errorMessage)); log.error(errorMessage); } } /** * Pass transformer parameters. */ @Override protected void passTransformerParameters(Transformer transformer) throws Exception { super.passTransformerParameters(transformer); try { String resourceConfigPropertyDomain = getResourceConfigProperty("domain"); if(resourceConfigPropertyDomain != null) { transformer.setParameter("domain", resourceConfigPropertyDomain); } } catch(Exception e) { log.error("Could not get property domain. Domain will not be available within transformer chain."); log.error(e.getMessage(), e); } } }
false
true
private void getNodeAsXML(String path, Document doc, Element root) { // Should we show all subnodes? boolean showAllSubnodes = true; try { if(getResourceConfigProperty("show-all-subnodes") != null) { showAllSubnodes = Boolean.valueOf(getResourceConfigProperty("show-all-subnodes")).booleanValue(); } } catch (Exception e) { log.info("Could not get property show-all-subnodes. Falling back to default value (true)."); } String showAllSubnodesParameter = getParameterAsString("show-all-subnodes"); if(showAllSubnodesParameter != null && Boolean.valueOf(showAllSubnodesParameter).booleanValue()) { showAllSubnodes = true; } // Get nodes from repository Sitetree sitetree = getRealm().getRepoNavigation(); Node node = sitetree.getNode(getRealm(), path); // Construct XML. if(node != null) { if(node.isCollection()) { Element collectionElement = null; if(showAllSubnodes) { collectionElement = (Element) root.appendChild(doc.createElement("collection")); collectionElement.setAttribute("path", node.getPath()); collectionElement.setAttribute("name", node.getName()); Element labelElement = (Element) collectionElement.appendChild(doc.createElement("label")); labelElement.appendChild(doc.createTextNode(node.getName())); } // Get all children Node[] children = node.getChildren(); for(Node child : children) { if(child.isCollection()) { if(collectionElement == null) { Element childCollectionElement = (Element) root.appendChild(doc.createElement("collection")); childCollectionElement.setAttribute("path", node.getPath()); childCollectionElement.setAttribute("name", node.getName()); Element labelElement = (Element) childCollectionElement.appendChild(doc.createElement("label")); //labelElement.appendChild(doc.createTextNode(node.getName())); labelElement.appendChild(doc.createTextNode(node.getName() + " (" + node.getLabel() + ")")); } else { getNodeAsXML(child.getPath(), doc, collectionElement); } } else if(child.isResource()) { Element resourceElement; if (collectionElement == null) { resourceElement = (Element) root.appendChild(doc.createElement("resource")); } else { resourceElement = (Element) collectionElement.appendChild(doc.createElement("resource")); } resourceElement.setAttribute("path", child.getPath()); resourceElement.setAttribute("name", child.getName()); Element labelElement = (Element) resourceElement.appendChild(doc.createElement("label")); //labelElement.appendChild(doc.createTextNode(child.getName())); labelElement.appendChild(doc.createTextNode(child.getName() + " (" + child.getLabel() + ")")); } else { Element nothingElement = (Element) root.appendChild(doc.createElement("neither-resource-nor-collection")); nothingElement.setAttribute("path", child.getPath()); nothingElement.setAttribute("name", child.getName()); } } } else { Element resourceElement = (Element) root.appendChild(doc.createElement("resource")); resourceElement.setAttribute("path", node.getPath()); resourceElement.setAttribute("name", node.getName()); Element labelElement = (Element) resourceElement.appendChild(doc.createElement("label")); labelElement.appendChild(doc.createTextNode(node.getName())); } } else { String errorMessage = "Node is null! (For path: " + path + ")"; Element exceptionElement = (Element) root.appendChild(doc.createElement("resource")); exceptionElement.appendChild(doc.createTextNode(errorMessage)); log.error(errorMessage); } }
private void getNodeAsXML(String path, Document doc, Element root) { // Should we show all subnodes? boolean showAllSubnodes = true; try { if(getResourceConfigProperty("show-all-subnodes") != null) { showAllSubnodes = Boolean.valueOf(getResourceConfigProperty("show-all-subnodes")).booleanValue(); } } catch (Exception e) { log.info("Could not get property show-all-subnodes. Falling back to default value (true)."); } String showAllSubnodesParameter = getParameterAsString("show-all-subnodes"); if(showAllSubnodesParameter != null && Boolean.valueOf(showAllSubnodesParameter).booleanValue()) { showAllSubnodes = true; } // Get nodes from repository Sitetree sitetree = getRealm().getRepoNavigation(); Node node = sitetree.getNode(getRealm(), path); // Construct XML. if(node != null) { if(node.isCollection()) { Element collectionElement = null; if(showAllSubnodes) { collectionElement = (Element) root.appendChild(doc.createElement("collection")); collectionElement.setAttribute("path", node.getPath()); collectionElement.setAttribute("name", node.getName()); Element labelElement = (Element) collectionElement.appendChild(doc.createElement("label")); labelElement.appendChild(doc.createTextNode(node.getName())); } // Get all children Node[] children = node.getChildren(); for(Node child : children) { if(child.isCollection()) { if(collectionElement == null) { Element childCollectionElement = (Element) root.appendChild(doc.createElement("collection")); childCollectionElement.setAttribute("path", child.getPath()); childCollectionElement.setAttribute("name", child.getName()); Element labelElement = (Element) childCollectionElement.appendChild(doc.createElement("label")); //labelElement.appendChild(doc.createTextNode(child.getName())); labelElement.appendChild(doc.createTextNode(child.getName() + " (" + child.getLabel() + ")")); } else { getNodeAsXML(child.getPath(), doc, collectionElement); } } else if(child.isResource()) { Element resourceElement; if (collectionElement == null) { resourceElement = (Element) root.appendChild(doc.createElement("resource")); } else { resourceElement = (Element) collectionElement.appendChild(doc.createElement("resource")); } resourceElement.setAttribute("path", child.getPath()); resourceElement.setAttribute("name", child.getName()); Element labelElement = (Element) resourceElement.appendChild(doc.createElement("label")); //labelElement.appendChild(doc.createTextNode(child.getName())); labelElement.appendChild(doc.createTextNode(child.getName() + " (" + child.getLabel() + ")")); } else { Element nothingElement = (Element) root.appendChild(doc.createElement("neither-resource-nor-collection")); nothingElement.setAttribute("path", child.getPath()); nothingElement.setAttribute("name", child.getName()); } } } else { Element resourceElement = (Element) root.appendChild(doc.createElement("resource")); resourceElement.setAttribute("path", node.getPath()); resourceElement.setAttribute("name", node.getName()); Element labelElement = (Element) resourceElement.appendChild(doc.createElement("label")); labelElement.appendChild(doc.createTextNode(node.getName())); } } else { String errorMessage = "Node is null! (For path: " + path + ")"; Element exceptionElement = (Element) root.appendChild(doc.createElement("resource")); exceptionElement.appendChild(doc.createTextNode(errorMessage)); log.error(errorMessage); } }
diff --git a/org.eclipse.m2e.launching/src/org/eclipse/m2e/ui/internal/launch/MavenLaunchMainTab.java b/org.eclipse.m2e.launching/src/org/eclipse/m2e/ui/internal/launch/MavenLaunchMainTab.java index 669e04e..69852eb 100644 --- a/org.eclipse.m2e.launching/src/org/eclipse/m2e/ui/internal/launch/MavenLaunchMainTab.java +++ b/org.eclipse.m2e.launching/src/org/eclipse/m2e/ui/internal/launch/MavenLaunchMainTab.java @@ -1,787 +1,787 @@ /******************************************************************************* * Copyright (c) 2008-2010 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sonatype, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.m2e.ui.internal.launch; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.ui.AbstractLaunchConfigurationTab; import org.eclipse.debug.ui.StringVariableSelectionDialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.m2e.actions.MavenLaunchConstants; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.core.Messages; import org.eclipse.m2e.core.embedder.IMavenConfiguration; import org.eclipse.m2e.core.embedder.MavenRuntime; import org.eclipse.m2e.core.embedder.MavenRuntimeManager; import org.eclipse.m2e.core.ui.internal.MavenImages; import org.eclipse.m2e.core.ui.internal.dialogs.MavenGoalSelectionDialog; import org.eclipse.m2e.core.ui.internal.dialogs.MavenPropertyDialog; import org.eclipse.m2e.internal.launch.LaunchingUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ContainerSelectionDialog; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.externaltools.internal.model.IExternalToolConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Maven Launch dialog Main tab * * @author Dmitri Maximovich * @author Eugene Kuleshov */ @SuppressWarnings("restriction") public class MavenLaunchMainTab extends AbstractLaunchConfigurationTab implements MavenLaunchConstants { private static final Logger log = LoggerFactory.getLogger(MavenLaunchMainTab.class); public static final String ID_EXTERNAL_TOOLS_LAUNCH_GROUP = "org.eclipse.ui.externaltools.launchGroup"; //$NON-NLS-1$ private final boolean isBuilder; protected Text pomDirNameText; protected Text goalsText; protected Text goalsAutoBuildText; protected Text goalsManualBuildText; protected Text goalsCleanText; protected Text goalsAfterCleanText; protected Text profilesText; protected Table propsTable; private Button offlineButton; private Button updateSnapshotsButton; private Button debugOutputButton; private Button skipTestsButton; private Button nonRecursiveButton; private Button enableWorkspaceResolution; private Button removePropButton; private Button editPropButton; ComboViewer runtimeComboViewer; public MavenLaunchMainTab(boolean isBuilder) { this.isBuilder = isBuilder; } public Image getImage() { return MavenImages.IMG_LAUNCH_MAIN; } public void createControl(Composite parent) { Composite mainComposite = new Composite(parent, SWT.NONE); setControl(mainComposite); //PlatformUI.getWorkbench().getHelpSystem().setHelp(mainComposite, IAntUIHelpContextIds.ANT_MAIN_TAB); GridLayout layout = new GridLayout(); layout.numColumns = 5; GridData gridData = new GridData(GridData.FILL_HORIZONTAL); mainComposite.setLayout(layout); mainComposite.setLayoutData(gridData); mainComposite.setFont(parent.getFont()); class Listener implements ModifyListener, SelectionListener { public void modifyText(ModifyEvent e) { entriesChanged(); } public void widgetDefaultSelected(SelectionEvent e) { entriesChanged(); } public void widgetSelected(SelectionEvent e) { entriesChanged(); } } Listener modyfyingListener = new Listener(); Label label = new Label(mainComposite, SWT.NONE); label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 1)); label.setText(Messages.getString("launch.pomGroup")); this.pomDirNameText = new Text(mainComposite, SWT.BORDER); this.pomDirNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 5, 1)); this.pomDirNameText.addModifyListener(modyfyingListener); final Composite pomDirButtonsComposite = new Composite(mainComposite, SWT.NONE); pomDirButtonsComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 5, 1)); final GridLayout pomDirButtonsGridLayout = new GridLayout(); pomDirButtonsGridLayout.marginWidth = 0; pomDirButtonsGridLayout.marginHeight = 0; pomDirButtonsGridLayout.numColumns = 3; pomDirButtonsComposite.setLayout(pomDirButtonsGridLayout); final Button browseWorkspaceButton = new Button(pomDirButtonsComposite, SWT.NONE); browseWorkspaceButton.setText(Messages.getString("launch.browseWorkspace")); //$NON-NLS-1$ browseWorkspaceButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), // ResourcesPlugin.getWorkspace().getRoot(), false, Messages.getString("launch.choosePomDir")); //$NON-NLS-1$ dialog.showClosedProjects(false); int buttonId = dialog.open(); if(buttonId == IDialogConstants.OK_ID) { Object[] resource = dialog.getResult(); if(resource != null && resource.length > 0) { String fileLoc = VariablesPlugin.getDefault().getStringVariableManager().generateVariableExpression( "workspace_loc", ((IPath) resource[0]).toString()); //$NON-NLS-1$ pomDirNameText.setText(fileLoc); entriesChanged(); } } } }); final Button browseFilesystemButton = new Button(pomDirButtonsComposite, SWT.NONE); browseFilesystemButton.setText(Messages.getString("launch.browseFs")); //$NON-NLS-1$ browseFilesystemButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.NONE); dialog.setFilterPath(pomDirNameText.getText()); String text = dialog.open(); if(text != null) { pomDirNameText.setText(text); entriesChanged(); } } }); final Button browseVariablesButton = new Button(pomDirButtonsComposite, SWT.NONE); browseVariablesButton.setText(Messages.getString("launch.browseVariables")); //$NON-NLS-1$ browseVariablesButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { StringVariableSelectionDialog dialog = new StringVariableSelectionDialog(getShell()); dialog.open(); String variable = dialog.getVariableExpression(); if(variable != null) { pomDirNameText.insert(variable); } } }); // pom file // goals if(isBuilder) { Label autoBuildGoalsLabel = new Label(mainComposite, SWT.NONE); GridData gd_autoBuildGoalsLabel = new GridData(); gd_autoBuildGoalsLabel.verticalIndent = 7; autoBuildGoalsLabel.setLayoutData(gd_autoBuildGoalsLabel); autoBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblAutoBuildGoals); goalsAutoBuildText = new Text(mainComposite, SWT.BORDER); GridData gd_goalsAutoBuildText = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1); gd_goalsAutoBuildText.verticalIndent = 7; goalsAutoBuildText.setLayoutData(gd_goalsAutoBuildText); goalsAutoBuildText.addModifyListener(modyfyingListener); goalsAutoBuildText.addFocusListener(new GoalsFocusListener(goalsAutoBuildText)); Button goalsAutoBuildButton = new Button(mainComposite, SWT.NONE); GridData gd_goalsAutoBuildButton = new GridData(SWT.FILL, SWT.CENTER, false, false); gd_goalsAutoBuildButton.verticalIndent = 7; goalsAutoBuildButton.setLayoutData(gd_goalsAutoBuildButton); goalsAutoBuildButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnAutoBuild); goalsAutoBuildButton.addSelectionListener(new GoalSelectionAdapter(goalsAutoBuildText)); Label manualBuildGoalsLabel = new Label(mainComposite, SWT.NONE); manualBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblManualGoals); goalsManualBuildText = new Text(mainComposite, SWT.BORDER); goalsManualBuildText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsManualBuildText.addModifyListener(modyfyingListener); goalsManualBuildText.addFocusListener(new GoalsFocusListener(goalsManualBuildText)); Button goalsManualBuildButton = new Button(mainComposite, SWT.NONE); goalsManualBuildButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsManualBuildButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnManualBuild); goalsManualBuildButton.addSelectionListener(new GoalSelectionAdapter(goalsManualBuildText)); Label cleanBuildGoalsLabel = new Label(mainComposite, SWT.NONE); cleanBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblCleanBuild); goalsCleanText = new Text(mainComposite, SWT.BORDER); goalsCleanText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsCleanText.addModifyListener(modyfyingListener); goalsCleanText.addFocusListener(new GoalsFocusListener(goalsCleanText)); Button goalsCleanButton = new Button(mainComposite, SWT.NONE); goalsCleanButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsCleanButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnCleanBuild); goalsCleanButton.addSelectionListener(new GoalSelectionAdapter(goalsCleanText)); Label afterCleanGoalsLabel = new Label(mainComposite, SWT.NONE); afterCleanGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblAfterClean); goalsAfterCleanText = new Text(mainComposite, SWT.BORDER); goalsAfterCleanText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsAfterCleanText.addModifyListener(modyfyingListener); goalsAfterCleanText.addFocusListener(new GoalsFocusListener(goalsAfterCleanText)); Button goalsAfterCleanButton = new Button(mainComposite, SWT.NONE); goalsAfterCleanButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsAfterCleanButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnAfterClean); goalsAfterCleanButton.addSelectionListener(new GoalSelectionAdapter(goalsAfterCleanText)); } else { Label goalsLabel = new Label(mainComposite, SWT.NONE); GridData gd_goalsLabel = new GridData(); gd_goalsLabel.verticalIndent = 7; goalsLabel.setLayoutData(gd_goalsLabel); goalsLabel.setText(Messages.getString("launch.goalsLabel")); //$NON-NLS-1$ goalsText = new Text(mainComposite, SWT.BORDER); goalsText.setData("name", "goalsText"); //$NON-NLS-1$ //$NON-NLS-2$ GridData gd_goalsText = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1); gd_goalsText.verticalIndent = 7; goalsText.setLayoutData(gd_goalsText); goalsText.addModifyListener(modyfyingListener); goalsText.addFocusListener(new GoalsFocusListener(goalsText)); Button selectGoalsButton = new Button(mainComposite, SWT.NONE); GridData gd_selectGoalsButton = new GridData(SWT.FILL, SWT.CENTER, false, false); gd_selectGoalsButton.verticalIndent = 7; selectGoalsButton.setLayoutData(gd_selectGoalsButton); selectGoalsButton.setText(Messages.getString("launch.goals")); //$NON-NLS-1$ selectGoalsButton.addSelectionListener(new GoalSelectionAdapter(goalsText)); } Label profilesLabel = new Label(mainComposite, SWT.NONE); profilesLabel.setText(Messages.getString("launch.profilesLabel")); //$NON-NLS-1$ // profilesLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); profilesText = new Text(mainComposite, SWT.BORDER); profilesText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); profilesText.addModifyListener(modyfyingListener); new Label(mainComposite, SWT.NONE); offlineButton = new Button(mainComposite, SWT.CHECK); offlineButton.setToolTipText("-o"); //$NON-NLS-1$ GridData gd_offlineButton = new GridData(); offlineButton.setLayoutData(gd_offlineButton); offlineButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnOffline); offlineButton.addSelectionListener(modyfyingListener); updateSnapshotsButton = new Button(mainComposite, SWT.CHECK); updateSnapshotsButton.setToolTipText("-U"); //$NON-NLS-1$ updateSnapshotsButton.addSelectionListener(modyfyingListener); GridData gd_updateSnapshotsButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1); gd_updateSnapshotsButton.horizontalIndent = 10; updateSnapshotsButton.setLayoutData(gd_updateSnapshotsButton); updateSnapshotsButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnUpdateSnapshots); new Label(mainComposite, SWT.NONE); debugOutputButton = new Button(mainComposite, SWT.CHECK); debugOutputButton.setToolTipText("-X -e"); //$NON-NLS-1$ debugOutputButton.addSelectionListener(modyfyingListener); debugOutputButton.setLayoutData(new GridData()); debugOutputButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnDebugOutput); skipTestsButton = new Button(mainComposite, SWT.CHECK); skipTestsButton.setToolTipText("-Dmaven.test.skip=true"); //$NON-NLS-1$ skipTestsButton.addSelectionListener(modyfyingListener); GridData gd_skipTestsButton = new GridData(); gd_skipTestsButton.horizontalIndent = 10; skipTestsButton.setLayoutData(gd_skipTestsButton); skipTestsButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnSkipTests); nonRecursiveButton = new Button(mainComposite, SWT.CHECK); GridData gd_nonrecursiveButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); gd_nonrecursiveButton.horizontalIndent = 10; nonRecursiveButton.setLayoutData(gd_nonrecursiveButton); nonRecursiveButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnNotRecursive); nonRecursiveButton.setToolTipText("-N"); //$NON-NLS-1$ nonRecursiveButton.setData("name", "nonRecursiveButton"); //$NON-NLS-1$ //$NON-NLS-2$ nonRecursiveButton.addSelectionListener(modyfyingListener); new Label(mainComposite, SWT.NONE); enableWorkspaceResolution = new Button(mainComposite, SWT.CHECK); enableWorkspaceResolution.addSelectionListener(modyfyingListener); enableWorkspaceResolution.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1)); enableWorkspaceResolution.setData("name", "enableWorkspaceResolution"); //$NON-NLS-1$ //$NON-NLS-2$ enableWorkspaceResolution.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnResolveWorkspace); TableViewer tableViewer = new TableViewer(mainComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { TableItem[] selection = propsTable.getSelection(); if(selection.length == 1) { editProperty(selection[0].getText(0), selection[0].getText(1)); } } }); tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){ public void selectionChanged(SelectionChangedEvent event) { TableItem[] items = propsTable.getSelection(); if(items == null || items.length == 0){ editPropButton.setEnabled(false); removePropButton.setEnabled(false); } else if(items.length == 1){ editPropButton.setEnabled(true); removePropButton.setEnabled(true); } else { editPropButton.setEnabled(false); removePropButton.setEnabled(true); } } }); this.propsTable = tableViewer.getTable(); //this.tProps.setItemCount(10); this.propsTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 3)); this.propsTable.setLinesVisible(true); this.propsTable.setHeaderVisible(true); final TableColumn propColumn = new TableColumn(this.propsTable, SWT.NONE, 0); propColumn.setWidth(120); propColumn.setText(Messages.getString("launch.propName")); //$NON-NLS-1$ final TableColumn valueColumn = new TableColumn(this.propsTable, SWT.NONE, 1); valueColumn.setWidth(200); valueColumn.setText(Messages.getString("launch.propValue")); //$NON-NLS-1$ final Button addPropButton = new Button(mainComposite, SWT.NONE); addPropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); addPropButton.setText(Messages.getString("launch.propAddButton")); //$NON-NLS-1$ addPropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addProperty(); } }); editPropButton = new Button(mainComposite, SWT.NONE); editPropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); editPropButton.setText(Messages.getString("launch.propEditButton")); //$NON-NLS-1$ editPropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(propsTable.getSelectionCount() > 0) { TableItem[] selection = propsTable.getSelection(); if(selection.length == 1) { editProperty(selection[0].getText(0), selection[0].getText(1)); } } } }); editPropButton.setEnabled(false); removePropButton = new Button(mainComposite, SWT.NONE); removePropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); removePropButton.setText(Messages.getString("launch.propRemoveButton")); //$NON-NLS-1$ removePropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(propsTable.getSelectionCount() > 0) { propsTable.remove(propsTable.getSelectionIndices()); entriesChanged(); } } }); removePropButton.setEnabled(false); { Composite composite = new Composite(mainComposite, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1)); GridLayout gridLayout = new GridLayout(2, false); gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; composite.setLayout(gridLayout); Label mavenRuntimeLabel = new Label(composite, SWT.NONE); mavenRuntimeLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); mavenRuntimeLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblRuntime); runtimeComboViewer = new ComboViewer(composite, SWT.BORDER | SWT.READ_ONLY); runtimeComboViewer.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); runtimeComboViewer.setContentProvider(new IStructuredContentProvider() { public Object[] getElements(Object input) { return ((List<?>) input).toArray(); } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public void dispose() { } }); runtimeComboViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { entriesChanged(); } }); MavenRuntimeManager runtimeManager = MavenPlugin.getDefault().getMavenRuntimeManager(); runtimeComboViewer.setInput(runtimeManager.getMavenRuntimes()); runtimeComboViewer.setSelection(new StructuredSelection(runtimeManager.getDefaultRuntime())); } Button configureRuntimesButton = new Button(mainComposite, SWT.NONE); GridData gd_configureRuntimesButton = new GridData(SWT.FILL, SWT.CENTER, false, false); configureRuntimesButton.setLayoutData(gd_configureRuntimesButton); configureRuntimesButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnConfigure); configureRuntimesButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PreferencesUtil.createPreferenceDialogOn(getShell(), - "org.eclipse.m2e.preferences.MavenInstallationsPreferencePage", null, null).open(); //$NON-NLS-1$ + "org.eclipse.m2e.core.preferences.MavenInstallationsPreferencePage", null, null).open(); //$NON-NLS-1$ MavenRuntimeManager runtimeManager = MavenPlugin.getDefault().getMavenRuntimeManager(); runtimeComboViewer.setInput(runtimeManager.getMavenRuntimes()); runtimeComboViewer.setSelection(new StructuredSelection(runtimeManager.getDefaultRuntime())); } }); if(isBuilder) { goalsAutoBuildText.setFocus(); } else { goalsText.setFocus(); } } protected Shell getShell() { return super.getShell(); } void addProperty() { MavenPropertyDialog dialog = getMavenPropertyDialog(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_property_dialog_title, "", ""); //$NON-NLS-2$ //$NON-NLS-3$ if(dialog.open() == IDialogConstants.OK_ID) { TableItem item = new TableItem(propsTable, SWT.NONE); item.setText(0, dialog.getName()); item.setText(1, dialog.getValue()); entriesChanged(); } } void editProperty(String name, String value) { MavenPropertyDialog dialog = getMavenPropertyDialog(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_property_dialog_edit_title, name, value); if(dialog.open() == IDialogConstants.OK_ID) { TableItem[] item = propsTable.getSelection(); item[0].setText(0, dialog.getName()); item[0].setText(1, dialog.getValue()); entriesChanged(); } } private MavenPropertyDialog getMavenPropertyDialog(String title, String initName, String initValue) { return new MavenPropertyDialog(getShell(), title, initName, initValue, null) { protected Control createDialogArea(Composite parent) { Composite comp = (Composite) super.createDialogArea(parent); Button variablesButton = new Button(comp, SWT.PUSH); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_END); gd.horizontalSpan = 2; gd.widthHint = Math.max(convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH), // variablesButton.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); variablesButton.setLayoutData(gd); variablesButton.setFont(comp.getFont()); variablesButton.setText(Messages.getString("launch.propertyDialog.browseVariables")); //$NON-NLS-1$; variablesButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent se) { StringVariableSelectionDialog variablesDialog = new StringVariableSelectionDialog(getShell()); if(variablesDialog.open() == IDialogConstants.OK_ID) { String variable = variablesDialog.getVariableExpression(); if(variable != null) { valueText.insert(variable.trim()); } } } }); return comp; } }; } public void initializeFrom(ILaunchConfiguration configuration) { String pomDirName = getAttribute(configuration, ATTR_POM_DIR, ""); //$NON-NLS-1$ if(isBuilder && pomDirName.length()==0) { pomDirName = "${workspace_loc:/" + configuration.getFile().getProject().getName() + "}"; //$NON-NLS-1$ //$NON-NLS-2$ } this.pomDirNameText.setText(pomDirName); if(isBuilder) { this.goalsAutoBuildText.setText(getAttribute(configuration, ATTR_GOALS_AUTO_BUILD, "install")); //$NON-NLS-1$ this.goalsManualBuildText.setText(getAttribute(configuration, ATTR_GOALS_MANUAL_BUILD, "install")); //$NON-NLS-1$ this.goalsCleanText.setText(getAttribute(configuration, ATTR_GOALS_CLEAN, "clean")); //$NON-NLS-1$ this.goalsAfterCleanText.setText(getAttribute(configuration, ATTR_GOALS_AFTER_CLEAN, "install")); //$NON-NLS-1$ } else { this.goalsText.setText(getAttribute(configuration, ATTR_GOALS, "")); //$NON-NLS-1$ } this.profilesText.setText(getAttribute(configuration, ATTR_PROFILES, "")); //$NON-NLS-1$ try { MavenPlugin plugin = MavenPlugin.getDefault(); MavenRuntimeManager runtimeManager = plugin.getMavenRuntimeManager(); IMavenConfiguration mavenConfiguration = MavenPlugin.getDefault().getMavenConfiguration(); this.offlineButton.setSelection(getAttribute(configuration, ATTR_OFFLINE, mavenConfiguration.isOffline())); this.debugOutputButton.setSelection(getAttribute(configuration, ATTR_DEBUG_OUTPUT, mavenConfiguration.isDebugOutput())); this.updateSnapshotsButton.setSelection(getAttribute(configuration, ATTR_UPDATE_SNAPSHOTS, false)); this.skipTestsButton.setSelection(getAttribute(configuration, ATTR_SKIP_TESTS, false)); this.nonRecursiveButton.setSelection(getAttribute(configuration, ATTR_NON_RECURSIVE, false)); this.enableWorkspaceResolution.setSelection(getAttribute(configuration, ATTR_WORKSPACE_RESOLUTION, false)); String location = getAttribute(configuration, ATTR_RUNTIME, ""); //$NON-NLS-1$ MavenRuntime runtime = runtimeManager.getRuntime(location); if(runtime != null){ this.runtimeComboViewer.setSelection(new StructuredSelection(runtime)); } propsTable.removeAll(); @SuppressWarnings("unchecked") List<String> properties = configuration.getAttribute(ATTR_PROPERTIES, Collections.EMPTY_LIST); for(String property : properties) { int n = property.indexOf('='); String name = property; String value = ""; //$NON-NLS-1$ if(n > -1) { name = property.substring(0, n); if(n > 1) { value = property.substring(n + 1); } } TableItem item = new TableItem(propsTable, SWT.NONE); item.setText(0, name); item.setText(1, value); } } catch(CoreException ex) { // XXX should we at least log something here? } setDirty(false); } private String getAttribute(ILaunchConfiguration configuration, String name, String defaultValue) { try { return configuration.getAttribute(name, defaultValue); } catch(CoreException ex) { log.error(ex.getMessage(), ex); return defaultValue; } } private boolean getAttribute(ILaunchConfiguration configuration, String name, boolean defaultValue) { try { return configuration.getAttribute(name, defaultValue); } catch(CoreException ex) { return defaultValue; } } public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { } public void performApply(ILaunchConfigurationWorkingCopy configuration) { configuration.setAttribute(ATTR_POM_DIR, this.pomDirNameText.getText()); if(isBuilder) { configuration.setAttribute(ATTR_GOALS_AUTO_BUILD, goalsAutoBuildText.getText()); configuration.setAttribute(ATTR_GOALS_MANUAL_BUILD, this.goalsManualBuildText.getText()); configuration.setAttribute(ATTR_GOALS_CLEAN, this.goalsCleanText.getText()); configuration.setAttribute(ATTR_GOALS_AFTER_CLEAN, this.goalsAfterCleanText.getText()); StringBuffer sb = new StringBuffer(); if(goalsAfterCleanText.getText().trim().length()>0) { sb.append(IExternalToolConstants.BUILD_TYPE_FULL).append(','); } if(goalsManualBuildText.getText().trim().length()>0) { sb.append(IExternalToolConstants.BUILD_TYPE_INCREMENTAL).append(','); } if(goalsAutoBuildText.getText().trim().length()>0) { sb.append(IExternalToolConstants.BUILD_TYPE_AUTO).append(','); } if(goalsCleanText.getText().trim().length()>0) { sb.append(IExternalToolConstants.BUILD_TYPE_CLEAN); } configuration.setAttribute(IExternalToolConstants.ATTR_RUN_BUILD_KINDS, sb.toString()); } else { configuration.setAttribute(ATTR_GOALS, this.goalsText.getText()); } configuration.setAttribute(ATTR_PROFILES, this.profilesText.getText()); configuration.setAttribute(ATTR_OFFLINE, this.offlineButton.getSelection()); configuration.setAttribute(ATTR_UPDATE_SNAPSHOTS, this.updateSnapshotsButton.getSelection()); configuration.setAttribute(ATTR_SKIP_TESTS, this.skipTestsButton.getSelection()); configuration.setAttribute(ATTR_NON_RECURSIVE, this.nonRecursiveButton.getSelection()); configuration.setAttribute(ATTR_WORKSPACE_RESOLUTION, this.enableWorkspaceResolution.getSelection()); configuration.setAttribute(ATTR_DEBUG_OUTPUT, this.debugOutputButton.getSelection()); IStructuredSelection selection = (IStructuredSelection) runtimeComboViewer.getSelection(); MavenRuntime runtime = (MavenRuntime) selection.getFirstElement(); configuration.setAttribute(ATTR_RUNTIME, runtime.getLocation()); // store as String in "param=value" format List<String> properties = new ArrayList<String>(); for(TableItem item : this.propsTable.getItems()) { String p = item.getText(0); String v = item.getText(1); if(p != null && p.trim().length() > 0) { String prop = p.trim() + "=" + (v == null ? "" : v); //$NON-NLS-1$ //$NON-NLS-2$ properties.add(prop); } } configuration.setAttribute(ATTR_PROPERTIES, properties); } public String getName() { return Messages.getString("launch.mainTabName"); //$NON-NLS-1$ } public boolean isValid(ILaunchConfiguration launchConfig) { setErrorMessage(null); String pomFileName = this.pomDirNameText.getText(); if(pomFileName == null || pomFileName.trim().length() == 0) { setErrorMessage(Messages.getString("launch.pomDirectoryEmpty")); return false; } if(!isDirectoryExist(pomFileName)) { setErrorMessage(Messages.getString("launch.pomDirectoryDoesntExist")); return false; } return true; } protected boolean isDirectoryExist(String name) { if(name == null || name.trim().length() == 0) { return false; } String dirName = LaunchingUtils.substituteVar(name); if(dirName == null) { return false; } File pomDir = new File(dirName); if(!pomDir.exists()) { return false; } if(!pomDir.isDirectory()) { return false; } return true; } void entriesChanged() { setDirty(true); updateLaunchConfigurationDialog(); } private static final class GoalsFocusListener extends FocusAdapter { private Text text; public GoalsFocusListener(Text text) { this.text = text; } public void focusGained(FocusEvent e) { super.focusGained(e); text.setData("focus"); //$NON-NLS-1$ } } private final class GoalSelectionAdapter extends SelectionAdapter { private Text text; public GoalSelectionAdapter(Text text) { this.text = text; } public void widgetSelected(SelectionEvent e) { // String fileName = Util.substituteVar(fPomDirName.getText()); // if(!isDirectoryExist(fileName)) { // MessageDialog.openError(getShell(), Messages.getString("launch.errorPomMissing"), // Messages.getString("launch.errorSelectPom")); //$NON-NLS-1$ //$NON-NLS-2$ // return; // } MavenGoalSelectionDialog dialog = new MavenGoalSelectionDialog(getShell()); int rc = dialog.open(); if(rc == IDialogConstants.OK_ID) { text.insert(""); // clear selected text //$NON-NLS-1$ String txt = text.getText(); int len = txt.length(); int pos = text.getCaretPosition(); StringBuffer sb = new StringBuffer(); if((pos > 0 && txt.charAt(pos - 1) != ' ')) { sb.append(' '); } String sep = ""; //$NON-NLS-1$ Object[] o = dialog.getResult(); for(int i = 0; i < o.length; i++ ) { if(o[i] instanceof MavenGoalSelectionDialog.Entry) { if(dialog.isQualifiedName()) { sb.append(sep).append(((MavenGoalSelectionDialog.Entry) o[i]).getQualifiedName()); } else { sb.append(sep).append(((MavenGoalSelectionDialog.Entry) o[i]).getName()); } } sep = " "; //$NON-NLS-1$ } if(pos < len && txt.charAt(pos) != ' ') { sb.append(' '); } text.insert(sb.toString()); text.setFocus(); entriesChanged(); } } } }
true
true
public void createControl(Composite parent) { Composite mainComposite = new Composite(parent, SWT.NONE); setControl(mainComposite); //PlatformUI.getWorkbench().getHelpSystem().setHelp(mainComposite, IAntUIHelpContextIds.ANT_MAIN_TAB); GridLayout layout = new GridLayout(); layout.numColumns = 5; GridData gridData = new GridData(GridData.FILL_HORIZONTAL); mainComposite.setLayout(layout); mainComposite.setLayoutData(gridData); mainComposite.setFont(parent.getFont()); class Listener implements ModifyListener, SelectionListener { public void modifyText(ModifyEvent e) { entriesChanged(); } public void widgetDefaultSelected(SelectionEvent e) { entriesChanged(); } public void widgetSelected(SelectionEvent e) { entriesChanged(); } } Listener modyfyingListener = new Listener(); Label label = new Label(mainComposite, SWT.NONE); label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 1)); label.setText(Messages.getString("launch.pomGroup")); this.pomDirNameText = new Text(mainComposite, SWT.BORDER); this.pomDirNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 5, 1)); this.pomDirNameText.addModifyListener(modyfyingListener); final Composite pomDirButtonsComposite = new Composite(mainComposite, SWT.NONE); pomDirButtonsComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 5, 1)); final GridLayout pomDirButtonsGridLayout = new GridLayout(); pomDirButtonsGridLayout.marginWidth = 0; pomDirButtonsGridLayout.marginHeight = 0; pomDirButtonsGridLayout.numColumns = 3; pomDirButtonsComposite.setLayout(pomDirButtonsGridLayout); final Button browseWorkspaceButton = new Button(pomDirButtonsComposite, SWT.NONE); browseWorkspaceButton.setText(Messages.getString("launch.browseWorkspace")); //$NON-NLS-1$ browseWorkspaceButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), // ResourcesPlugin.getWorkspace().getRoot(), false, Messages.getString("launch.choosePomDir")); //$NON-NLS-1$ dialog.showClosedProjects(false); int buttonId = dialog.open(); if(buttonId == IDialogConstants.OK_ID) { Object[] resource = dialog.getResult(); if(resource != null && resource.length > 0) { String fileLoc = VariablesPlugin.getDefault().getStringVariableManager().generateVariableExpression( "workspace_loc", ((IPath) resource[0]).toString()); //$NON-NLS-1$ pomDirNameText.setText(fileLoc); entriesChanged(); } } } }); final Button browseFilesystemButton = new Button(pomDirButtonsComposite, SWT.NONE); browseFilesystemButton.setText(Messages.getString("launch.browseFs")); //$NON-NLS-1$ browseFilesystemButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.NONE); dialog.setFilterPath(pomDirNameText.getText()); String text = dialog.open(); if(text != null) { pomDirNameText.setText(text); entriesChanged(); } } }); final Button browseVariablesButton = new Button(pomDirButtonsComposite, SWT.NONE); browseVariablesButton.setText(Messages.getString("launch.browseVariables")); //$NON-NLS-1$ browseVariablesButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { StringVariableSelectionDialog dialog = new StringVariableSelectionDialog(getShell()); dialog.open(); String variable = dialog.getVariableExpression(); if(variable != null) { pomDirNameText.insert(variable); } } }); // pom file // goals if(isBuilder) { Label autoBuildGoalsLabel = new Label(mainComposite, SWT.NONE); GridData gd_autoBuildGoalsLabel = new GridData(); gd_autoBuildGoalsLabel.verticalIndent = 7; autoBuildGoalsLabel.setLayoutData(gd_autoBuildGoalsLabel); autoBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblAutoBuildGoals); goalsAutoBuildText = new Text(mainComposite, SWT.BORDER); GridData gd_goalsAutoBuildText = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1); gd_goalsAutoBuildText.verticalIndent = 7; goalsAutoBuildText.setLayoutData(gd_goalsAutoBuildText); goalsAutoBuildText.addModifyListener(modyfyingListener); goalsAutoBuildText.addFocusListener(new GoalsFocusListener(goalsAutoBuildText)); Button goalsAutoBuildButton = new Button(mainComposite, SWT.NONE); GridData gd_goalsAutoBuildButton = new GridData(SWT.FILL, SWT.CENTER, false, false); gd_goalsAutoBuildButton.verticalIndent = 7; goalsAutoBuildButton.setLayoutData(gd_goalsAutoBuildButton); goalsAutoBuildButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnAutoBuild); goalsAutoBuildButton.addSelectionListener(new GoalSelectionAdapter(goalsAutoBuildText)); Label manualBuildGoalsLabel = new Label(mainComposite, SWT.NONE); manualBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblManualGoals); goalsManualBuildText = new Text(mainComposite, SWT.BORDER); goalsManualBuildText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsManualBuildText.addModifyListener(modyfyingListener); goalsManualBuildText.addFocusListener(new GoalsFocusListener(goalsManualBuildText)); Button goalsManualBuildButton = new Button(mainComposite, SWT.NONE); goalsManualBuildButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsManualBuildButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnManualBuild); goalsManualBuildButton.addSelectionListener(new GoalSelectionAdapter(goalsManualBuildText)); Label cleanBuildGoalsLabel = new Label(mainComposite, SWT.NONE); cleanBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblCleanBuild); goalsCleanText = new Text(mainComposite, SWT.BORDER); goalsCleanText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsCleanText.addModifyListener(modyfyingListener); goalsCleanText.addFocusListener(new GoalsFocusListener(goalsCleanText)); Button goalsCleanButton = new Button(mainComposite, SWT.NONE); goalsCleanButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsCleanButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnCleanBuild); goalsCleanButton.addSelectionListener(new GoalSelectionAdapter(goalsCleanText)); Label afterCleanGoalsLabel = new Label(mainComposite, SWT.NONE); afterCleanGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblAfterClean); goalsAfterCleanText = new Text(mainComposite, SWT.BORDER); goalsAfterCleanText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsAfterCleanText.addModifyListener(modyfyingListener); goalsAfterCleanText.addFocusListener(new GoalsFocusListener(goalsAfterCleanText)); Button goalsAfterCleanButton = new Button(mainComposite, SWT.NONE); goalsAfterCleanButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsAfterCleanButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnAfterClean); goalsAfterCleanButton.addSelectionListener(new GoalSelectionAdapter(goalsAfterCleanText)); } else { Label goalsLabel = new Label(mainComposite, SWT.NONE); GridData gd_goalsLabel = new GridData(); gd_goalsLabel.verticalIndent = 7; goalsLabel.setLayoutData(gd_goalsLabel); goalsLabel.setText(Messages.getString("launch.goalsLabel")); //$NON-NLS-1$ goalsText = new Text(mainComposite, SWT.BORDER); goalsText.setData("name", "goalsText"); //$NON-NLS-1$ //$NON-NLS-2$ GridData gd_goalsText = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1); gd_goalsText.verticalIndent = 7; goalsText.setLayoutData(gd_goalsText); goalsText.addModifyListener(modyfyingListener); goalsText.addFocusListener(new GoalsFocusListener(goalsText)); Button selectGoalsButton = new Button(mainComposite, SWT.NONE); GridData gd_selectGoalsButton = new GridData(SWT.FILL, SWT.CENTER, false, false); gd_selectGoalsButton.verticalIndent = 7; selectGoalsButton.setLayoutData(gd_selectGoalsButton); selectGoalsButton.setText(Messages.getString("launch.goals")); //$NON-NLS-1$ selectGoalsButton.addSelectionListener(new GoalSelectionAdapter(goalsText)); } Label profilesLabel = new Label(mainComposite, SWT.NONE); profilesLabel.setText(Messages.getString("launch.profilesLabel")); //$NON-NLS-1$ // profilesLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); profilesText = new Text(mainComposite, SWT.BORDER); profilesText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); profilesText.addModifyListener(modyfyingListener); new Label(mainComposite, SWT.NONE); offlineButton = new Button(mainComposite, SWT.CHECK); offlineButton.setToolTipText("-o"); //$NON-NLS-1$ GridData gd_offlineButton = new GridData(); offlineButton.setLayoutData(gd_offlineButton); offlineButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnOffline); offlineButton.addSelectionListener(modyfyingListener); updateSnapshotsButton = new Button(mainComposite, SWT.CHECK); updateSnapshotsButton.setToolTipText("-U"); //$NON-NLS-1$ updateSnapshotsButton.addSelectionListener(modyfyingListener); GridData gd_updateSnapshotsButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1); gd_updateSnapshotsButton.horizontalIndent = 10; updateSnapshotsButton.setLayoutData(gd_updateSnapshotsButton); updateSnapshotsButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnUpdateSnapshots); new Label(mainComposite, SWT.NONE); debugOutputButton = new Button(mainComposite, SWT.CHECK); debugOutputButton.setToolTipText("-X -e"); //$NON-NLS-1$ debugOutputButton.addSelectionListener(modyfyingListener); debugOutputButton.setLayoutData(new GridData()); debugOutputButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnDebugOutput); skipTestsButton = new Button(mainComposite, SWT.CHECK); skipTestsButton.setToolTipText("-Dmaven.test.skip=true"); //$NON-NLS-1$ skipTestsButton.addSelectionListener(modyfyingListener); GridData gd_skipTestsButton = new GridData(); gd_skipTestsButton.horizontalIndent = 10; skipTestsButton.setLayoutData(gd_skipTestsButton); skipTestsButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnSkipTests); nonRecursiveButton = new Button(mainComposite, SWT.CHECK); GridData gd_nonrecursiveButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); gd_nonrecursiveButton.horizontalIndent = 10; nonRecursiveButton.setLayoutData(gd_nonrecursiveButton); nonRecursiveButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnNotRecursive); nonRecursiveButton.setToolTipText("-N"); //$NON-NLS-1$ nonRecursiveButton.setData("name", "nonRecursiveButton"); //$NON-NLS-1$ //$NON-NLS-2$ nonRecursiveButton.addSelectionListener(modyfyingListener); new Label(mainComposite, SWT.NONE); enableWorkspaceResolution = new Button(mainComposite, SWT.CHECK); enableWorkspaceResolution.addSelectionListener(modyfyingListener); enableWorkspaceResolution.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1)); enableWorkspaceResolution.setData("name", "enableWorkspaceResolution"); //$NON-NLS-1$ //$NON-NLS-2$ enableWorkspaceResolution.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnResolveWorkspace); TableViewer tableViewer = new TableViewer(mainComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { TableItem[] selection = propsTable.getSelection(); if(selection.length == 1) { editProperty(selection[0].getText(0), selection[0].getText(1)); } } }); tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){ public void selectionChanged(SelectionChangedEvent event) { TableItem[] items = propsTable.getSelection(); if(items == null || items.length == 0){ editPropButton.setEnabled(false); removePropButton.setEnabled(false); } else if(items.length == 1){ editPropButton.setEnabled(true); removePropButton.setEnabled(true); } else { editPropButton.setEnabled(false); removePropButton.setEnabled(true); } } }); this.propsTable = tableViewer.getTable(); //this.tProps.setItemCount(10); this.propsTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 3)); this.propsTable.setLinesVisible(true); this.propsTable.setHeaderVisible(true); final TableColumn propColumn = new TableColumn(this.propsTable, SWT.NONE, 0); propColumn.setWidth(120); propColumn.setText(Messages.getString("launch.propName")); //$NON-NLS-1$ final TableColumn valueColumn = new TableColumn(this.propsTable, SWT.NONE, 1); valueColumn.setWidth(200); valueColumn.setText(Messages.getString("launch.propValue")); //$NON-NLS-1$ final Button addPropButton = new Button(mainComposite, SWT.NONE); addPropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); addPropButton.setText(Messages.getString("launch.propAddButton")); //$NON-NLS-1$ addPropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addProperty(); } }); editPropButton = new Button(mainComposite, SWT.NONE); editPropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); editPropButton.setText(Messages.getString("launch.propEditButton")); //$NON-NLS-1$ editPropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(propsTable.getSelectionCount() > 0) { TableItem[] selection = propsTable.getSelection(); if(selection.length == 1) { editProperty(selection[0].getText(0), selection[0].getText(1)); } } } }); editPropButton.setEnabled(false); removePropButton = new Button(mainComposite, SWT.NONE); removePropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); removePropButton.setText(Messages.getString("launch.propRemoveButton")); //$NON-NLS-1$ removePropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(propsTable.getSelectionCount() > 0) { propsTable.remove(propsTable.getSelectionIndices()); entriesChanged(); } } }); removePropButton.setEnabled(false); { Composite composite = new Composite(mainComposite, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1)); GridLayout gridLayout = new GridLayout(2, false); gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; composite.setLayout(gridLayout); Label mavenRuntimeLabel = new Label(composite, SWT.NONE); mavenRuntimeLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); mavenRuntimeLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblRuntime); runtimeComboViewer = new ComboViewer(composite, SWT.BORDER | SWT.READ_ONLY); runtimeComboViewer.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); runtimeComboViewer.setContentProvider(new IStructuredContentProvider() { public Object[] getElements(Object input) { return ((List<?>) input).toArray(); } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public void dispose() { } }); runtimeComboViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { entriesChanged(); } }); MavenRuntimeManager runtimeManager = MavenPlugin.getDefault().getMavenRuntimeManager(); runtimeComboViewer.setInput(runtimeManager.getMavenRuntimes()); runtimeComboViewer.setSelection(new StructuredSelection(runtimeManager.getDefaultRuntime())); } Button configureRuntimesButton = new Button(mainComposite, SWT.NONE); GridData gd_configureRuntimesButton = new GridData(SWT.FILL, SWT.CENTER, false, false); configureRuntimesButton.setLayoutData(gd_configureRuntimesButton); configureRuntimesButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnConfigure); configureRuntimesButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PreferencesUtil.createPreferenceDialogOn(getShell(), "org.eclipse.m2e.preferences.MavenInstallationsPreferencePage", null, null).open(); //$NON-NLS-1$ MavenRuntimeManager runtimeManager = MavenPlugin.getDefault().getMavenRuntimeManager(); runtimeComboViewer.setInput(runtimeManager.getMavenRuntimes()); runtimeComboViewer.setSelection(new StructuredSelection(runtimeManager.getDefaultRuntime())); } }); if(isBuilder) { goalsAutoBuildText.setFocus(); } else { goalsText.setFocus(); } }
public void createControl(Composite parent) { Composite mainComposite = new Composite(parent, SWT.NONE); setControl(mainComposite); //PlatformUI.getWorkbench().getHelpSystem().setHelp(mainComposite, IAntUIHelpContextIds.ANT_MAIN_TAB); GridLayout layout = new GridLayout(); layout.numColumns = 5; GridData gridData = new GridData(GridData.FILL_HORIZONTAL); mainComposite.setLayout(layout); mainComposite.setLayoutData(gridData); mainComposite.setFont(parent.getFont()); class Listener implements ModifyListener, SelectionListener { public void modifyText(ModifyEvent e) { entriesChanged(); } public void widgetDefaultSelected(SelectionEvent e) { entriesChanged(); } public void widgetSelected(SelectionEvent e) { entriesChanged(); } } Listener modyfyingListener = new Listener(); Label label = new Label(mainComposite, SWT.NONE); label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 5, 1)); label.setText(Messages.getString("launch.pomGroup")); this.pomDirNameText = new Text(mainComposite, SWT.BORDER); this.pomDirNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 5, 1)); this.pomDirNameText.addModifyListener(modyfyingListener); final Composite pomDirButtonsComposite = new Composite(mainComposite, SWT.NONE); pomDirButtonsComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 5, 1)); final GridLayout pomDirButtonsGridLayout = new GridLayout(); pomDirButtonsGridLayout.marginWidth = 0; pomDirButtonsGridLayout.marginHeight = 0; pomDirButtonsGridLayout.numColumns = 3; pomDirButtonsComposite.setLayout(pomDirButtonsGridLayout); final Button browseWorkspaceButton = new Button(pomDirButtonsComposite, SWT.NONE); browseWorkspaceButton.setText(Messages.getString("launch.browseWorkspace")); //$NON-NLS-1$ browseWorkspaceButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), // ResourcesPlugin.getWorkspace().getRoot(), false, Messages.getString("launch.choosePomDir")); //$NON-NLS-1$ dialog.showClosedProjects(false); int buttonId = dialog.open(); if(buttonId == IDialogConstants.OK_ID) { Object[] resource = dialog.getResult(); if(resource != null && resource.length > 0) { String fileLoc = VariablesPlugin.getDefault().getStringVariableManager().generateVariableExpression( "workspace_loc", ((IPath) resource[0]).toString()); //$NON-NLS-1$ pomDirNameText.setText(fileLoc); entriesChanged(); } } } }); final Button browseFilesystemButton = new Button(pomDirButtonsComposite, SWT.NONE); browseFilesystemButton.setText(Messages.getString("launch.browseFs")); //$NON-NLS-1$ browseFilesystemButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.NONE); dialog.setFilterPath(pomDirNameText.getText()); String text = dialog.open(); if(text != null) { pomDirNameText.setText(text); entriesChanged(); } } }); final Button browseVariablesButton = new Button(pomDirButtonsComposite, SWT.NONE); browseVariablesButton.setText(Messages.getString("launch.browseVariables")); //$NON-NLS-1$ browseVariablesButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { StringVariableSelectionDialog dialog = new StringVariableSelectionDialog(getShell()); dialog.open(); String variable = dialog.getVariableExpression(); if(variable != null) { pomDirNameText.insert(variable); } } }); // pom file // goals if(isBuilder) { Label autoBuildGoalsLabel = new Label(mainComposite, SWT.NONE); GridData gd_autoBuildGoalsLabel = new GridData(); gd_autoBuildGoalsLabel.verticalIndent = 7; autoBuildGoalsLabel.setLayoutData(gd_autoBuildGoalsLabel); autoBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblAutoBuildGoals); goalsAutoBuildText = new Text(mainComposite, SWT.BORDER); GridData gd_goalsAutoBuildText = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1); gd_goalsAutoBuildText.verticalIndent = 7; goalsAutoBuildText.setLayoutData(gd_goalsAutoBuildText); goalsAutoBuildText.addModifyListener(modyfyingListener); goalsAutoBuildText.addFocusListener(new GoalsFocusListener(goalsAutoBuildText)); Button goalsAutoBuildButton = new Button(mainComposite, SWT.NONE); GridData gd_goalsAutoBuildButton = new GridData(SWT.FILL, SWT.CENTER, false, false); gd_goalsAutoBuildButton.verticalIndent = 7; goalsAutoBuildButton.setLayoutData(gd_goalsAutoBuildButton); goalsAutoBuildButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnAutoBuild); goalsAutoBuildButton.addSelectionListener(new GoalSelectionAdapter(goalsAutoBuildText)); Label manualBuildGoalsLabel = new Label(mainComposite, SWT.NONE); manualBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblManualGoals); goalsManualBuildText = new Text(mainComposite, SWT.BORDER); goalsManualBuildText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsManualBuildText.addModifyListener(modyfyingListener); goalsManualBuildText.addFocusListener(new GoalsFocusListener(goalsManualBuildText)); Button goalsManualBuildButton = new Button(mainComposite, SWT.NONE); goalsManualBuildButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsManualBuildButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnManualBuild); goalsManualBuildButton.addSelectionListener(new GoalSelectionAdapter(goalsManualBuildText)); Label cleanBuildGoalsLabel = new Label(mainComposite, SWT.NONE); cleanBuildGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblCleanBuild); goalsCleanText = new Text(mainComposite, SWT.BORDER); goalsCleanText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsCleanText.addModifyListener(modyfyingListener); goalsCleanText.addFocusListener(new GoalsFocusListener(goalsCleanText)); Button goalsCleanButton = new Button(mainComposite, SWT.NONE); goalsCleanButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsCleanButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnCleanBuild); goalsCleanButton.addSelectionListener(new GoalSelectionAdapter(goalsCleanText)); Label afterCleanGoalsLabel = new Label(mainComposite, SWT.NONE); afterCleanGoalsLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblAfterClean); goalsAfterCleanText = new Text(mainComposite, SWT.BORDER); goalsAfterCleanText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); goalsAfterCleanText.addModifyListener(modyfyingListener); goalsAfterCleanText.addFocusListener(new GoalsFocusListener(goalsAfterCleanText)); Button goalsAfterCleanButton = new Button(mainComposite, SWT.NONE); goalsAfterCleanButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); goalsAfterCleanButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnAfterClean); goalsAfterCleanButton.addSelectionListener(new GoalSelectionAdapter(goalsAfterCleanText)); } else { Label goalsLabel = new Label(mainComposite, SWT.NONE); GridData gd_goalsLabel = new GridData(); gd_goalsLabel.verticalIndent = 7; goalsLabel.setLayoutData(gd_goalsLabel); goalsLabel.setText(Messages.getString("launch.goalsLabel")); //$NON-NLS-1$ goalsText = new Text(mainComposite, SWT.BORDER); goalsText.setData("name", "goalsText"); //$NON-NLS-1$ //$NON-NLS-2$ GridData gd_goalsText = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1); gd_goalsText.verticalIndent = 7; goalsText.setLayoutData(gd_goalsText); goalsText.addModifyListener(modyfyingListener); goalsText.addFocusListener(new GoalsFocusListener(goalsText)); Button selectGoalsButton = new Button(mainComposite, SWT.NONE); GridData gd_selectGoalsButton = new GridData(SWT.FILL, SWT.CENTER, false, false); gd_selectGoalsButton.verticalIndent = 7; selectGoalsButton.setLayoutData(gd_selectGoalsButton); selectGoalsButton.setText(Messages.getString("launch.goals")); //$NON-NLS-1$ selectGoalsButton.addSelectionListener(new GoalSelectionAdapter(goalsText)); } Label profilesLabel = new Label(mainComposite, SWT.NONE); profilesLabel.setText(Messages.getString("launch.profilesLabel")); //$NON-NLS-1$ // profilesLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); profilesText = new Text(mainComposite, SWT.BORDER); profilesText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1)); profilesText.addModifyListener(modyfyingListener); new Label(mainComposite, SWT.NONE); offlineButton = new Button(mainComposite, SWT.CHECK); offlineButton.setToolTipText("-o"); //$NON-NLS-1$ GridData gd_offlineButton = new GridData(); offlineButton.setLayoutData(gd_offlineButton); offlineButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnOffline); offlineButton.addSelectionListener(modyfyingListener); updateSnapshotsButton = new Button(mainComposite, SWT.CHECK); updateSnapshotsButton.setToolTipText("-U"); //$NON-NLS-1$ updateSnapshotsButton.addSelectionListener(modyfyingListener); GridData gd_updateSnapshotsButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1); gd_updateSnapshotsButton.horizontalIndent = 10; updateSnapshotsButton.setLayoutData(gd_updateSnapshotsButton); updateSnapshotsButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnUpdateSnapshots); new Label(mainComposite, SWT.NONE); debugOutputButton = new Button(mainComposite, SWT.CHECK); debugOutputButton.setToolTipText("-X -e"); //$NON-NLS-1$ debugOutputButton.addSelectionListener(modyfyingListener); debugOutputButton.setLayoutData(new GridData()); debugOutputButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnDebugOutput); skipTestsButton = new Button(mainComposite, SWT.CHECK); skipTestsButton.setToolTipText("-Dmaven.test.skip=true"); //$NON-NLS-1$ skipTestsButton.addSelectionListener(modyfyingListener); GridData gd_skipTestsButton = new GridData(); gd_skipTestsButton.horizontalIndent = 10; skipTestsButton.setLayoutData(gd_skipTestsButton); skipTestsButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnSkipTests); nonRecursiveButton = new Button(mainComposite, SWT.CHECK); GridData gd_nonrecursiveButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1); gd_nonrecursiveButton.horizontalIndent = 10; nonRecursiveButton.setLayoutData(gd_nonrecursiveButton); nonRecursiveButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnNotRecursive); nonRecursiveButton.setToolTipText("-N"); //$NON-NLS-1$ nonRecursiveButton.setData("name", "nonRecursiveButton"); //$NON-NLS-1$ //$NON-NLS-2$ nonRecursiveButton.addSelectionListener(modyfyingListener); new Label(mainComposite, SWT.NONE); enableWorkspaceResolution = new Button(mainComposite, SWT.CHECK); enableWorkspaceResolution.addSelectionListener(modyfyingListener); enableWorkspaceResolution.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1)); enableWorkspaceResolution.setData("name", "enableWorkspaceResolution"); //$NON-NLS-1$ //$NON-NLS-2$ enableWorkspaceResolution.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnResolveWorkspace); TableViewer tableViewer = new TableViewer(mainComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); tableViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { TableItem[] selection = propsTable.getSelection(); if(selection.length == 1) { editProperty(selection[0].getText(0), selection[0].getText(1)); } } }); tableViewer.addSelectionChangedListener(new ISelectionChangedListener(){ public void selectionChanged(SelectionChangedEvent event) { TableItem[] items = propsTable.getSelection(); if(items == null || items.length == 0){ editPropButton.setEnabled(false); removePropButton.setEnabled(false); } else if(items.length == 1){ editPropButton.setEnabled(true); removePropButton.setEnabled(true); } else { editPropButton.setEnabled(false); removePropButton.setEnabled(true); } } }); this.propsTable = tableViewer.getTable(); //this.tProps.setItemCount(10); this.propsTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 4, 3)); this.propsTable.setLinesVisible(true); this.propsTable.setHeaderVisible(true); final TableColumn propColumn = new TableColumn(this.propsTable, SWT.NONE, 0); propColumn.setWidth(120); propColumn.setText(Messages.getString("launch.propName")); //$NON-NLS-1$ final TableColumn valueColumn = new TableColumn(this.propsTable, SWT.NONE, 1); valueColumn.setWidth(200); valueColumn.setText(Messages.getString("launch.propValue")); //$NON-NLS-1$ final Button addPropButton = new Button(mainComposite, SWT.NONE); addPropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); addPropButton.setText(Messages.getString("launch.propAddButton")); //$NON-NLS-1$ addPropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addProperty(); } }); editPropButton = new Button(mainComposite, SWT.NONE); editPropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); editPropButton.setText(Messages.getString("launch.propEditButton")); //$NON-NLS-1$ editPropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(propsTable.getSelectionCount() > 0) { TableItem[] selection = propsTable.getSelection(); if(selection.length == 1) { editProperty(selection[0].getText(0), selection[0].getText(1)); } } } }); editPropButton.setEnabled(false); removePropButton = new Button(mainComposite, SWT.NONE); removePropButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); removePropButton.setText(Messages.getString("launch.propRemoveButton")); //$NON-NLS-1$ removePropButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if(propsTable.getSelectionCount() > 0) { propsTable.remove(propsTable.getSelectionIndices()); entriesChanged(); } } }); removePropButton.setEnabled(false); { Composite composite = new Composite(mainComposite, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1)); GridLayout gridLayout = new GridLayout(2, false); gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; composite.setLayout(gridLayout); Label mavenRuntimeLabel = new Label(composite, SWT.NONE); mavenRuntimeLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); mavenRuntimeLabel.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_lblRuntime); runtimeComboViewer = new ComboViewer(composite, SWT.BORDER | SWT.READ_ONLY); runtimeComboViewer.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); runtimeComboViewer.setContentProvider(new IStructuredContentProvider() { public Object[] getElements(Object input) { return ((List<?>) input).toArray(); } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public void dispose() { } }); runtimeComboViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { entriesChanged(); } }); MavenRuntimeManager runtimeManager = MavenPlugin.getDefault().getMavenRuntimeManager(); runtimeComboViewer.setInput(runtimeManager.getMavenRuntimes()); runtimeComboViewer.setSelection(new StructuredSelection(runtimeManager.getDefaultRuntime())); } Button configureRuntimesButton = new Button(mainComposite, SWT.NONE); GridData gd_configureRuntimesButton = new GridData(SWT.FILL, SWT.CENTER, false, false); configureRuntimesButton.setLayoutData(gd_configureRuntimesButton); configureRuntimesButton.setText(org.eclipse.m2e.internal.launch.Messages.MavenLaunchMainTab_btnConfigure); configureRuntimesButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PreferencesUtil.createPreferenceDialogOn(getShell(), "org.eclipse.m2e.core.preferences.MavenInstallationsPreferencePage", null, null).open(); //$NON-NLS-1$ MavenRuntimeManager runtimeManager = MavenPlugin.getDefault().getMavenRuntimeManager(); runtimeComboViewer.setInput(runtimeManager.getMavenRuntimes()); runtimeComboViewer.setSelection(new StructuredSelection(runtimeManager.getDefaultRuntime())); } }); if(isBuilder) { goalsAutoBuildText.setFocus(); } else { goalsText.setFocus(); } }
diff --git a/src/main/java/org/flowdev/base/data/PrettyPrinter.java b/src/main/java/org/flowdev/base/data/PrettyPrinter.java index 890a951..0f9249f 100644 --- a/src/main/java/org/flowdev/base/data/PrettyPrinter.java +++ b/src/main/java/org/flowdev/base/data/PrettyPrinter.java @@ -1,167 +1,167 @@ package org.flowdev.base.data; import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Utility class for printing data and config objects. This is useful for * 'toString()' methods, debugging, ... */ public final class PrettyPrinter { public final static String INDENT = " "; public final static String NL = System.lineSeparator(); public final static String NULL = "NULL"; public static class Entry implements Comparable<Entry> { public String name; public Object value; public Entry(String nam, Object val) { name = (nam == null) ? NULL : nam; value = val; } public int compareTo(Entry e) { return name.compareTo(e.name); } } /** Prevent instantiation. */ private PrettyPrinter() { } public static String prettyPrint(Object obj) { return prettyPrintObject("", new StringBuilder(4096), obj).append(NL) .toString(); } public static StringBuilder prettyPrintObject(String indentation, StringBuilder buf, Object obj) { buf.append(obj.getClass().getSimpleName()).append(" {").append(NL); prettyPrintEntries(indentation + INDENT, buf, fieldsToEntries(obj.getClass().getFields(), obj), " = "); buf.append(indentation).append("}"); return buf; } private static Entry[] fieldsToEntries(Field[] fields, Object obj) { Entry[] entries = new Entry[fields.length]; for (int i = 0; i < fields.length; i++) { Field field = fields[i]; entries[i] = new Entry(field.getName(), getValueOfField(field, obj)); } return entries; } private static Object getValueOfField(Field field, Object obj) { try { return field.get(obj); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static StringBuilder prettyPrintEntries(String indentation, StringBuilder buf, Entry[] entries, String relation) { Arrays.sort(entries); for (Entry entry : entries) { prettyPrintEntry(indentation, buf, entry.name, " : ", entry.value); } return buf; } public static StringBuilder prettyPrintEntry(String indentation, StringBuilder buf, String name, String relation, Object value) { String type = (value == null) ? "" : value.getClass().getName(); buf.append(indentation).append(name).append(relation); if (value == null) { buf.append(NULL); } else if (value.getClass().isEnum() || value.getClass().isPrimitive()) { buf.append(value.toString()); } else if (value instanceof Map) { prettyPrintMap(indentation, buf, (Map<?, ?>) value); } else if (value instanceof List) { prettyPrintList(indentation, buf, (List<?>) value); } else if (value.getClass().isArray()) { buf.append("WARNING: Arrays are not supported: ").append( value.toString()); } else { switch (type) { case "java.lang.Boolean": case "java.lang.Byte": case "java.lang.Character": case "java.lang.Short": case "java.lang.Integer": case "java.lang.Long": case "java.lang.Float": case "java.lang.Double": - buf.append('"').append(value.toString()).append('"'); + buf.append(value.toString()); break; case "java.lang.String": - buf.append(value.toString()); + buf.append('"').append(value.toString()).append('"'); break; default: prettyPrintObject(indentation, buf, value); break; } } buf.append(" ;").append(NL); return buf; } public static StringBuilder prettyPrintMap(String indentation, StringBuilder buf, Map<?, ?> map) { buf.append("Map {").append(NL); prettyPrintEntries(indentation + INDENT, buf, mapToEntries(map), " : "); buf.append(indentation).append("}"); return buf; } private static Entry[] mapToEntries(Map<?, ?> map) { Entry[] entries = new Entry[map.size()]; int i = 0; for (Object key : map.keySet()) { entries[i] = new Entry(escapeString(key.toString()), map.get(key)); i++; } return entries; } public static String escapeString(String s) { return "\"" + s.replace("\\", "\\\\").replace("\t", "\\t") .replace("\n", "\\n").replace("\r", "\\r") + "\""; } public static StringBuilder prettyPrintList(String indentation, StringBuilder buf, List<?> list) { String innerIndentation = indentation + INDENT; int N = list.size(); buf.append("List [").append(NL); for (int i = 0; i < N; i++) { prettyPrintEntry(innerIndentation, buf, "" + i, " : ", list.get(i)); } buf.append(indentation).append("]"); return buf; } }
false
true
public static StringBuilder prettyPrintEntry(String indentation, StringBuilder buf, String name, String relation, Object value) { String type = (value == null) ? "" : value.getClass().getName(); buf.append(indentation).append(name).append(relation); if (value == null) { buf.append(NULL); } else if (value.getClass().isEnum() || value.getClass().isPrimitive()) { buf.append(value.toString()); } else if (value instanceof Map) { prettyPrintMap(indentation, buf, (Map<?, ?>) value); } else if (value instanceof List) { prettyPrintList(indentation, buf, (List<?>) value); } else if (value.getClass().isArray()) { buf.append("WARNING: Arrays are not supported: ").append( value.toString()); } else { switch (type) { case "java.lang.Boolean": case "java.lang.Byte": case "java.lang.Character": case "java.lang.Short": case "java.lang.Integer": case "java.lang.Long": case "java.lang.Float": case "java.lang.Double": buf.append('"').append(value.toString()).append('"'); break; case "java.lang.String": buf.append(value.toString()); break; default: prettyPrintObject(indentation, buf, value); break; } } buf.append(" ;").append(NL); return buf; }
public static StringBuilder prettyPrintEntry(String indentation, StringBuilder buf, String name, String relation, Object value) { String type = (value == null) ? "" : value.getClass().getName(); buf.append(indentation).append(name).append(relation); if (value == null) { buf.append(NULL); } else if (value.getClass().isEnum() || value.getClass().isPrimitive()) { buf.append(value.toString()); } else if (value instanceof Map) { prettyPrintMap(indentation, buf, (Map<?, ?>) value); } else if (value instanceof List) { prettyPrintList(indentation, buf, (List<?>) value); } else if (value.getClass().isArray()) { buf.append("WARNING: Arrays are not supported: ").append( value.toString()); } else { switch (type) { case "java.lang.Boolean": case "java.lang.Byte": case "java.lang.Character": case "java.lang.Short": case "java.lang.Integer": case "java.lang.Long": case "java.lang.Float": case "java.lang.Double": buf.append(value.toString()); break; case "java.lang.String": buf.append('"').append(value.toString()).append('"'); break; default: prettyPrintObject(indentation, buf, value); break; } } buf.append(" ;").append(NL); return buf; }
diff --git a/src/com/voc4u/activity/DialogInfo.java b/src/com/voc4u/activity/DialogInfo.java index 8ce93ac..71f1bf6 100644 --- a/src/com/voc4u/activity/DialogInfo.java +++ b/src/com/voc4u/activity/DialogInfo.java @@ -1,119 +1,119 @@ package com.voc4u.activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.voc4u.R; import com.voc4u.setting.CommonSetting; public class DialogInfo { public static final String TYPE_INIT = "init"; public static final String TYPE_DICTIONARY = "dictionary"; public static final String TYPE_TRAIN = "train"; public static Dialog create(final Context context) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.dialog_info); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; // lp.height = WindowManager.LayoutParams.FILL_PARENT; // dialog.show(); dialog.getWindow().setAttributes(lp); //setup(context, type, dialog); return dialog; } public static void setup(final Context context, final String type, final Dialog dialog) { Resources r = context.getResources(); - int titleid = r.getIdentifier("info_title_" + type, "string", context.getPackageName()); - int textid = r.getIdentifier("info_text_" + type, "string", context.getPackageName()); + int titleid = r.getIdentifier("form_" + type, "string", context.getPackageName()); + int textid = r.getIdentifier("information_" + type, "string", context.getPackageName()); dialog.setTitle(titleid); dialog.setOnCancelListener(new Dialog.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CommonSetting.store(context); } }); final TextView tvText = (TextView) dialog.findViewById(R.id.text); tvText.setText(textid); Button btnAdd = (Button) dialog.findViewById(R.id.btnCancel); btnAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); CommonSetting.store(context); } }); final CheckBox chkNSM = (CheckBox) dialog.findViewById(R.id.chkNoShowMore); chkNSM.setChecked( GetChecked(type)); chkNSM.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SetupCommonSetting(type, isChecked); } }); } public static boolean GetChecked(final String type) { if(type.contentEquals(TYPE_INIT)) { return CommonSetting.NSMInit; } else if(type.contentEquals(TYPE_DICTIONARY)) { return CommonSetting.NSMDictionary; } else if(type.contentEquals(TYPE_TRAIN)) { return CommonSetting.NSMTrain; } else // no show dialog which haven't // common setting value return true; } private static void SetupCommonSetting(final String type, boolean isChecked) { if(type.contentEquals(TYPE_INIT)) { CommonSetting.NSMInit = isChecked; } else if(type.contentEquals(TYPE_DICTIONARY)) { CommonSetting.NSMDictionary = isChecked; } else if(type.contentEquals(TYPE_TRAIN)) { CommonSetting.NSMTrain = isChecked; } } }
true
true
public static void setup(final Context context, final String type, final Dialog dialog) { Resources r = context.getResources(); int titleid = r.getIdentifier("info_title_" + type, "string", context.getPackageName()); int textid = r.getIdentifier("info_text_" + type, "string", context.getPackageName()); dialog.setTitle(titleid); dialog.setOnCancelListener(new Dialog.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CommonSetting.store(context); } }); final TextView tvText = (TextView) dialog.findViewById(R.id.text); tvText.setText(textid); Button btnAdd = (Button) dialog.findViewById(R.id.btnCancel); btnAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); CommonSetting.store(context); } }); final CheckBox chkNSM = (CheckBox) dialog.findViewById(R.id.chkNoShowMore); chkNSM.setChecked( GetChecked(type)); chkNSM.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SetupCommonSetting(type, isChecked); } }); }
public static void setup(final Context context, final String type, final Dialog dialog) { Resources r = context.getResources(); int titleid = r.getIdentifier("form_" + type, "string", context.getPackageName()); int textid = r.getIdentifier("information_" + type, "string", context.getPackageName()); dialog.setTitle(titleid); dialog.setOnCancelListener(new Dialog.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CommonSetting.store(context); } }); final TextView tvText = (TextView) dialog.findViewById(R.id.text); tvText.setText(textid); Button btnAdd = (Button) dialog.findViewById(R.id.btnCancel); btnAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); CommonSetting.store(context); } }); final CheckBox chkNSM = (CheckBox) dialog.findViewById(R.id.chkNoShowMore); chkNSM.setChecked( GetChecked(type)); chkNSM.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SetupCommonSetting(type, isChecked); } }); }
diff --git a/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java b/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java index 35895d9..cf46c5f 100644 --- a/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java +++ b/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java @@ -1,269 +1,285 @@ package com.webkonsept.bukkit.simplechestlock.listener; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.webkonsept.bukkit.simplechestlock.SCL; import com.webkonsept.bukkit.simplechestlock.locks.SCLItem; public class SCLPlayerListener implements Listener { final SCL plugin; public SCLPlayerListener(SCL instance) { plugin = instance; } private String ucfirst(String string){ return string.substring(0,1).toUpperCase() + string.substring(1); } // TODO: Break up this monster method, plx! @EventHandler public void onPlayerInteract (final PlayerInteractEvent event){ if (! plugin.isEnabled() ) return; if ( event.isCancelled() ) return; Block block = event.getClickedBlock(); ItemStack toolUsed = null; if (event.getItem() != null){ toolUsed = event.getItem().clone(); toolUsed.setAmount(1); } Player player = event.getPlayer(); if (block == null) return; // We don't care about non-block (air) interactions. if (plugin.canLock(block)){ String typeName = block.getType().toString().replaceAll("_", " ").toLowerCase(); if( event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || ( event.getAction().equals(Action.LEFT_CLICK_BLOCK) && plugin.leftLocked.contains(block.getType()) && !(plugin.toolMatch(toolUsed,plugin.cfg.key()) || plugin.toolMatch(toolUsed,plugin.cfg.comboKey())) ) || event.getAction().equals(Action.PHYSICAL) ){ if (plugin.chests.isLocked(block)){ SCLItem lockedItem = plugin.chests.getItem(block); String owner = lockedItem.getOwner(); SCL.verbose(player.getName() + " wants to use " + owner + "'s " + typeName); boolean ignoreOwner = SCL.permit(player, "simplechestlock.ignoreowner"); boolean comboLocked = lockedItem.isComboLocked(); if (comboLocked){ SCL.verbose("This block is locked with a combination lock!"); } else { SCL.verbose("This block is locked with a normal key"); } if ( comboLocked && ! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){ Inventory inv = player.getInventory(); if ( inv.getItem(0).getType().equals(Material.WOOL) && inv.getItem(1).getType().equals(Material.WOOL) && inv.getItem(2).getType().equals(Material.WOOL) ){ DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData()); DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData()); DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData()); DyeColor[] combo = {tumbler1,tumbler2,tumbler3}; if (!lockedItem.correctCombo(combo)){ SCL.verbose(player.getName() + " provided the wrong combo for " + owner + "'s " + typeName); plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" has a different combination..."); event.setCancelled(true); } } else { SCL.verbose(player.getName() + " provided no combo for " + owner + "'s " + typeName); plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" is locked with a combination lock."); event.setCancelled(true); } } else if (! owner.equalsIgnoreCase(player.getName()) && lockedItem.trusts(player)){ player.sendMessage(ChatColor.GREEN+owner+" trusts you with access to this "+typeName); } else if (! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){ event.setCancelled(true); plugin.messaging.throttledMessage(player,ChatColor.RED+"Access denied to "+owner+"'s "+typeName); } else if (! owner.equalsIgnoreCase(player.getName()) && ignoreOwner){ SCL.verbose(player.getName() + " was let into " + owner + "'s " + typeName + ", ignoring owner."); if (plugin.cfg.openMessage()){ player.sendMessage(ChatColor.GREEN+"Access granted to "+owner+"'s "+typeName); } } else { SCL.verbose(player.getName() + " was let into the " + typeName); if (plugin.cfg.openMessage()){ if (comboLocked){ String comboString = plugin.chests.getComboString(block); player.sendMessage(ChatColor.GREEN+"Lock combination is "+comboString); } else { player.sendMessage(ChatColor.GREEN+"Access granted to "+typeName); } String trustedNames = lockedItem.trustedNames(); if (trustedNames != null && trustedNames.length() > 0){ player.sendMessage(ChatColor.GREEN+"Trusted for access: "+trustedNames); } } } } else { SCL.verbose("Access granted to unlocked " + typeName); } } else if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){ ItemStack inHand = event.getItem(); if (inHand == null) return; ItemStack tool = inHand.clone(); tool.setAmount(1); if (plugin.toolMatch(tool,plugin.cfg.key()) || plugin.toolMatch(tool,plugin.cfg.comboKey())){ event.setCancelled(true); if (SCL.permit(player,"simplechestlock.lock")){ if (plugin.chests.isLocked(block)){ String owner = plugin.chests.getOwner(block); if (owner.equalsIgnoreCase(player.getName())){ Integer unlockedChests = plugin.chests.unlock(block); if (unlockedChests == 1){ player.sendMessage(ChatColor.GREEN+ucfirst(typeName)+" unlocked"); } else if (unlockedChests > 1){ player.sendMessage(ChatColor.GREEN+unlockedChests.toString()+" "+typeName+"s unlocked"); } else { player.sendMessage(ChatColor.RED+"Error while unlocking your "+typeName); } } else if (SCL.permit(player, "simplechestlock.ignoreowner")){ Integer unlockedChests = plugin.chests.unlock(block); Player ownerObject = Bukkit.getServer().getPlayer(owner); if (unlockedChests == 1){ if (ownerObject != null){ player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", and taddle-taled on you for it."); ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked your "+typeName+" using mystic powers!"); } else { player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", but that user is offline, and was not notified."); } } else if (unlockedChests > 1){ if (ownerObject != null){ player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+unlockedChests.toString()+" "+typeName+"s, and taddle-taled on you for it."); ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked "+unlockedChests.toString()+" of your "+typeName+"s using mystic powers!"); } } else { player.sendMessage(ChatColor.RED+"Error while unlocking "+owner+"'s "+typeName); } } else { player.sendMessage(ChatColor.RED+"Locked by "+owner+": You can't use it!"); } } else { if ( !(plugin.cfg.usePermissionsWhitelist()) || ( plugin.cfg.usePermissionsWhitelist() // Just checking for the indevidual block now, as the parent .* permission will grant them all. && SCL.permit(player,"simplechestlock.locktype."+block.getType().toString().toLowerCase()) ) ){ boolean lockForSomeone = false; String locksFor = player.getName(); if (plugin.locksAs.containsKey(player.getName())){ locksFor = plugin.locksAs.get(player.getName()); lockForSomeone = true; } if (plugin.toolMatch(tool,plugin.cfg.comboKey())){ if (SCL.permit(player, "simplechestlock.usecombo")){ Inventory inv = player.getInventory(); if ( inv.getItem(0).getType().equals(Material.WOOL) && inv.getItem(1).getType().equals(Material.WOOL) && inv.getItem(2).getType().equals(Material.WOOL) ){ DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData()); DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData()); DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData()); DyeColor[] combo = {tumbler1,tumbler2,tumbler3}; String comboString = tumbler1.toString()+","+tumbler2.toString()+","+tumbler3.toString(); Integer itemsLocked = plugin.chests.lock(player,block,combo); if (itemsLocked >= 1){ if (lockForSomeone){ player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"! Combo is "+comboString); } else { player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+"s locked! Combo is "+comboString); } if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){ - player.getInventory().remove(plugin.cfg.comboKey()); + if (inHand.getAmount() > 1){ + inHand.setAmount(inHand.getAmount()-1); + } + else if (inHand.getAmount() == 1){ + player.setItemInHand(new ItemStack(Material.AIR)); + } + else { + SCL.crap(player.getName()+" is locking stuff without being charged for it!"); + } } } else if (itemsLocked < 0){ player.sendMessage(ChatColor.RED+"Something horrible happened while trying to lock!"); } } else { player.sendMessage(ChatColor.RED+"First three hotbar slots must be wool for the combo!"); } } else { player.sendMessage(ChatColor.RED+"Sorry, permission denied for combination locking!"); } } else { Integer itemsLocked = plugin.chests.lock(player, block); String trustReminder = plugin.trustHandler.trustList(locksFor); if (itemsLocked >= 1){ if (lockForSomeone){ player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"!"); if (trustReminder != null){ player.sendMessage(ChatColor.GREEN+trustReminder); } } else { player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked!"); if (trustReminder != null){ player.sendMessage(ChatColor.GREEN+trustReminder); } } if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){ - player.getInventory().remove(plugin.cfg.key()); + if (inHand.getAmount() > 1){ + inHand.setAmount(inHand.getAmount()-1); + } + else if (inHand.getAmount() == 1){ + player.setItemInHand(new ItemStack(Material.AIR)); + } + else { + SCL.crap(player.getName()+" is locking stuff without being charged for it!"); + } } } else if (itemsLocked < 0){ player.sendMessage(ChatColor.RED+"Strange and horrible error encountered while locking!"); } } } else if (plugin.cfg.usePermissionsWhitelist() && plugin.cfg.whitelistMessage()){ player.sendMessage(ChatColor.RED+"Sorry, you are not allowed to lock "+block.getType().toString()); } } } else { player.sendMessage(ChatColor.RED+"You can't lock or unlock blocks! Permission denied!"); } } } } } }
false
true
public void onPlayerInteract (final PlayerInteractEvent event){ if (! plugin.isEnabled() ) return; if ( event.isCancelled() ) return; Block block = event.getClickedBlock(); ItemStack toolUsed = null; if (event.getItem() != null){ toolUsed = event.getItem().clone(); toolUsed.setAmount(1); } Player player = event.getPlayer(); if (block == null) return; // We don't care about non-block (air) interactions. if (plugin.canLock(block)){ String typeName = block.getType().toString().replaceAll("_", " ").toLowerCase(); if( event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || ( event.getAction().equals(Action.LEFT_CLICK_BLOCK) && plugin.leftLocked.contains(block.getType()) && !(plugin.toolMatch(toolUsed,plugin.cfg.key()) || plugin.toolMatch(toolUsed,plugin.cfg.comboKey())) ) || event.getAction().equals(Action.PHYSICAL) ){ if (plugin.chests.isLocked(block)){ SCLItem lockedItem = plugin.chests.getItem(block); String owner = lockedItem.getOwner(); SCL.verbose(player.getName() + " wants to use " + owner + "'s " + typeName); boolean ignoreOwner = SCL.permit(player, "simplechestlock.ignoreowner"); boolean comboLocked = lockedItem.isComboLocked(); if (comboLocked){ SCL.verbose("This block is locked with a combination lock!"); } else { SCL.verbose("This block is locked with a normal key"); } if ( comboLocked && ! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){ Inventory inv = player.getInventory(); if ( inv.getItem(0).getType().equals(Material.WOOL) && inv.getItem(1).getType().equals(Material.WOOL) && inv.getItem(2).getType().equals(Material.WOOL) ){ DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData()); DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData()); DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData()); DyeColor[] combo = {tumbler1,tumbler2,tumbler3}; if (!lockedItem.correctCombo(combo)){ SCL.verbose(player.getName() + " provided the wrong combo for " + owner + "'s " + typeName); plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" has a different combination..."); event.setCancelled(true); } } else { SCL.verbose(player.getName() + " provided no combo for " + owner + "'s " + typeName); plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" is locked with a combination lock."); event.setCancelled(true); } } else if (! owner.equalsIgnoreCase(player.getName()) && lockedItem.trusts(player)){ player.sendMessage(ChatColor.GREEN+owner+" trusts you with access to this "+typeName); } else if (! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){ event.setCancelled(true); plugin.messaging.throttledMessage(player,ChatColor.RED+"Access denied to "+owner+"'s "+typeName); } else if (! owner.equalsIgnoreCase(player.getName()) && ignoreOwner){ SCL.verbose(player.getName() + " was let into " + owner + "'s " + typeName + ", ignoring owner."); if (plugin.cfg.openMessage()){ player.sendMessage(ChatColor.GREEN+"Access granted to "+owner+"'s "+typeName); } } else { SCL.verbose(player.getName() + " was let into the " + typeName); if (plugin.cfg.openMessage()){ if (comboLocked){ String comboString = plugin.chests.getComboString(block); player.sendMessage(ChatColor.GREEN+"Lock combination is "+comboString); } else { player.sendMessage(ChatColor.GREEN+"Access granted to "+typeName); } String trustedNames = lockedItem.trustedNames(); if (trustedNames != null && trustedNames.length() > 0){ player.sendMessage(ChatColor.GREEN+"Trusted for access: "+trustedNames); } } } } else { SCL.verbose("Access granted to unlocked " + typeName); } } else if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){ ItemStack inHand = event.getItem(); if (inHand == null) return; ItemStack tool = inHand.clone(); tool.setAmount(1); if (plugin.toolMatch(tool,plugin.cfg.key()) || plugin.toolMatch(tool,plugin.cfg.comboKey())){ event.setCancelled(true); if (SCL.permit(player,"simplechestlock.lock")){ if (plugin.chests.isLocked(block)){ String owner = plugin.chests.getOwner(block); if (owner.equalsIgnoreCase(player.getName())){ Integer unlockedChests = plugin.chests.unlock(block); if (unlockedChests == 1){ player.sendMessage(ChatColor.GREEN+ucfirst(typeName)+" unlocked"); } else if (unlockedChests > 1){ player.sendMessage(ChatColor.GREEN+unlockedChests.toString()+" "+typeName+"s unlocked"); } else { player.sendMessage(ChatColor.RED+"Error while unlocking your "+typeName); } } else if (SCL.permit(player, "simplechestlock.ignoreowner")){ Integer unlockedChests = plugin.chests.unlock(block); Player ownerObject = Bukkit.getServer().getPlayer(owner); if (unlockedChests == 1){ if (ownerObject != null){ player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", and taddle-taled on you for it."); ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked your "+typeName+" using mystic powers!"); } else { player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", but that user is offline, and was not notified."); } } else if (unlockedChests > 1){ if (ownerObject != null){ player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+unlockedChests.toString()+" "+typeName+"s, and taddle-taled on you for it."); ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked "+unlockedChests.toString()+" of your "+typeName+"s using mystic powers!"); } } else { player.sendMessage(ChatColor.RED+"Error while unlocking "+owner+"'s "+typeName); } } else { player.sendMessage(ChatColor.RED+"Locked by "+owner+": You can't use it!"); } } else { if ( !(plugin.cfg.usePermissionsWhitelist()) || ( plugin.cfg.usePermissionsWhitelist() // Just checking for the indevidual block now, as the parent .* permission will grant them all. && SCL.permit(player,"simplechestlock.locktype."+block.getType().toString().toLowerCase()) ) ){ boolean lockForSomeone = false; String locksFor = player.getName(); if (plugin.locksAs.containsKey(player.getName())){ locksFor = plugin.locksAs.get(player.getName()); lockForSomeone = true; } if (plugin.toolMatch(tool,plugin.cfg.comboKey())){ if (SCL.permit(player, "simplechestlock.usecombo")){ Inventory inv = player.getInventory(); if ( inv.getItem(0).getType().equals(Material.WOOL) && inv.getItem(1).getType().equals(Material.WOOL) && inv.getItem(2).getType().equals(Material.WOOL) ){ DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData()); DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData()); DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData()); DyeColor[] combo = {tumbler1,tumbler2,tumbler3}; String comboString = tumbler1.toString()+","+tumbler2.toString()+","+tumbler3.toString(); Integer itemsLocked = plugin.chests.lock(player,block,combo); if (itemsLocked >= 1){ if (lockForSomeone){ player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"! Combo is "+comboString); } else { player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+"s locked! Combo is "+comboString); } if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){ player.getInventory().remove(plugin.cfg.comboKey()); } } else if (itemsLocked < 0){ player.sendMessage(ChatColor.RED+"Something horrible happened while trying to lock!"); } } else { player.sendMessage(ChatColor.RED+"First three hotbar slots must be wool for the combo!"); } } else { player.sendMessage(ChatColor.RED+"Sorry, permission denied for combination locking!"); } } else { Integer itemsLocked = plugin.chests.lock(player, block); String trustReminder = plugin.trustHandler.trustList(locksFor); if (itemsLocked >= 1){ if (lockForSomeone){ player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"!"); if (trustReminder != null){ player.sendMessage(ChatColor.GREEN+trustReminder); } } else { player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked!"); if (trustReminder != null){ player.sendMessage(ChatColor.GREEN+trustReminder); } } if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){ player.getInventory().remove(plugin.cfg.key()); } } else if (itemsLocked < 0){ player.sendMessage(ChatColor.RED+"Strange and horrible error encountered while locking!"); } } } else if (plugin.cfg.usePermissionsWhitelist() && plugin.cfg.whitelistMessage()){ player.sendMessage(ChatColor.RED+"Sorry, you are not allowed to lock "+block.getType().toString()); } } } else { player.sendMessage(ChatColor.RED+"You can't lock or unlock blocks! Permission denied!"); } } } } }
public void onPlayerInteract (final PlayerInteractEvent event){ if (! plugin.isEnabled() ) return; if ( event.isCancelled() ) return; Block block = event.getClickedBlock(); ItemStack toolUsed = null; if (event.getItem() != null){ toolUsed = event.getItem().clone(); toolUsed.setAmount(1); } Player player = event.getPlayer(); if (block == null) return; // We don't care about non-block (air) interactions. if (plugin.canLock(block)){ String typeName = block.getType().toString().replaceAll("_", " ").toLowerCase(); if( event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || ( event.getAction().equals(Action.LEFT_CLICK_BLOCK) && plugin.leftLocked.contains(block.getType()) && !(plugin.toolMatch(toolUsed,plugin.cfg.key()) || plugin.toolMatch(toolUsed,plugin.cfg.comboKey())) ) || event.getAction().equals(Action.PHYSICAL) ){ if (plugin.chests.isLocked(block)){ SCLItem lockedItem = plugin.chests.getItem(block); String owner = lockedItem.getOwner(); SCL.verbose(player.getName() + " wants to use " + owner + "'s " + typeName); boolean ignoreOwner = SCL.permit(player, "simplechestlock.ignoreowner"); boolean comboLocked = lockedItem.isComboLocked(); if (comboLocked){ SCL.verbose("This block is locked with a combination lock!"); } else { SCL.verbose("This block is locked with a normal key"); } if ( comboLocked && ! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){ Inventory inv = player.getInventory(); if ( inv.getItem(0).getType().equals(Material.WOOL) && inv.getItem(1).getType().equals(Material.WOOL) && inv.getItem(2).getType().equals(Material.WOOL) ){ DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData()); DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData()); DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData()); DyeColor[] combo = {tumbler1,tumbler2,tumbler3}; if (!lockedItem.correctCombo(combo)){ SCL.verbose(player.getName() + " provided the wrong combo for " + owner + "'s " + typeName); plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" has a different combination..."); event.setCancelled(true); } } else { SCL.verbose(player.getName() + " provided no combo for " + owner + "'s " + typeName); plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" is locked with a combination lock."); event.setCancelled(true); } } else if (! owner.equalsIgnoreCase(player.getName()) && lockedItem.trusts(player)){ player.sendMessage(ChatColor.GREEN+owner+" trusts you with access to this "+typeName); } else if (! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){ event.setCancelled(true); plugin.messaging.throttledMessage(player,ChatColor.RED+"Access denied to "+owner+"'s "+typeName); } else if (! owner.equalsIgnoreCase(player.getName()) && ignoreOwner){ SCL.verbose(player.getName() + " was let into " + owner + "'s " + typeName + ", ignoring owner."); if (plugin.cfg.openMessage()){ player.sendMessage(ChatColor.GREEN+"Access granted to "+owner+"'s "+typeName); } } else { SCL.verbose(player.getName() + " was let into the " + typeName); if (plugin.cfg.openMessage()){ if (comboLocked){ String comboString = plugin.chests.getComboString(block); player.sendMessage(ChatColor.GREEN+"Lock combination is "+comboString); } else { player.sendMessage(ChatColor.GREEN+"Access granted to "+typeName); } String trustedNames = lockedItem.trustedNames(); if (trustedNames != null && trustedNames.length() > 0){ player.sendMessage(ChatColor.GREEN+"Trusted for access: "+trustedNames); } } } } else { SCL.verbose("Access granted to unlocked " + typeName); } } else if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){ ItemStack inHand = event.getItem(); if (inHand == null) return; ItemStack tool = inHand.clone(); tool.setAmount(1); if (plugin.toolMatch(tool,plugin.cfg.key()) || plugin.toolMatch(tool,plugin.cfg.comboKey())){ event.setCancelled(true); if (SCL.permit(player,"simplechestlock.lock")){ if (plugin.chests.isLocked(block)){ String owner = plugin.chests.getOwner(block); if (owner.equalsIgnoreCase(player.getName())){ Integer unlockedChests = plugin.chests.unlock(block); if (unlockedChests == 1){ player.sendMessage(ChatColor.GREEN+ucfirst(typeName)+" unlocked"); } else if (unlockedChests > 1){ player.sendMessage(ChatColor.GREEN+unlockedChests.toString()+" "+typeName+"s unlocked"); } else { player.sendMessage(ChatColor.RED+"Error while unlocking your "+typeName); } } else if (SCL.permit(player, "simplechestlock.ignoreowner")){ Integer unlockedChests = plugin.chests.unlock(block); Player ownerObject = Bukkit.getServer().getPlayer(owner); if (unlockedChests == 1){ if (ownerObject != null){ player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", and taddle-taled on you for it."); ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked your "+typeName+" using mystic powers!"); } else { player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", but that user is offline, and was not notified."); } } else if (unlockedChests > 1){ if (ownerObject != null){ player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+unlockedChests.toString()+" "+typeName+"s, and taddle-taled on you for it."); ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked "+unlockedChests.toString()+" of your "+typeName+"s using mystic powers!"); } } else { player.sendMessage(ChatColor.RED+"Error while unlocking "+owner+"'s "+typeName); } } else { player.sendMessage(ChatColor.RED+"Locked by "+owner+": You can't use it!"); } } else { if ( !(plugin.cfg.usePermissionsWhitelist()) || ( plugin.cfg.usePermissionsWhitelist() // Just checking for the indevidual block now, as the parent .* permission will grant them all. && SCL.permit(player,"simplechestlock.locktype."+block.getType().toString().toLowerCase()) ) ){ boolean lockForSomeone = false; String locksFor = player.getName(); if (plugin.locksAs.containsKey(player.getName())){ locksFor = plugin.locksAs.get(player.getName()); lockForSomeone = true; } if (plugin.toolMatch(tool,plugin.cfg.comboKey())){ if (SCL.permit(player, "simplechestlock.usecombo")){ Inventory inv = player.getInventory(); if ( inv.getItem(0).getType().equals(Material.WOOL) && inv.getItem(1).getType().equals(Material.WOOL) && inv.getItem(2).getType().equals(Material.WOOL) ){ DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData()); DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData()); DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData()); DyeColor[] combo = {tumbler1,tumbler2,tumbler3}; String comboString = tumbler1.toString()+","+tumbler2.toString()+","+tumbler3.toString(); Integer itemsLocked = plugin.chests.lock(player,block,combo); if (itemsLocked >= 1){ if (lockForSomeone){ player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"! Combo is "+comboString); } else { player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+"s locked! Combo is "+comboString); } if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){ if (inHand.getAmount() > 1){ inHand.setAmount(inHand.getAmount()-1); } else if (inHand.getAmount() == 1){ player.setItemInHand(new ItemStack(Material.AIR)); } else { SCL.crap(player.getName()+" is locking stuff without being charged for it!"); } } } else if (itemsLocked < 0){ player.sendMessage(ChatColor.RED+"Something horrible happened while trying to lock!"); } } else { player.sendMessage(ChatColor.RED+"First three hotbar slots must be wool for the combo!"); } } else { player.sendMessage(ChatColor.RED+"Sorry, permission denied for combination locking!"); } } else { Integer itemsLocked = plugin.chests.lock(player, block); String trustReminder = plugin.trustHandler.trustList(locksFor); if (itemsLocked >= 1){ if (lockForSomeone){ player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"!"); if (trustReminder != null){ player.sendMessage(ChatColor.GREEN+trustReminder); } } else { player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked!"); if (trustReminder != null){ player.sendMessage(ChatColor.GREEN+trustReminder); } } if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){ if (inHand.getAmount() > 1){ inHand.setAmount(inHand.getAmount()-1); } else if (inHand.getAmount() == 1){ player.setItemInHand(new ItemStack(Material.AIR)); } else { SCL.crap(player.getName()+" is locking stuff without being charged for it!"); } } } else if (itemsLocked < 0){ player.sendMessage(ChatColor.RED+"Strange and horrible error encountered while locking!"); } } } else if (plugin.cfg.usePermissionsWhitelist() && plugin.cfg.whitelistMessage()){ player.sendMessage(ChatColor.RED+"Sorry, you are not allowed to lock "+block.getType().toString()); } } } else { player.sendMessage(ChatColor.RED+"You can't lock or unlock blocks! Permission denied!"); } } } } }
diff --git a/src/net/kiwz/ThePlugin/commands/PlaceCommand.java b/src/net/kiwz/ThePlugin/commands/PlaceCommand.java index 2a82fd7..37dc68b 100644 --- a/src/net/kiwz/ThePlugin/commands/PlaceCommand.java +++ b/src/net/kiwz/ThePlugin/commands/PlaceCommand.java @@ -1,303 +1,303 @@ package net.kiwz.ThePlugin.commands; import net.kiwz.ThePlugin.ThePlugin; import net.kiwz.ThePlugin.utils.HandlePlaces; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class PlaceCommand { /** * * @param sender player who issued the command * @param cmd command that was issued * @param args as String[] describing what we want to do with given place * @return true no matter what */ public boolean place(CommandSender sender, Command cmd, String[] args) { HandlePlaces hPlaces = new HandlePlaces(); HelpCommand help = new HelpCommand(); Player player = Bukkit.getPlayer(sender.getName()); int id; if (!(sender instanceof Player)) { int check = 0; if (args.length == 0) { check = 1; } if((args.length == 1 || args.length == 2) && args[0].equalsIgnoreCase("spiller")) { check = 1; } if (args.length == 1 && !args[0].equalsIgnoreCase("her")) { check = 1; } if (check == 0) { sender.sendMessage(ThePlugin.c2 + "Consolen kan bare bruke /plass, /plass liste, /plass spiller <navn> og /plass <navn>"); return true; } } for (String arg : args) { if (!arg.matches("[a-zA-Z-_0-9������]+")) { sender.sendMessage(ThePlugin.c2 + "Tillatte tegn er a-� A-� 0-9 - _"); return true; } } if (args.length == 0) { help.customHelp(sender, cmd.getName(), "1", help()); return true; } else if (args.length == 1) { if (args[0].equalsIgnoreCase("liste")) { hPlaces.sendPlaceList(sender); return true; } else if (args[0].equalsIgnoreCase("spiller")) { hPlaces.sendPlayersPlaceList(sender); return true; } else if (args[0].equalsIgnoreCase("her")) { hPlaces.sendPlaceHere(sender); return true; } else if (args[0].length() == 1) { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } else { id = hPlaces.getID(args[0]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[0] + " finnes ikke"); return true; } hPlaces.sendPlace(sender, id); return true; } } if (args.length == 2) { if (args[0].equalsIgnoreCase("spiller")) { sender.sendMessage(hPlaces.getOwned(args[1])); sender.sendMessage(hPlaces.getMembered(args[1])); return true; } if (args[0].equalsIgnoreCase("ny")) { sender.sendMessage(hPlaces.addPlace(player, args[1], "40")); return true; } id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } if (args[0].equalsIgnoreCase("flytt")) { sender.sendMessage(hPlaces.setPlace(player, id, "40")); return true; } else if (args[0].equalsIgnoreCase("spawn")) { player.teleport(hPlaces.getSpawn(id)); return true; } else if (args[0].equalsIgnoreCase("setspawn")) { sender.sendMessage(hPlaces.setSpawn(player, id)); return true; } else if (args[0].equalsIgnoreCase("slett")) { sender.sendMessage(hPlaces.remPlace(player, id)); return true; } else if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, "")); return true; } else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, "")); return true; } else if (args[0].equalsIgnoreCase("navn")) { sender.sendMessage(ThePlugin.c2 + "/plass navn <plass-navn> <nytt-plass-navn>"); return true; } else if (args[0].equalsIgnoreCase("toggle")) { sender.sendMessage(ThePlugin.c2 + "/plass toggle <plass-navn> <[pvp] [monstre] [dyr]>"); return true; } else if (args[0].equalsIgnoreCase("medlem")) { sender.sendMessage(ThePlugin.c2 + "/plass medlem <plass-navn> <spiller-navn>"); return true; } else if (args[0].equalsIgnoreCase("spark")) { sender.sendMessage(ThePlugin.c2 + "/plass spark <plass-navn> <spiller-navn>"); return true; } else if (args[0].equalsIgnoreCase("eier")) { sender.sendMessage(ThePlugin.c2 + "/plass eier <plass-navn> <spiller-navn>"); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else if (args.length == 3) { if (args[0].equalsIgnoreCase("ny")) { if (!args[2].matches("[0-9]+")) { sender.sendMessage(ThePlugin.c2 + "St�rrelsen m� defineres med tall"); return true; } sender.sendMessage(hPlaces.addPlace(player, args[1], args[2])); return true; } id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } if (args[0].equalsIgnoreCase("flytt")) { if (!args[2].matches("[0-9]+")) { sender.sendMessage(ThePlugin.c2 + "St�rrelsen m� defineres med tall"); return true; } sender.sendMessage(hPlaces.setPlace(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("navn")) { sender.sendMessage(hPlaces.setName(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("toggle")) { if (args[2].equalsIgnoreCase("pvp")) { sender.sendMessage(hPlaces.setPvP(player, id)); return true; } else if (args[2].equalsIgnoreCase("monstre")) { sender.sendMessage(hPlaces.setMonsters(player, id)); return true; } else if (args[2].equalsIgnoreCase("dyr")) { sender.sendMessage(hPlaces.setAnimals(player, id)); return true; } else { sender.sendMessage(ThePlugin.c2 + "Du m� skrive pvp/monstre/dyr"); return true; } } else if (args[0].equalsIgnoreCase("medlem")) { sender.sendMessage(hPlaces.addMember(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("spark")) { sender.sendMessage(hPlaces.remMember(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("eier")) { sender.sendMessage(hPlaces.setOwner(player, id, args[2])); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else if (args.length > 3 && (args[0].equalsIgnoreCase("entre") || args[0].equalsIgnoreCase("forlate"))) { id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } String arg = ""; for (int i = 2; i < args.length; i++) { arg = arg + args[i] + " "; } arg = arg.trim(); - if (args[1].equalsIgnoreCase("entre")) { + if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, arg)); return true; } - else if (args[1].equalsIgnoreCase("forlate")) { + else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, arg)); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } /** * * @return Help entryes for /plass */ private String help() { ChatColor white = ChatColor.WHITE; ChatColor gold = ChatColor.GOLD; StringBuilder help = new StringBuilder(); help.append(gold + "/plass\n"); help.append(white + "Viser denne hjelpe menyen\n"); help.append(gold + "/plass liste\n"); help.append(white + "Viser en liste over alle plasser\n"); help.append(gold + "/plass spiller\n"); help.append(white + "Viser en liste over spillere som har plasser\n"); help.append(gold + "/plass spiller <spiller-navn>\n"); help.append(white + "Viser hvilke plasser spilleren er eier og medlem av\n"); help.append(gold + "/plass her\n"); help.append(white + "Viser info om plassen du st�r p�\n"); help.append(gold + "/plass <plass-navn>\n"); help.append(white + "Viser info om angitte plass\n"); help.append(gold + "/plass ny <plass-navn>\n"); help.append(white + "Lager ny plass der du st�r (st�rrelse blir 81x81)\n"); help.append(gold + "/plass ny <plass-navn> <st�rrelse>\n"); help.append(white + "Lager ny plass der du st�r med �nsket st�rrelse\n"); help.append(gold + "/plass flytt <plass-navn>\n"); help.append(white + "Flytter plassen din til der du st�r (st�rrelse blir 81x81)\n"); help.append(gold + "/plass flytt <plass-navn> <st�rrelse>\n"); help.append(white + "Flytter plassen din til der du st�r med �nsket st�rrelse\n"); help.append(gold + "/plass spawn <plass-navn>\n"); help.append(white + "Teleporterer deg til spawn i angitte plass\n"); help.append(gold + "/plass setspawn <plass-navn>\n"); help.append(white + "Setter ny spawn til der du st�r\n"); help.append(gold + "/plass medlem <plass-navn> <spiller-navn>\n"); help.append(white + "Inviterer spiller til � bli medlem av din plass\n"); help.append(gold + "/plass spark <plass-navn> <spiller-navn>\n"); help.append(white + "Fjerner spiller som medlem av din plass\n"); help.append(gold + "/plass eier <plass-navn> <spiller-navn>\n"); help.append(white + "Setter ny eier av din plass, DU kan IKKE gj�re om dette\n"); help.append(gold + "/plass navn <plass-navn> <nytt-plass-navn>\n"); help.append(white + "Bytter navn p� angitte plass\n"); help.append(gold + "/plass toggle <plass-navn> [pvp, monstre, dyr]\n"); help.append(white + "Skrur p�/av pvp, monstre eller dyr\n"); help.append(gold + "/plass entre <plass-navn> <ny velkomst-melding>\n"); help.append(white + "Setter ny velkomst-melding for angitte plass\n"); help.append(gold + "/plass entre <plass-navn>\n"); help.append(white + "Fjerner velkomst-melding for angitte plass\n"); help.append(gold + "/plass forlate <plass-navn> <ny forlat-melding>\n"); help.append(white + "Setter ny forlat-melding for angitte plass\n"); help.append(gold + "/plass forlate <plass-navn>\n"); help.append(white + "Fjerner forlat-melding for angitte plass\n"); help.append(gold + "/plass slett <plass-navn>\n"); help.append(white + "Sletter angitte plass\n"); return help.toString(); } }
false
true
public boolean place(CommandSender sender, Command cmd, String[] args) { HandlePlaces hPlaces = new HandlePlaces(); HelpCommand help = new HelpCommand(); Player player = Bukkit.getPlayer(sender.getName()); int id; if (!(sender instanceof Player)) { int check = 0; if (args.length == 0) { check = 1; } if((args.length == 1 || args.length == 2) && args[0].equalsIgnoreCase("spiller")) { check = 1; } if (args.length == 1 && !args[0].equalsIgnoreCase("her")) { check = 1; } if (check == 0) { sender.sendMessage(ThePlugin.c2 + "Consolen kan bare bruke /plass, /plass liste, /plass spiller <navn> og /plass <navn>"); return true; } } for (String arg : args) { if (!arg.matches("[a-zA-Z-_0-9������]+")) { sender.sendMessage(ThePlugin.c2 + "Tillatte tegn er a-� A-� 0-9 - _"); return true; } } if (args.length == 0) { help.customHelp(sender, cmd.getName(), "1", help()); return true; } else if (args.length == 1) { if (args[0].equalsIgnoreCase("liste")) { hPlaces.sendPlaceList(sender); return true; } else if (args[0].equalsIgnoreCase("spiller")) { hPlaces.sendPlayersPlaceList(sender); return true; } else if (args[0].equalsIgnoreCase("her")) { hPlaces.sendPlaceHere(sender); return true; } else if (args[0].length() == 1) { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } else { id = hPlaces.getID(args[0]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[0] + " finnes ikke"); return true; } hPlaces.sendPlace(sender, id); return true; } } if (args.length == 2) { if (args[0].equalsIgnoreCase("spiller")) { sender.sendMessage(hPlaces.getOwned(args[1])); sender.sendMessage(hPlaces.getMembered(args[1])); return true; } if (args[0].equalsIgnoreCase("ny")) { sender.sendMessage(hPlaces.addPlace(player, args[1], "40")); return true; } id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } if (args[0].equalsIgnoreCase("flytt")) { sender.sendMessage(hPlaces.setPlace(player, id, "40")); return true; } else if (args[0].equalsIgnoreCase("spawn")) { player.teleport(hPlaces.getSpawn(id)); return true; } else if (args[0].equalsIgnoreCase("setspawn")) { sender.sendMessage(hPlaces.setSpawn(player, id)); return true; } else if (args[0].equalsIgnoreCase("slett")) { sender.sendMessage(hPlaces.remPlace(player, id)); return true; } else if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, "")); return true; } else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, "")); return true; } else if (args[0].equalsIgnoreCase("navn")) { sender.sendMessage(ThePlugin.c2 + "/plass navn <plass-navn> <nytt-plass-navn>"); return true; } else if (args[0].equalsIgnoreCase("toggle")) { sender.sendMessage(ThePlugin.c2 + "/plass toggle <plass-navn> <[pvp] [monstre] [dyr]>"); return true; } else if (args[0].equalsIgnoreCase("medlem")) { sender.sendMessage(ThePlugin.c2 + "/plass medlem <plass-navn> <spiller-navn>"); return true; } else if (args[0].equalsIgnoreCase("spark")) { sender.sendMessage(ThePlugin.c2 + "/plass spark <plass-navn> <spiller-navn>"); return true; } else if (args[0].equalsIgnoreCase("eier")) { sender.sendMessage(ThePlugin.c2 + "/plass eier <plass-navn> <spiller-navn>"); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else if (args.length == 3) { if (args[0].equalsIgnoreCase("ny")) { if (!args[2].matches("[0-9]+")) { sender.sendMessage(ThePlugin.c2 + "St�rrelsen m� defineres med tall"); return true; } sender.sendMessage(hPlaces.addPlace(player, args[1], args[2])); return true; } id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } if (args[0].equalsIgnoreCase("flytt")) { if (!args[2].matches("[0-9]+")) { sender.sendMessage(ThePlugin.c2 + "St�rrelsen m� defineres med tall"); return true; } sender.sendMessage(hPlaces.setPlace(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("navn")) { sender.sendMessage(hPlaces.setName(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("toggle")) { if (args[2].equalsIgnoreCase("pvp")) { sender.sendMessage(hPlaces.setPvP(player, id)); return true; } else if (args[2].equalsIgnoreCase("monstre")) { sender.sendMessage(hPlaces.setMonsters(player, id)); return true; } else if (args[2].equalsIgnoreCase("dyr")) { sender.sendMessage(hPlaces.setAnimals(player, id)); return true; } else { sender.sendMessage(ThePlugin.c2 + "Du m� skrive pvp/monstre/dyr"); return true; } } else if (args[0].equalsIgnoreCase("medlem")) { sender.sendMessage(hPlaces.addMember(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("spark")) { sender.sendMessage(hPlaces.remMember(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("eier")) { sender.sendMessage(hPlaces.setOwner(player, id, args[2])); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else if (args.length > 3 && (args[0].equalsIgnoreCase("entre") || args[0].equalsIgnoreCase("forlate"))) { id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } String arg = ""; for (int i = 2; i < args.length; i++) { arg = arg + args[i] + " "; } arg = arg.trim(); if (args[1].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, arg)); return true; } else if (args[1].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, arg)); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } }
public boolean place(CommandSender sender, Command cmd, String[] args) { HandlePlaces hPlaces = new HandlePlaces(); HelpCommand help = new HelpCommand(); Player player = Bukkit.getPlayer(sender.getName()); int id; if (!(sender instanceof Player)) { int check = 0; if (args.length == 0) { check = 1; } if((args.length == 1 || args.length == 2) && args[0].equalsIgnoreCase("spiller")) { check = 1; } if (args.length == 1 && !args[0].equalsIgnoreCase("her")) { check = 1; } if (check == 0) { sender.sendMessage(ThePlugin.c2 + "Consolen kan bare bruke /plass, /plass liste, /plass spiller <navn> og /plass <navn>"); return true; } } for (String arg : args) { if (!arg.matches("[a-zA-Z-_0-9������]+")) { sender.sendMessage(ThePlugin.c2 + "Tillatte tegn er a-� A-� 0-9 - _"); return true; } } if (args.length == 0) { help.customHelp(sender, cmd.getName(), "1", help()); return true; } else if (args.length == 1) { if (args[0].equalsIgnoreCase("liste")) { hPlaces.sendPlaceList(sender); return true; } else if (args[0].equalsIgnoreCase("spiller")) { hPlaces.sendPlayersPlaceList(sender); return true; } else if (args[0].equalsIgnoreCase("her")) { hPlaces.sendPlaceHere(sender); return true; } else if (args[0].length() == 1) { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } else { id = hPlaces.getID(args[0]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[0] + " finnes ikke"); return true; } hPlaces.sendPlace(sender, id); return true; } } if (args.length == 2) { if (args[0].equalsIgnoreCase("spiller")) { sender.sendMessage(hPlaces.getOwned(args[1])); sender.sendMessage(hPlaces.getMembered(args[1])); return true; } if (args[0].equalsIgnoreCase("ny")) { sender.sendMessage(hPlaces.addPlace(player, args[1], "40")); return true; } id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } if (args[0].equalsIgnoreCase("flytt")) { sender.sendMessage(hPlaces.setPlace(player, id, "40")); return true; } else if (args[0].equalsIgnoreCase("spawn")) { player.teleport(hPlaces.getSpawn(id)); return true; } else if (args[0].equalsIgnoreCase("setspawn")) { sender.sendMessage(hPlaces.setSpawn(player, id)); return true; } else if (args[0].equalsIgnoreCase("slett")) { sender.sendMessage(hPlaces.remPlace(player, id)); return true; } else if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, "")); return true; } else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, "")); return true; } else if (args[0].equalsIgnoreCase("navn")) { sender.sendMessage(ThePlugin.c2 + "/plass navn <plass-navn> <nytt-plass-navn>"); return true; } else if (args[0].equalsIgnoreCase("toggle")) { sender.sendMessage(ThePlugin.c2 + "/plass toggle <plass-navn> <[pvp] [monstre] [dyr]>"); return true; } else if (args[0].equalsIgnoreCase("medlem")) { sender.sendMessage(ThePlugin.c2 + "/plass medlem <plass-navn> <spiller-navn>"); return true; } else if (args[0].equalsIgnoreCase("spark")) { sender.sendMessage(ThePlugin.c2 + "/plass spark <plass-navn> <spiller-navn>"); return true; } else if (args[0].equalsIgnoreCase("eier")) { sender.sendMessage(ThePlugin.c2 + "/plass eier <plass-navn> <spiller-navn>"); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else if (args.length == 3) { if (args[0].equalsIgnoreCase("ny")) { if (!args[2].matches("[0-9]+")) { sender.sendMessage(ThePlugin.c2 + "St�rrelsen m� defineres med tall"); return true; } sender.sendMessage(hPlaces.addPlace(player, args[1], args[2])); return true; } id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } if (args[0].equalsIgnoreCase("flytt")) { if (!args[2].matches("[0-9]+")) { sender.sendMessage(ThePlugin.c2 + "St�rrelsen m� defineres med tall"); return true; } sender.sendMessage(hPlaces.setPlace(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("navn")) { sender.sendMessage(hPlaces.setName(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("toggle")) { if (args[2].equalsIgnoreCase("pvp")) { sender.sendMessage(hPlaces.setPvP(player, id)); return true; } else if (args[2].equalsIgnoreCase("monstre")) { sender.sendMessage(hPlaces.setMonsters(player, id)); return true; } else if (args[2].equalsIgnoreCase("dyr")) { sender.sendMessage(hPlaces.setAnimals(player, id)); return true; } else { sender.sendMessage(ThePlugin.c2 + "Du m� skrive pvp/monstre/dyr"); return true; } } else if (args[0].equalsIgnoreCase("medlem")) { sender.sendMessage(hPlaces.addMember(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("spark")) { sender.sendMessage(hPlaces.remMember(player, id, args[2])); return true; } else if (args[0].equalsIgnoreCase("eier")) { sender.sendMessage(hPlaces.setOwner(player, id, args[2])); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else if (args.length > 3 && (args[0].equalsIgnoreCase("entre") || args[0].equalsIgnoreCase("forlate"))) { id = hPlaces.getID(args[1]); if (id == 0) { sender.sendMessage(ThePlugin.c2 + args[1] + " finnes ikke"); return true; } String arg = ""; for (int i = 2; i < args.length; i++) { arg = arg + args[i] + " "; } arg = arg.trim(); if (args[0].equalsIgnoreCase("entre")) { sender.sendMessage(hPlaces.setEnter(player, id, arg)); return true; } else if (args[0].equalsIgnoreCase("forlate")) { sender.sendMessage(hPlaces.setLeave(player, id, arg)); return true; } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } } else { help.customHelp(sender, cmd.getName(), args[0], help()); return true; } }
diff --git a/source/de/anomic/crawler/retrieval/HTTPLoader.java b/source/de/anomic/crawler/retrieval/HTTPLoader.java index b49244cca..1d42f6f0e 100644 --- a/source/de/anomic/crawler/retrieval/HTTPLoader.java +++ b/source/de/anomic/crawler/retrieval/HTTPLoader.java @@ -1,222 +1,223 @@ //plasmaCrawlWorker.java //------------------------ //part of YaCy //(C) by Michael Peter Christen; [email protected] //first published on http://www.anomic.de //Frankfurt, Germany, 2006 // // $LastChangedDate: 2006-08-12 16:28:14 +0200 (Sa, 12 Aug 2006) $ // $LastChangedRevision: 2397 $ // $LastChangedBy: theli $ // //This program is free software; you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation; either version 2 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package de.anomic.crawler.retrieval; import java.io.IOException; import java.util.Date; import de.anomic.crawler.Latency; import de.anomic.data.Blacklist; import de.anomic.document.Parser; import de.anomic.http.client.Client; import de.anomic.http.metadata.HeaderFramework; import de.anomic.http.metadata.RequestHeader; import de.anomic.http.metadata.ResponseContainer; import de.anomic.search.Switchboard; import de.anomic.yacy.yacyURL; import de.anomic.yacy.logging.Log; public final class HTTPLoader { private static final String DEFAULT_ENCODING = "gzip,deflate"; private static final String DEFAULT_LANGUAGE = "en-us,en;q=0.5"; private static final String DEFAULT_CHARSET = "ISO-8859-1,utf-8;q=0.7,*;q=0.7"; private static final long DEFAULT_MAXFILESIZE = 1024 * 1024 * 10; public static final int DEFAULT_CRAWLING_RETRY_COUNT = 5; public static final String crawlerUserAgent = "yacybot (" + Client.getSystemOST() +") http://yacy.net/bot.html"; public static final String yacyUserAgent = "yacy (" + Client.getSystemOST() +") yacy.net"; /** * The socket timeout that should be used */ private final int socketTimeout; /** * The maximum allowed file size */ //private long maxFileSize = -1; //private String acceptEncoding; //private String acceptLanguage; //private String acceptCharset; private final Switchboard sb; private final Log log; public HTTPLoader(final Switchboard sb, final Log theLog) { this.sb = sb; this.log = theLog; // refreshing timeout value this.socketTimeout = (int) sb.getConfigLong("crawler.clientTimeout", 10000); } public Response load(final Request entry, final boolean acceptOnlyParseable) throws IOException { long start = System.currentTimeMillis(); Response doc = load(entry, acceptOnlyParseable, DEFAULT_CRAWLING_RETRY_COUNT); Latency.update(entry.url().hash().substring(6), entry.url().getHost(), System.currentTimeMillis() - start); return doc; } private Response load(final Request request, boolean acceptOnlyParseable, final int retryCount) throws IOException { if (retryCount < 0) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection counter exceeded").store(); throw new IOException("Redirection counter exceeded for URL " + request.url().toString() + ". Processing aborted."); } final String host = request.url().getHost(); + if (host == null || host.length() < 2) throw new IOException("host is not well-formed: '" + host + "'"); final String path = request.url().getFile(); int port = request.url().getPort(); final boolean ssl = request.url().getProtocol().equals("https"); if (port < 0) port = (ssl) ? 443 : 80; // if not the right file type then reject file if (acceptOnlyParseable) { String supportError = Parser.supportsExtension(request.url()); if (supportError != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, supportError); throw new IOException("REJECTED WRONG EXTENSION TYPE: " + supportError); } } // check if url is in blacklist final String hostlow = host.toLowerCase(); if (Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_CRAWLER, hostlow, path)) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "url in blacklist").store(); throw new IOException("CRAWLER Rejecting URL '" + request.url().toString() + "'. URL is in blacklist."); } // take a file from the net Response response = null; final long maxFileSize = sb.getConfigLong("crawler.http.maxFileSize", DEFAULT_MAXFILESIZE); // create a request header final RequestHeader requestHeader = new RequestHeader(); requestHeader.put(HeaderFramework.USER_AGENT, crawlerUserAgent); yacyURL refererURL = null; if (request.referrerhash() != null) refererURL = sb.getURL(request.referrerhash()); if (refererURL != null) requestHeader.put(RequestHeader.REFERER, refererURL.toNormalform(true, true)); requestHeader.put(HeaderFramework.ACCEPT_LANGUAGE, sb.getConfig("crawler.http.acceptLanguage", DEFAULT_LANGUAGE)); requestHeader.put(HeaderFramework.ACCEPT_CHARSET, sb.getConfig("crawler.http.acceptCharset", DEFAULT_CHARSET)); requestHeader.put(HeaderFramework.ACCEPT_ENCODING, sb.getConfig("crawler.http.acceptEncoding", DEFAULT_ENCODING)); // HTTP-Client final Client client = new Client(socketTimeout, requestHeader); ResponseContainer res = null; try { // send request res = client.GET(request.url().toString(), maxFileSize); // FIXME: 30*-handling (bottom) is never reached // we always get the final content because httpClient.followRedirects = true if (res.getStatusCode() == 200 || res.getStatusCode() == 203) { // the transfer is ok if (acceptOnlyParseable) { // if the response has not the right file type then reject file String supportError = Parser.supports(request.url(), res.getResponseHeader().mime()); if (supportError != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, supportError); throw new IOException("REJECTED WRONG MIME TYPE: " + supportError); } } // we write the new cache entry to file system directly res.setAccountingName("CRAWLER"); final byte[] responseBody = res.getData(); long contentLength = responseBody.length; // check length again in case it was not possible to get the length before loading if (maxFileSize > 0 && contentLength > maxFileSize) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "file size limit exceeded"); throw new IOException("REJECTED URL " + request.url() + " because file size '" + contentLength + "' exceeds max filesize limit of " + maxFileSize + " bytes. (GET)"); } // create a new cache entry response = new Response( request, requestHeader, res.getResponseHeader(), res.getStatusLine(), sb.crawler.profilesActiveCrawls.getEntry(request.profileHandle()), responseBody ); return response; } else if (res.getStatusLine().startsWith("30")) { if (res.getResponseHeader().containsKey(HeaderFramework.LOCATION)) { // getting redirection URL String redirectionUrlString = res.getResponseHeader().get(HeaderFramework.LOCATION); redirectionUrlString = redirectionUrlString.trim(); if (redirectionUrlString.length() == 0) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection header empy"); throw new IOException("CRAWLER Redirection of URL=" + request.url().toString() + " aborted. Location header is empty."); } // normalizing URL final yacyURL redirectionUrl = yacyURL.newURL(request.url(), redirectionUrlString); // restart crawling with new url this.log.logInfo("CRAWLER Redirection detected ('" + res.getStatusLine() + "') for URL " + request.url().toString()); this.log.logInfo("CRAWLER ..Redirecting request to: " + redirectionUrl); // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "server shutdown"); throw new IOException("CRAWLER Retry of URL=" + request.url().toString() + " aborted because of server shutdown."); } // generating url hash final String urlhash = redirectionUrl.hash(); // check if the url was already indexed final String dbname = sb.urlExists(urlhash); if (dbname != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection to double content"); throw new IOException("CRAWLER Redirection of URL=" + request.url().toString() + " ignored. The url appears already in db " + dbname); } // retry crawling with new url request.redirectURL(redirectionUrl); return load(request, acceptOnlyParseable, retryCount - 1); } } else { // if the response has not the right response type then reject file sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "wrong http status code " + res.getStatusCode() + ")"); throw new IOException("REJECTED WRONG STATUS TYPE '" + res.getStatusLine() + "' for URL " + request.url().toString()); } } finally { if(res != null) { // release connection res.closeStream(); } } return response; } }
true
true
private Response load(final Request request, boolean acceptOnlyParseable, final int retryCount) throws IOException { if (retryCount < 0) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection counter exceeded").store(); throw new IOException("Redirection counter exceeded for URL " + request.url().toString() + ". Processing aborted."); } final String host = request.url().getHost(); final String path = request.url().getFile(); int port = request.url().getPort(); final boolean ssl = request.url().getProtocol().equals("https"); if (port < 0) port = (ssl) ? 443 : 80; // if not the right file type then reject file if (acceptOnlyParseable) { String supportError = Parser.supportsExtension(request.url()); if (supportError != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, supportError); throw new IOException("REJECTED WRONG EXTENSION TYPE: " + supportError); } } // check if url is in blacklist final String hostlow = host.toLowerCase(); if (Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_CRAWLER, hostlow, path)) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "url in blacklist").store(); throw new IOException("CRAWLER Rejecting URL '" + request.url().toString() + "'. URL is in blacklist."); } // take a file from the net Response response = null; final long maxFileSize = sb.getConfigLong("crawler.http.maxFileSize", DEFAULT_MAXFILESIZE); // create a request header final RequestHeader requestHeader = new RequestHeader(); requestHeader.put(HeaderFramework.USER_AGENT, crawlerUserAgent); yacyURL refererURL = null; if (request.referrerhash() != null) refererURL = sb.getURL(request.referrerhash()); if (refererURL != null) requestHeader.put(RequestHeader.REFERER, refererURL.toNormalform(true, true)); requestHeader.put(HeaderFramework.ACCEPT_LANGUAGE, sb.getConfig("crawler.http.acceptLanguage", DEFAULT_LANGUAGE)); requestHeader.put(HeaderFramework.ACCEPT_CHARSET, sb.getConfig("crawler.http.acceptCharset", DEFAULT_CHARSET)); requestHeader.put(HeaderFramework.ACCEPT_ENCODING, sb.getConfig("crawler.http.acceptEncoding", DEFAULT_ENCODING)); // HTTP-Client final Client client = new Client(socketTimeout, requestHeader); ResponseContainer res = null; try { // send request res = client.GET(request.url().toString(), maxFileSize); // FIXME: 30*-handling (bottom) is never reached // we always get the final content because httpClient.followRedirects = true if (res.getStatusCode() == 200 || res.getStatusCode() == 203) { // the transfer is ok if (acceptOnlyParseable) { // if the response has not the right file type then reject file String supportError = Parser.supports(request.url(), res.getResponseHeader().mime()); if (supportError != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, supportError); throw new IOException("REJECTED WRONG MIME TYPE: " + supportError); } } // we write the new cache entry to file system directly res.setAccountingName("CRAWLER"); final byte[] responseBody = res.getData(); long contentLength = responseBody.length; // check length again in case it was not possible to get the length before loading if (maxFileSize > 0 && contentLength > maxFileSize) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "file size limit exceeded"); throw new IOException("REJECTED URL " + request.url() + " because file size '" + contentLength + "' exceeds max filesize limit of " + maxFileSize + " bytes. (GET)"); } // create a new cache entry response = new Response( request, requestHeader, res.getResponseHeader(), res.getStatusLine(), sb.crawler.profilesActiveCrawls.getEntry(request.profileHandle()), responseBody ); return response; } else if (res.getStatusLine().startsWith("30")) { if (res.getResponseHeader().containsKey(HeaderFramework.LOCATION)) { // getting redirection URL String redirectionUrlString = res.getResponseHeader().get(HeaderFramework.LOCATION); redirectionUrlString = redirectionUrlString.trim(); if (redirectionUrlString.length() == 0) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection header empy"); throw new IOException("CRAWLER Redirection of URL=" + request.url().toString() + " aborted. Location header is empty."); } // normalizing URL final yacyURL redirectionUrl = yacyURL.newURL(request.url(), redirectionUrlString); // restart crawling with new url this.log.logInfo("CRAWLER Redirection detected ('" + res.getStatusLine() + "') for URL " + request.url().toString()); this.log.logInfo("CRAWLER ..Redirecting request to: " + redirectionUrl); // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "server shutdown"); throw new IOException("CRAWLER Retry of URL=" + request.url().toString() + " aborted because of server shutdown."); } // generating url hash final String urlhash = redirectionUrl.hash(); // check if the url was already indexed final String dbname = sb.urlExists(urlhash); if (dbname != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection to double content"); throw new IOException("CRAWLER Redirection of URL=" + request.url().toString() + " ignored. The url appears already in db " + dbname); } // retry crawling with new url request.redirectURL(redirectionUrl); return load(request, acceptOnlyParseable, retryCount - 1); } } else { // if the response has not the right response type then reject file sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "wrong http status code " + res.getStatusCode() + ")"); throw new IOException("REJECTED WRONG STATUS TYPE '" + res.getStatusLine() + "' for URL " + request.url().toString()); } } finally { if(res != null) { // release connection res.closeStream(); } } return response; }
private Response load(final Request request, boolean acceptOnlyParseable, final int retryCount) throws IOException { if (retryCount < 0) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection counter exceeded").store(); throw new IOException("Redirection counter exceeded for URL " + request.url().toString() + ". Processing aborted."); } final String host = request.url().getHost(); if (host == null || host.length() < 2) throw new IOException("host is not well-formed: '" + host + "'"); final String path = request.url().getFile(); int port = request.url().getPort(); final boolean ssl = request.url().getProtocol().equals("https"); if (port < 0) port = (ssl) ? 443 : 80; // if not the right file type then reject file if (acceptOnlyParseable) { String supportError = Parser.supportsExtension(request.url()); if (supportError != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, supportError); throw new IOException("REJECTED WRONG EXTENSION TYPE: " + supportError); } } // check if url is in blacklist final String hostlow = host.toLowerCase(); if (Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_CRAWLER, hostlow, path)) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "url in blacklist").store(); throw new IOException("CRAWLER Rejecting URL '" + request.url().toString() + "'. URL is in blacklist."); } // take a file from the net Response response = null; final long maxFileSize = sb.getConfigLong("crawler.http.maxFileSize", DEFAULT_MAXFILESIZE); // create a request header final RequestHeader requestHeader = new RequestHeader(); requestHeader.put(HeaderFramework.USER_AGENT, crawlerUserAgent); yacyURL refererURL = null; if (request.referrerhash() != null) refererURL = sb.getURL(request.referrerhash()); if (refererURL != null) requestHeader.put(RequestHeader.REFERER, refererURL.toNormalform(true, true)); requestHeader.put(HeaderFramework.ACCEPT_LANGUAGE, sb.getConfig("crawler.http.acceptLanguage", DEFAULT_LANGUAGE)); requestHeader.put(HeaderFramework.ACCEPT_CHARSET, sb.getConfig("crawler.http.acceptCharset", DEFAULT_CHARSET)); requestHeader.put(HeaderFramework.ACCEPT_ENCODING, sb.getConfig("crawler.http.acceptEncoding", DEFAULT_ENCODING)); // HTTP-Client final Client client = new Client(socketTimeout, requestHeader); ResponseContainer res = null; try { // send request res = client.GET(request.url().toString(), maxFileSize); // FIXME: 30*-handling (bottom) is never reached // we always get the final content because httpClient.followRedirects = true if (res.getStatusCode() == 200 || res.getStatusCode() == 203) { // the transfer is ok if (acceptOnlyParseable) { // if the response has not the right file type then reject file String supportError = Parser.supports(request.url(), res.getResponseHeader().mime()); if (supportError != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, supportError); throw new IOException("REJECTED WRONG MIME TYPE: " + supportError); } } // we write the new cache entry to file system directly res.setAccountingName("CRAWLER"); final byte[] responseBody = res.getData(); long contentLength = responseBody.length; // check length again in case it was not possible to get the length before loading if (maxFileSize > 0 && contentLength > maxFileSize) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "file size limit exceeded"); throw new IOException("REJECTED URL " + request.url() + " because file size '" + contentLength + "' exceeds max filesize limit of " + maxFileSize + " bytes. (GET)"); } // create a new cache entry response = new Response( request, requestHeader, res.getResponseHeader(), res.getStatusLine(), sb.crawler.profilesActiveCrawls.getEntry(request.profileHandle()), responseBody ); return response; } else if (res.getStatusLine().startsWith("30")) { if (res.getResponseHeader().containsKey(HeaderFramework.LOCATION)) { // getting redirection URL String redirectionUrlString = res.getResponseHeader().get(HeaderFramework.LOCATION); redirectionUrlString = redirectionUrlString.trim(); if (redirectionUrlString.length() == 0) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection header empy"); throw new IOException("CRAWLER Redirection of URL=" + request.url().toString() + " aborted. Location header is empty."); } // normalizing URL final yacyURL redirectionUrl = yacyURL.newURL(request.url(), redirectionUrlString); // restart crawling with new url this.log.logInfo("CRAWLER Redirection detected ('" + res.getStatusLine() + "') for URL " + request.url().toString()); this.log.logInfo("CRAWLER ..Redirecting request to: " + redirectionUrl); // if we are already doing a shutdown we don't need to retry crawling if (Thread.currentThread().isInterrupted()) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "server shutdown"); throw new IOException("CRAWLER Retry of URL=" + request.url().toString() + " aborted because of server shutdown."); } // generating url hash final String urlhash = redirectionUrl.hash(); // check if the url was already indexed final String dbname = sb.urlExists(urlhash); if (dbname != null) { sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "redirection to double content"); throw new IOException("CRAWLER Redirection of URL=" + request.url().toString() + " ignored. The url appears already in db " + dbname); } // retry crawling with new url request.redirectURL(redirectionUrl); return load(request, acceptOnlyParseable, retryCount - 1); } } else { // if the response has not the right response type then reject file sb.crawlQueues.errorURL.newEntry(request, sb.peers.mySeed().hash, new Date(), 1, "wrong http status code " + res.getStatusCode() + ")"); throw new IOException("REJECTED WRONG STATUS TYPE '" + res.getStatusLine() + "' for URL " + request.url().toString()); } } finally { if(res != null) { // release connection res.closeStream(); } } return response; }
diff --git a/src/main/java/net/sf/testium/plugins/SeleniumPlugin.java b/src/main/java/net/sf/testium/plugins/SeleniumPlugin.java index 8030e0e..0e5ce5d 100644 --- a/src/main/java/net/sf/testium/plugins/SeleniumPlugin.java +++ b/src/main/java/net/sf/testium/plugins/SeleniumPlugin.java @@ -1,298 +1,298 @@ package net.sf.testium.plugins; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import net.sf.testium.Testium; import net.sf.testium.configuration.ConfigurationException; import net.sf.testium.configuration.CustomStepDefinitionsXmlHandler; import net.sf.testium.configuration.PersonalSeleniumConfigurationXmlHandler; import net.sf.testium.configuration.SeleniumConfiguration; import net.sf.testium.configuration.SeleniumConfiguration.BROWSER_TYPE; import net.sf.testium.configuration.SeleniumConfigurationXmlHandler; import net.sf.testium.configuration.SeleniumInterfaceConfiguration; import net.sf.testium.configuration.SeleniumInterfaceXmlHandler; import net.sf.testium.executor.CustomInterface; import net.sf.testium.executor.DefaultInterface; import net.sf.testium.executor.SupportedInterfaceList; import net.sf.testium.executor.TestStepMetaExecutor; import net.sf.testium.executor.webdriver.WebInterface; import net.sf.testium.executor.webdriver.commands.CheckListSize_modified; import net.sf.testium.executor.webdriver.commands.GetListItem_modified; import net.sf.testium.executor.webdriver.commands.GetListSize_modified; import org.testtoolinterfaces.testsuite.TestInterfaceList; import org.testtoolinterfaces.utils.RunTimeData; import org.testtoolinterfaces.utils.TTIException; import org.testtoolinterfaces.utils.Trace; import org.testtoolinterfaces.utils.XmlHandler; import org.xml.sax.XMLReader; /** * @author Arjan Kranenburg * */ public class SeleniumPlugin implements Plugin { public static final String BASEURL = "BaseUrl"; public SeleniumPlugin() { // nop } public void loadPlugIn( PluginCollection aPluginCollection, RunTimeData anRtData ) throws ConfigurationException { // Interfaces SupportedInterfaceList interfaceList = aPluginCollection.getInterfaces(); TestStepMetaExecutor testStepMetaExecutor = aPluginCollection.getTestStepExecutor(); SeleniumConfiguration config = readConfigFile( anRtData ); File seleniumLibsDir = config.getSeleniumLibsDir(); try { PluginClassLoader.addDirToClassLoader( seleniumLibsDir ); } catch (MalformedURLException e) { throw new ConfigurationException( e ); } DefaultInterface defInterface = (DefaultInterface) interfaceList.getInterface(DefaultInterface.NAME); defInterface.add( new CheckListSize_modified( defInterface ) ); defInterface.add( new GetListItem_modified( defInterface ) ); defInterface.add( new GetListSize_modified( defInterface ) ); createInterfaces(anRtData, interfaceList, testStepMetaExecutor, config); } /** * @param anRtData * @param anInterfaceList * @param aTestStepMetaExecutor * @param aConfig * @throws ConfigurationException */ private void createInterfaces(RunTimeData anRtData, SupportedInterfaceList anInterfaceList, TestStepMetaExecutor aTestStepMetaExecutor, SeleniumConfiguration aConfig) throws ConfigurationException { Iterator<String> interfaceNamesItr = aConfig.getInterfaceNames().iterator(); while ( interfaceNamesItr.hasNext() ) { String interfaceName = interfaceNamesItr.next(); createInterface(anRtData, anInterfaceList, aTestStepMetaExecutor, aConfig, interfaceName); } } /** * @param anRtData * @param anInterfaceList * @param aTestStepMetaExecutor * @param aConfig * @param anInterfaceName * @throws ConfigurationException */ private void createInterface(RunTimeData anRtData, SupportedInterfaceList anInterfaceList, TestStepMetaExecutor aTestStepMetaExecutor, SeleniumConfiguration aConfig, String anInterfaceName) throws ConfigurationException { File configDir = (File) anRtData.getValue(Testium.CONFIGDIR); File interfaceDefinitionsFile = new File( configDir, anInterfaceName + ".xml" ); SeleniumInterfaceConfiguration tmpIfConfig = new SeleniumInterfaceConfiguration(anInterfaceName, aConfig.getBrowserType()); SeleniumInterfaceConfiguration globalIfConfig = readInterfaceDefintions( interfaceDefinitionsFile, tmpIfConfig ); File userConfigDir = (File) anRtData.getValue(Testium.USERCONFIGDIR); File personalInterfaceDefinitionsFile = new File( userConfigDir, anInterfaceName + ".xml" ); SeleniumInterfaceConfiguration ifConfig = globalIfConfig; if ( personalInterfaceDefinitionsFile.canRead() ) { ifConfig = readInterfaceDefintions( personalInterfaceDefinitionsFile, globalIfConfig ); } ifConfig.setSeleniumGridUrl( aConfig.getSeleniumGridUrl() ); - String sysPropBaseUrl = System.getProperty( anInterfaceName + SeleniumPlugin.BASEURL ); + String sysPropBaseUrl = System.getProperty( anInterfaceName + "." + SeleniumPlugin.BASEURL ); if ( sysPropBaseUrl != null ) { ifConfig.setBaseUrl( sysPropBaseUrl ); } WebInterface iface = new WebInterface( anInterfaceName, anRtData, ifConfig ); anInterfaceList.add(iface); createCustomKeywords(anRtData, anInterfaceList, aTestStepMetaExecutor, ifConfig, iface); } /** * @param anRtData * @param interfaceList * @param testStepMetaExecutor * @param ifConfig * @param iface * @throws ConfigurationException */ private void createCustomKeywords(RunTimeData anRtData, SupportedInterfaceList interfaceList, TestStepMetaExecutor testStepMetaExecutor, SeleniumInterfaceConfiguration ifConfig, WebInterface iface) throws ConfigurationException { Iterator<String> keywordsDefLinksItr = ifConfig.getCustomKeywordLinks().iterator(); while ( keywordsDefLinksItr.hasNext() ) { String keywordsDefLink = keywordsDefLinksItr.next(); String fileName = anRtData.substituteVars(keywordsDefLink); CustomStepDefinitionsXmlHandler.loadElementDefinitions( new File( fileName ), anRtData, iface, interfaceList, testStepMetaExecutor ); } } // private SeleniumInterfaceConfiguration readInterfaceDefintions( String anInterfaceName, // RunTimeData anRtData, // SeleniumConfiguration aConfig ) throws ConfigurationException { // Trace.println(Trace.UTIL, "readInterfaceDefintions( " + anInterfaceName + " )", true ); // // File configDir = (File) anRtData.getValue(Testium.CONFIGDIR); // File interfaceDefinitionsFile = new File( configDir, anInterfaceName + ".xml" ); // // SeleniumInterfaceXmlHandler handler = null; // try { // XMLReader reader = XmlHandler.getNewXmlReader(); // handler = new SeleniumInterfaceXmlHandler( reader ); // // handler.parse(reader, interfaceDefinitionsFile); // } catch (TTIException e) { // throw new ConfigurationException( e ); // } // // SeleniumInterfaceConfiguration tmpIfConfig = new SeleniumInterfaceConfiguration(anInterfaceName, aConfig.getBrowserType()); //// TODO tmpIfConfig.setSavePageSource( aConfig.getSave...()); // SeleniumInterfaceConfiguration ifConfiguration = handler.getConfiguration(tmpIfConfig); // handler.reset(); // // return ifConfiguration; // } private SeleniumInterfaceConfiguration readInterfaceDefintions( File interfaceDefinitionsFile, SeleniumInterfaceConfiguration tmpIfConfig) throws ConfigurationException { Trace.println(Trace.UTIL, "readInterfaceDefintions( " + tmpIfConfig.getInterfaceName() + " )", true ); SeleniumInterfaceXmlHandler handler = null; try { XMLReader reader = XmlHandler.getNewXmlReader(); handler = new SeleniumInterfaceXmlHandler( reader ); handler.parse(reader, interfaceDefinitionsFile); } catch (TTIException e) { throw new ConfigurationException( e ); } // TODO tmpIfConfig.setSavePageSource( aConfig.getSave...()); SeleniumInterfaceConfiguration ifConfiguration = handler.getConfiguration(tmpIfConfig); handler.reset(); return ifConfiguration; } public final SeleniumConfiguration readConfigFile( RunTimeData anRtData ) throws ConfigurationException { Trace.println(Trace.UTIL); File configDir = (File) anRtData.getValue(Testium.CONFIGDIR); File configFile = new File( configDir, "selenium.xml" ); SeleniumConfiguration config = readConfigFile( anRtData, configFile ); BROWSER_TYPE browserType = config.getBrowserType(); URL gridUrl = config.getSeleniumGridUrl(); File userConfigDir = (File) anRtData.getValue(Testium.USERCONFIGDIR); File userConfigFile = new File( userConfigDir, "selenium.xml" ); if ( userConfigFile.exists() ) { SeleniumConfiguration userConfig = readPersonalConfigFile( anRtData, userConfigFile ); if ( userConfig.getBrowserType() != null ) { browserType = userConfig.getBrowserType(); } if ( userConfig.getSeleniumGridUrl() != null ) { gridUrl = userConfig.getSeleniumGridUrl(); } } return new SeleniumConfiguration(config.getInterfaceNames(), browserType, config.getSeleniumLibsDir(), gridUrl); } public final SeleniumConfiguration readConfigFile( RunTimeData anRtData, File aConfigFile ) throws ConfigurationException { Trace.println(Trace.UTIL, "readConfigFile( " + aConfigFile.getName() + " )", true ); SeleniumConfigurationXmlHandler myHandler; try { XMLReader reader = XmlHandler.getNewXmlReader(); myHandler = new SeleniumConfigurationXmlHandler(reader, anRtData); myHandler.parse(reader, aConfigFile); } catch (TTIException e) { Trace.print(Trace.UTIL, e); throw new ConfigurationException(e); } SeleniumConfiguration configuration = myHandler.getConfiguration(); return configuration; } public final SeleniumConfiguration readPersonalConfigFile( RunTimeData anRtData, File aConfigFile ) throws ConfigurationException { Trace.println(Trace.UTIL, "readConfigFile( " + aConfigFile.getName() + " )", true ); PersonalSeleniumConfigurationXmlHandler myHandler; try { XMLReader reader = XmlHandler.getNewXmlReader(); myHandler = new PersonalSeleniumConfigurationXmlHandler(reader, anRtData); myHandler.parse(reader, aConfigFile); } catch (TTIException e) { Trace.print(Trace.UTIL, e); throw new ConfigurationException(e); } SeleniumConfiguration configuration = myHandler.getConfiguration(); return configuration; } public static void loadElementDefinitions( File aFile, RunTimeData anRtData, CustomInterface anInterface, TestInterfaceList anInterfaceList, TestStepMetaExecutor aTestStepMetaExecutor ) throws ConfigurationException { Trace.println(Trace.UTIL, "loadElementDefinitions( " + aFile.getName() + " )", true ); CustomStepDefinitionsXmlHandler handler = null; try { XMLReader reader = XmlHandler.getNewXmlReader(); handler = new CustomStepDefinitionsXmlHandler( reader, anRtData, anInterface, anInterfaceList, aTestStepMetaExecutor ); handler.parse(reader, aFile); } catch (TTIException e) { Trace.print(Trace.UTIL, e); throw new ConfigurationException(e); } } }
true
true
private void createInterface(RunTimeData anRtData, SupportedInterfaceList anInterfaceList, TestStepMetaExecutor aTestStepMetaExecutor, SeleniumConfiguration aConfig, String anInterfaceName) throws ConfigurationException { File configDir = (File) anRtData.getValue(Testium.CONFIGDIR); File interfaceDefinitionsFile = new File( configDir, anInterfaceName + ".xml" ); SeleniumInterfaceConfiguration tmpIfConfig = new SeleniumInterfaceConfiguration(anInterfaceName, aConfig.getBrowserType()); SeleniumInterfaceConfiguration globalIfConfig = readInterfaceDefintions( interfaceDefinitionsFile, tmpIfConfig ); File userConfigDir = (File) anRtData.getValue(Testium.USERCONFIGDIR); File personalInterfaceDefinitionsFile = new File( userConfigDir, anInterfaceName + ".xml" ); SeleniumInterfaceConfiguration ifConfig = globalIfConfig; if ( personalInterfaceDefinitionsFile.canRead() ) { ifConfig = readInterfaceDefintions( personalInterfaceDefinitionsFile, globalIfConfig ); } ifConfig.setSeleniumGridUrl( aConfig.getSeleniumGridUrl() ); String sysPropBaseUrl = System.getProperty( anInterfaceName + SeleniumPlugin.BASEURL ); if ( sysPropBaseUrl != null ) { ifConfig.setBaseUrl( sysPropBaseUrl ); } WebInterface iface = new WebInterface( anInterfaceName, anRtData, ifConfig ); anInterfaceList.add(iface); createCustomKeywords(anRtData, anInterfaceList, aTestStepMetaExecutor, ifConfig, iface); }
private void createInterface(RunTimeData anRtData, SupportedInterfaceList anInterfaceList, TestStepMetaExecutor aTestStepMetaExecutor, SeleniumConfiguration aConfig, String anInterfaceName) throws ConfigurationException { File configDir = (File) anRtData.getValue(Testium.CONFIGDIR); File interfaceDefinitionsFile = new File( configDir, anInterfaceName + ".xml" ); SeleniumInterfaceConfiguration tmpIfConfig = new SeleniumInterfaceConfiguration(anInterfaceName, aConfig.getBrowserType()); SeleniumInterfaceConfiguration globalIfConfig = readInterfaceDefintions( interfaceDefinitionsFile, tmpIfConfig ); File userConfigDir = (File) anRtData.getValue(Testium.USERCONFIGDIR); File personalInterfaceDefinitionsFile = new File( userConfigDir, anInterfaceName + ".xml" ); SeleniumInterfaceConfiguration ifConfig = globalIfConfig; if ( personalInterfaceDefinitionsFile.canRead() ) { ifConfig = readInterfaceDefintions( personalInterfaceDefinitionsFile, globalIfConfig ); } ifConfig.setSeleniumGridUrl( aConfig.getSeleniumGridUrl() ); String sysPropBaseUrl = System.getProperty( anInterfaceName + "." + SeleniumPlugin.BASEURL ); if ( sysPropBaseUrl != null ) { ifConfig.setBaseUrl( sysPropBaseUrl ); } WebInterface iface = new WebInterface( anInterfaceName, anRtData, ifConfig ); anInterfaceList.add(iface); createCustomKeywords(anRtData, anInterfaceList, aTestStepMetaExecutor, ifConfig, iface); }
diff --git a/app/query/QueryHelper.java b/app/query/QueryHelper.java index eaa55e9..6fe4239 100644 --- a/app/query/QueryHelper.java +++ b/app/query/QueryHelper.java @@ -1,356 +1,356 @@ package query; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.Query; import models.UsageLog; import play.Logger; import play.db.jpa.JPA; import util.Utils; /** * Helper class defining DB finder methods used in the application * * @author Paolo Di Tommaso * * */ public class QueryHelper { /** * Find the minimum and maximum creation dates in the usage log * * @return a <min, max> dates pair using a {@link MinMaxDate} instance or null if no data is available */ public static MinMaxDate findUsageMinMaxDate() { Query query = JPA.em().createQuery( "select " + " new query.MinMaxDate( min(log.creation), max(log.creation) )" + "from " + " UsageLog log " ); return (MinMaxDate) query.getSingleResult(); } /** * Find the minimum creation date in the usage log * * @return the min @{link Date} instance or null if no data is available */ public static Date findUsageMinDate() { MinMaxDate result = findUsageMinMaxDate(); return result != null ? result.min : null; } /** * Find the maximum creation date in the usage log * * @return the min @{link Date} instance or null if no data is available */ public static Date findUsageMaxDate() { MinMaxDate result = findUsageMinMaxDate(); return result != null ? result.max : null; } /** * Fetch the dataset to be shoed in the usage grid control * * @param filter * @param page the page index when pagination is used, the first page starts from 1 * @param size the maximum number of records that a page can contain * @param sortfield * @param sortorder * @param qvalue * @param qfield * @return */ public static GridResult findUsageGridData( UsageFilter filter, int page, int size, String sortfield, String sortorder, String qvalue, String qfield ) { int skip = (page>0 && size>0 ) ? (page-1) * size : -1; QueryBuilder where = new QueryBuilder(UsageLog.class); /* * 1. counting */ /* apply filter restrictions */ if( filter!=null && Utils.isNotEmpty(filter.bundle)) { where.and( "bundle", "like", filter.bundle ); } if( filter!=null && Utils.isNotEmpty(filter.service)) { where.and( "service", "like", filter.service ); } if( filter!=null && Utils.isNotEmpty(filter.status)) { where.and( "status", "=", filter.status); } if( filter!=null && filter.since!=null) { where.and( "creation", ">=", filter.since); } if( filter!=null && filter.until!=null) { Date end = new Date( filter.until.getTime() + 24L * 3600 * 1000 ); where.and( "creation", "<", end); } /* * more restrictions specified by the grid control */ if( "bundle".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "bundle", "like", qvalue ); } else if( "service".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "service", "like", qvalue ); } else if( "creation".equals(qfield) && Utils.isNotEmpty(qvalue) ) { Date date = Utils.parseDate(qvalue, null); if( date != null ) { where.and( "creation", "=", date ); } else { Logger.warn("Invalid date format: %s", qvalue); } } else if( "ip".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "ip", "like", qvalue ); } else if( "rid".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "requestId", "like", qvalue ); } else if( "email".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "email", "like", qvalue ); } else if( "source".equals(qfield) && Utils.isNotEmpty(qvalue) ) { - where.and( "source", "=", qvalue ); + where.and( "source", "like", qvalue ); } else if( "status".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "status", "=", qvalue ); } /* * counting the total result items */ GridResult result = new GridResult(); Query query = JPA.em().createQuery("select count(*) " + where.toString()); // append the params where.setParams(query); // execute the query and get the COUNT result.total = (Long) query.getSingleResult(); /* * 2. fetch result set * define the ordering */ if( Utils.isNotEmpty(sortfield) && !"undefined".equals(sortfield) && !"null".equals(sortfield) ) { if( sortfield.equals("duration") ) { // 'duration' is the formatted version of the field 'elapsed' sortfield = "elapsed"; } where.order(sortfield, !"desc".equals(sortorder) ); } /* * find the rows */ query = JPA.em().createQuery(where.toString()); if( skip > 0 ) { query.setFirstResult(skip); } if( size > 0 ) { query.setMaxResults(size); } where.setParams(query); result.rows = query.getResultList(); return result; } public static List<Object[]> findUsageAggregation(UsageFilter filter) { String select = "select " + " count(*), " + " log.bundle, " + " log.service," + " log.status," + " PARSEDATETIME( FORMATDATETIME(log.creation,'yyyy-MM-dd'), 'yyyy-MM-dd' ) _creation "; QueryBuilder where = new QueryBuilder( "from USAGE_LOG log " ); /* apply filter restrictions */ if( filter!=null && Utils.isNotEmpty(filter.bundle)) { where.and( "log.bundle", "like", filter.bundle ); } if( filter!=null && Utils.isNotEmpty(filter.service)) { where.and( "log.service", "like", filter.service ); } if( filter!=null && Utils.isNotEmpty(filter.status)) { where.and( "log.status", "=", filter.status); } if( filter!=null && filter.since!=null) { where.and( "log.creation", ">=", filter.since); } if( filter!=null && filter.until!=null) { Date end = new Date( filter.until.getTime() + 24L * 3600 * 1000 ); where.and( "log.creation", "<", end); } /* group by condition */ String groupby = " group by " + " log.bundle, log.service, log.status, _creation "; Query query = JPA.em().createNativeQuery( select + where + groupby ); // set the restrictions params where.setParams(query); /* return the result */ return query.getResultList(); } /* helper class to add 'and' restriction */ static class QueryBuilder { StringBuilder string; boolean first=true; List<Object> params; public QueryBuilder( Class clazz ) { params = new ArrayList<Object>(); string = new StringBuilder("from "); string. append( clazz.getSimpleName() ); } public QueryBuilder( String from ) { params = new ArrayList<Object>(); string = new StringBuilder(from); } QueryBuilder and( String field, String condition, Object value ) { if( Utils.isEmpty(field)) { return this; } /* * add the valid query separator 'and' or 'where' */ if( first ) { first = false; string.append( " where "); } else { string.append( " and " ); } /* appent the restriction */ string.append(field) .append(" ") .append(condition) .append(" ") .append("?"); /* save the param value */ params.add(value); return this; } public QueryBuilder order( String field, boolean asc ) { if( Utils.isEmpty(field) ) { return this; } string .append(" ") .append("order by ") .append( field ) .append( asc ? " asc" : " desc" ); return this; } public String toString() { return string.toString(); } public void setParams(Query query) { for( int i=0; i<params.size(); i++ ) { query.setParameter(i+1, params.get(i)); } } } /** * Fetchs the usage count for all bundle/service in the applicaton log * * @return a list of {@link BundleServiceCount} */ public static List<BundleServiceCount> findUsageBundleServiceCounts () { String sQuery = "select new query.BundleServiceCount(" + " log.bundle, " + " log.service, " + " count(*) " + ") " + "from " + " UsageLog log " + "group by " + " log.bundle, log.service "; List<BundleServiceCount> result = JPA.em().createQuery(sQuery) .getResultList(); return result != null ? result : Collections.EMPTY_LIST; } /** * @return a map containing the available services for each bundle in the usage log */ public static Map<String,List<String>> findUsageServiceMap() { List<BundleServiceCount> list = findUsageBundleServiceCounts(); return findUsageServiceMap(list); } static Map<String,List<String>> findUsageServiceMap(List<BundleServiceCount> list) { /* * 1. group by bundle name */ Map<String,List<String>> aggregate = new HashMap<String, List<String>>(); for( BundleServiceCount item : list ) { List<String> services = aggregate.get(item.bundle); if( services == null ) { services = new ArrayList<String>(); aggregate.put(item.bundle,services); } if( !services.contains(item.service) ) { services.add(item.service); } } return aggregate; } }
true
true
public static GridResult findUsageGridData( UsageFilter filter, int page, int size, String sortfield, String sortorder, String qvalue, String qfield ) { int skip = (page>0 && size>0 ) ? (page-1) * size : -1; QueryBuilder where = new QueryBuilder(UsageLog.class); /* * 1. counting */ /* apply filter restrictions */ if( filter!=null && Utils.isNotEmpty(filter.bundle)) { where.and( "bundle", "like", filter.bundle ); } if( filter!=null && Utils.isNotEmpty(filter.service)) { where.and( "service", "like", filter.service ); } if( filter!=null && Utils.isNotEmpty(filter.status)) { where.and( "status", "=", filter.status); } if( filter!=null && filter.since!=null) { where.and( "creation", ">=", filter.since); } if( filter!=null && filter.until!=null) { Date end = new Date( filter.until.getTime() + 24L * 3600 * 1000 ); where.and( "creation", "<", end); } /* * more restrictions specified by the grid control */ if( "bundle".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "bundle", "like", qvalue ); } else if( "service".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "service", "like", qvalue ); } else if( "creation".equals(qfield) && Utils.isNotEmpty(qvalue) ) { Date date = Utils.parseDate(qvalue, null); if( date != null ) { where.and( "creation", "=", date ); } else { Logger.warn("Invalid date format: %s", qvalue); } } else if( "ip".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "ip", "like", qvalue ); } else if( "rid".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "requestId", "like", qvalue ); } else if( "email".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "email", "like", qvalue ); } else if( "source".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "source", "=", qvalue ); } else if( "status".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "status", "=", qvalue ); } /* * counting the total result items */ GridResult result = new GridResult(); Query query = JPA.em().createQuery("select count(*) " + where.toString()); // append the params where.setParams(query); // execute the query and get the COUNT result.total = (Long) query.getSingleResult(); /* * 2. fetch result set * define the ordering */ if( Utils.isNotEmpty(sortfield) && !"undefined".equals(sortfield) && !"null".equals(sortfield) ) { if( sortfield.equals("duration") ) { // 'duration' is the formatted version of the field 'elapsed' sortfield = "elapsed"; } where.order(sortfield, !"desc".equals(sortorder) ); } /* * find the rows */ query = JPA.em().createQuery(where.toString()); if( skip > 0 ) { query.setFirstResult(skip); } if( size > 0 ) { query.setMaxResults(size); } where.setParams(query); result.rows = query.getResultList(); return result; }
public static GridResult findUsageGridData( UsageFilter filter, int page, int size, String sortfield, String sortorder, String qvalue, String qfield ) { int skip = (page>0 && size>0 ) ? (page-1) * size : -1; QueryBuilder where = new QueryBuilder(UsageLog.class); /* * 1. counting */ /* apply filter restrictions */ if( filter!=null && Utils.isNotEmpty(filter.bundle)) { where.and( "bundle", "like", filter.bundle ); } if( filter!=null && Utils.isNotEmpty(filter.service)) { where.and( "service", "like", filter.service ); } if( filter!=null && Utils.isNotEmpty(filter.status)) { where.and( "status", "=", filter.status); } if( filter!=null && filter.since!=null) { where.and( "creation", ">=", filter.since); } if( filter!=null && filter.until!=null) { Date end = new Date( filter.until.getTime() + 24L * 3600 * 1000 ); where.and( "creation", "<", end); } /* * more restrictions specified by the grid control */ if( "bundle".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "bundle", "like", qvalue ); } else if( "service".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "service", "like", qvalue ); } else if( "creation".equals(qfield) && Utils.isNotEmpty(qvalue) ) { Date date = Utils.parseDate(qvalue, null); if( date != null ) { where.and( "creation", "=", date ); } else { Logger.warn("Invalid date format: %s", qvalue); } } else if( "ip".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "ip", "like", qvalue ); } else if( "rid".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "requestId", "like", qvalue ); } else if( "email".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "email", "like", qvalue ); } else if( "source".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "source", "like", qvalue ); } else if( "status".equals(qfield) && Utils.isNotEmpty(qvalue) ) { where.and( "status", "=", qvalue ); } /* * counting the total result items */ GridResult result = new GridResult(); Query query = JPA.em().createQuery("select count(*) " + where.toString()); // append the params where.setParams(query); // execute the query and get the COUNT result.total = (Long) query.getSingleResult(); /* * 2. fetch result set * define the ordering */ if( Utils.isNotEmpty(sortfield) && !"undefined".equals(sortfield) && !"null".equals(sortfield) ) { if( sortfield.equals("duration") ) { // 'duration' is the formatted version of the field 'elapsed' sortfield = "elapsed"; } where.order(sortfield, !"desc".equals(sortorder) ); } /* * find the rows */ query = JPA.em().createQuery(where.toString()); if( skip > 0 ) { query.setFirstResult(skip); } if( size > 0 ) { query.setMaxResults(size); } where.setParams(query); result.rows = query.getResultList(); return result; }
diff --git a/src/com/timvisee/manager/Manager.java b/src/com/timvisee/manager/Manager.java index 8d6763e..f73a217 100644 --- a/src/com/timvisee/manager/Manager.java +++ b/src/com/timvisee/manager/Manager.java @@ -1,118 +1,118 @@ package com.timvisee.manager; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import com.timvisee.manager.economymanager.EconomyManager; import com.timvisee.manager.permissionsmanager.PermissionsManager; public class Manager extends JavaPlugin { private static final Logger log = Logger.getLogger("Minecraft"); // Permissions and Economy manager private PermissionsManager pm; private EconomyManager em; public void onEnable() { // Setup the managers setupPermissionsManager(); setupEconomyManager(); // Plugin started log.info("[Manager] Manager Started"); } public void onDisable() { log.info("[Manager] Manager Disabled"); } /** * Setup the economy manager */ public void setupEconomyManager() { // Setup the economy manager this.em = new EconomyManager(this.getServer(), this); this.em.setup(); } /** * Get the economy manager * @return economy manager */ public EconomyManager getEconomyManager() { return this.em; } /** * Setup the permissions manager */ public void setupPermissionsManager() { // Setup the permissions manager this.pm = new PermissionsManager(this.getServer(), this); this.pm.setup(); } /** * Get the permissions manager * @return permissions manager */ public PermissionsManager getPermissionsManager() { return this.pm; } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { // Commands to test whether or not Manager is able to properly communicate with the permission/economy system currently running if (sender instanceof Player){ if (cmd.getName().equalsIgnoreCase("manager")){ if (args.length>0){ if (args[0].equalsIgnoreCase("node")){ if (args.length>1){ if (this.pm.hasPermission((Player) sender, args[1])) sender.sendMessage("Passed"); else sender.sendMessage("Failed"); return true; } else { sender.sendMessage("No permission node provided."); return false; } } else if (args[0].equalsIgnoreCase("groups")){ for(Object o: this.pm.getGroups((Player) sender)){ sender.sendMessage(o.toString()); } return true; } else if (args[0].equalsIgnoreCase("addmoney")){ - if (args[1] != null){ + if (args.length>1){ this.em.depositMoney(sender.getName(), Double.parseDouble(args[1])); return true; } else return false; } else if (args[0].equalsIgnoreCase("submoney")){ - if (args[1] != null){ + if (args.length>1){ this.em.withdrawMoney(sender.getName(), Double.parseDouble(args[1])); return true; } else return false; } else if (args[0].equalsIgnoreCase("getmoney")){ - if (args[1] != null){ + if (args.length>1){ Double balance = this.em.getBalance(args[1]); sender.sendMessage("Balance: "+Double.toString(balance)+" "+this.em.getCurrencyName(balance)); return true; } else { Double balance = this.em.getBalance(sender.getName()); sender.sendMessage("Balance: "+Double.toString(balance)+" "+this.em.getCurrencyName(balance)); return true; } } } } else return false; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { // Commands to test whether or not Manager is able to properly communicate with the permission/economy system currently running if (sender instanceof Player){ if (cmd.getName().equalsIgnoreCase("manager")){ if (args.length>0){ if (args[0].equalsIgnoreCase("node")){ if (args.length>1){ if (this.pm.hasPermission((Player) sender, args[1])) sender.sendMessage("Passed"); else sender.sendMessage("Failed"); return true; } else { sender.sendMessage("No permission node provided."); return false; } } else if (args[0].equalsIgnoreCase("groups")){ for(Object o: this.pm.getGroups((Player) sender)){ sender.sendMessage(o.toString()); } return true; } else if (args[0].equalsIgnoreCase("addmoney")){ if (args[1] != null){ this.em.depositMoney(sender.getName(), Double.parseDouble(args[1])); return true; } else return false; } else if (args[0].equalsIgnoreCase("submoney")){ if (args[1] != null){ this.em.withdrawMoney(sender.getName(), Double.parseDouble(args[1])); return true; } else return false; } else if (args[0].equalsIgnoreCase("getmoney")){ if (args[1] != null){ Double balance = this.em.getBalance(args[1]); sender.sendMessage("Balance: "+Double.toString(balance)+" "+this.em.getCurrencyName(balance)); return true; } else { Double balance = this.em.getBalance(sender.getName()); sender.sendMessage("Balance: "+Double.toString(balance)+" "+this.em.getCurrencyName(balance)); return true; } } } } else return false; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { // Commands to test whether or not Manager is able to properly communicate with the permission/economy system currently running if (sender instanceof Player){ if (cmd.getName().equalsIgnoreCase("manager")){ if (args.length>0){ if (args[0].equalsIgnoreCase("node")){ if (args.length>1){ if (this.pm.hasPermission((Player) sender, args[1])) sender.sendMessage("Passed"); else sender.sendMessage("Failed"); return true; } else { sender.sendMessage("No permission node provided."); return false; } } else if (args[0].equalsIgnoreCase("groups")){ for(Object o: this.pm.getGroups((Player) sender)){ sender.sendMessage(o.toString()); } return true; } else if (args[0].equalsIgnoreCase("addmoney")){ if (args.length>1){ this.em.depositMoney(sender.getName(), Double.parseDouble(args[1])); return true; } else return false; } else if (args[0].equalsIgnoreCase("submoney")){ if (args.length>1){ this.em.withdrawMoney(sender.getName(), Double.parseDouble(args[1])); return true; } else return false; } else if (args[0].equalsIgnoreCase("getmoney")){ if (args.length>1){ Double balance = this.em.getBalance(args[1]); sender.sendMessage("Balance: "+Double.toString(balance)+" "+this.em.getCurrencyName(balance)); return true; } else { Double balance = this.em.getBalance(sender.getName()); sender.sendMessage("Balance: "+Double.toString(balance)+" "+this.em.getCurrencyName(balance)); return true; } } } } else return false; } return false; }
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/prefs/views/PaneLayoutPreferencesPane.java b/src/gwt/src/org/rstudio/studio/client/workbench/prefs/views/PaneLayoutPreferencesPane.java index 5309690993..1e0c610bbb 100644 --- a/src/gwt/src/org/rstudio/studio/client/workbench/prefs/views/PaneLayoutPreferencesPane.java +++ b/src/gwt/src/org/rstudio/studio/client/workbench/prefs/views/PaneLayoutPreferencesPane.java @@ -1,360 +1,360 @@ package org.rstudio.studio.client.workbench.prefs.views; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.*; import com.google.inject.Inject; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.ui.PaneConfig; import java.util.ArrayList; public class PaneLayoutPreferencesPane extends PreferencesPane { private static class Item { private Item(String label, String value) { this.label = label; this.value = value; } public final String label; public final String value; } class ExclusiveSelectionMaintainer { class ListChangeHandler implements ChangeHandler { ListChangeHandler(int whichList) { whichList_ = whichList; } public void onChange(ChangeEvent event) { int selectedIndex = lists_[whichList_].getSelectedIndex(); for (int i = 0; i < lists_.length; i++) { if (i != whichList_ && lists_[i].getSelectedIndex() == selectedIndex) { lists_[i].setSelectedIndex(notSelectedIndex()); } } updateTabSetPositions(); } private Integer notSelectedIndex() { boolean[] seen = new boolean[4]; for (ListBox listBox : lists_) seen[listBox.getSelectedIndex()] = true; for (int i = 0; i < seen.length; i++) if (!seen[i]) return i; return null; } private final int whichList_; } ExclusiveSelectionMaintainer(ListBox[] lists) { lists_ = lists; for (int i = 0; i < lists.length; i++) lists[i].addChangeHandler(new ListChangeHandler(i)); } private final ListBox[] lists_; } class ModuleList extends Composite implements ValueChangeHandler<Boolean>, HasValueChangeHandlers<ArrayList<Boolean>> { ModuleList() { checkBoxes_ = new ArrayList<CheckBox>(); VerticalPanel panel = new VerticalPanel(); for (String module : PaneConfig.getAllTabs()) { CheckBox checkBox = new CheckBox(module, false); checkBox.addValueChangeHandler(this); checkBoxes_.add(checkBox); panel.add(checkBox); } initWidget(panel); } public void onValueChange(ValueChangeEvent<Boolean> event) { if (getValue().size() > 0) ValueChangeEvent.fire(this, getSelectedIndices()); else { ((CheckBox)event.getSource()).setValue(true, false); } } public ArrayList<Boolean> getSelectedIndices() { ArrayList<Boolean> results = new ArrayList<Boolean>(); for (CheckBox checkBox : checkBoxes_) results.add(checkBox.getValue()); return results; } public void setSelectedIndices(ArrayList<Boolean> selected) { for (int i = 0; i < selected.size(); i++) checkBoxes_.get(i).setValue(selected.get(i), false); } public ArrayList<String> getValue() { ArrayList<String> value = new ArrayList<String>(); for (CheckBox checkBox : checkBoxes_) { if (checkBox.getValue()) value.add(checkBox.getText()); } return value; } public void setValue(ArrayList<String> tabs) { for (CheckBox checkBox : checkBoxes_) checkBox.setValue(tabs.contains(checkBox.getText()), false); } public HandlerRegistration addValueChangeHandler( ValueChangeHandler<ArrayList<Boolean>> handler) { return addHandler(handler, ValueChangeEvent.getType()); } private final ArrayList<CheckBox> checkBoxes_; } @Inject public PaneLayoutPreferencesPane(PreferencesDialogResources res, UIPrefs uiPrefs) { res_ = res; uiPrefs_ = uiPrefs; add(new Label("Choose the layout of the panes in RStudio by selecting from the controls in each quadrant.", true)); String[] allPanes = PaneConfig.getAllPanes(); leftTop_ = new ListBox(); leftBottom_ = new ListBox(); rightTop_ = new ListBox(); rightBottom_ = new ListBox(); allPanes_ = new ListBox[]{leftTop_, leftBottom_, rightTop_, rightBottom_}; for (ListBox lb : allPanes_) { for (String value : allPanes) lb.addItem(value); } PaneConfig value = uiPrefs.paneConfig().getValue(); - if (value == null || value.isValid()) + if (value == null || !value.isValid()) uiPrefs.paneConfig().setValue(PaneConfig.createDefault()); JsArrayString origPanes = uiPrefs.paneConfig().getValue().getPanes(); for (int i = 0; i < 4; i++) { boolean success = selectByValue(allPanes_[i], origPanes.get(i)); if (!success) { Debug.log("Bad config! Falling back to a reasonable default"); leftTop_.setSelectedIndex(0); leftBottom_.setSelectedIndex(1); rightTop_.setSelectedIndex(2); rightBottom_.setSelectedIndex(3); break; } } new ExclusiveSelectionMaintainer(allPanes_); Grid grid = new Grid(2, 2); grid.addStyleName(res.styles().paneLayoutTable()); grid.setCellSpacing(8); grid.setCellPadding(6); grid.setWidget(0, 0, leftTopPanel_ = createPane(leftTop_)); grid.setWidget(1, 0, leftBottomPanel_ = createPane(leftBottom_)); grid.setWidget(0, 1, rightTopPanel_ = createPane(rightTop_)); grid.setWidget(1, 1, rightBottomPanel_ = createPane(rightBottom_)); for (int row = 0; row < 2; row++) for (int col = 0; col < 2; col++) grid.getCellFormatter().setStyleName(row, col, res.styles().paneLayoutTable()); add(grid); allPanePanels_ = new VerticalPanel[] {leftTopPanel_, leftBottomPanel_, rightTopPanel_, rightBottomPanel_}; tabSet1ModuleList_ = new ModuleList(); tabSet1ModuleList_.setValue(toArrayList(uiPrefs.paneConfig().getValue().getTabSet1())); tabSet2ModuleList_ = new ModuleList(); tabSet2ModuleList_.setValue(toArrayList(uiPrefs.paneConfig().getValue().getTabSet2())); ValueChangeHandler<ArrayList<Boolean>> vch = new ValueChangeHandler<ArrayList<Boolean>>() { public void onValueChange(ValueChangeEvent<ArrayList<Boolean>> e) { ModuleList source = (ModuleList) e.getSource(); ModuleList other = (source == tabSet1ModuleList_) ? tabSet2ModuleList_ : tabSet1ModuleList_; if (source.getValue().size() == PaneConfig.getAllTabs().length) { ArrayList<Boolean> indices = source.getSelectedIndices(); ArrayList<Boolean> otherIndices = other.getSelectedIndices(); for (int i = 0; i < indices.size(); i++) { if (otherIndices.get(i)) { indices.set(i, false); } } source.setSelectedIndices(indices); } else { ArrayList<Boolean> indices = source.getSelectedIndices(); ArrayList<Boolean> otherIndices = new ArrayList<Boolean>(); for (Boolean b : indices) otherIndices.add(!b); other.setSelectedIndices(otherIndices); updateTabSetLabels(); } } }; tabSet1ModuleList_.addValueChangeHandler(vch); tabSet2ModuleList_.addValueChangeHandler(vch); updateTabSetPositions(); updateTabSetLabels(); } private VerticalPanel createPane(ListBox listBox) { VerticalPanel vp = new VerticalPanel(); vp.add(listBox); return vp; } private static boolean selectByValue(ListBox listBox, String value) { for (int i = 0; i < listBox.getItemCount(); i++) { if (listBox.getValue(i).equals(value)) { listBox.setSelectedIndex(i); return true; } } return false; } @Override public ImageResource getIcon() { return res_.iconPanes(); } @Override public void onApply() { PaneConfig config = uiPrefs_.paneConfig().getValue(); JsArrayString panes = JsArrayString.createArray().cast(); panes.push(leftTop_.getValue(leftTop_.getSelectedIndex())); panes.push(leftBottom_.getValue(leftBottom_.getSelectedIndex())); panes.push(rightTop_.getValue(rightTop_.getSelectedIndex())); panes.push(rightBottom_.getValue(rightBottom_.getSelectedIndex())); config.setPanes(panes); JsArrayString tabSet1 = JsArrayString.createArray().cast(); for (String tab : tabSet1ModuleList_.getValue()) tabSet1.push(tab); config.setTabSet1(tabSet1); JsArrayString tabSet2 = JsArrayString.createArray().cast(); for (String tab : tabSet2ModuleList_.getValue()) tabSet2.push(tab); config.setTabSet2(tabSet2); uiPrefs_.paneConfig().setValue(config); } @Override public String getName() { return "Pane Layout"; } private void updateTabSetPositions() { for (int i = 0; i < allPanes_.length; i++) { String value = allPanes_[i].getValue(allPanes_[i].getSelectedIndex()); if (value.equals("TabSet1")) allPanePanels_[i].add(tabSet1ModuleList_); else if (value.equals("TabSet2")) allPanePanels_[i].add(tabSet2ModuleList_); } } private void updateTabSetLabels() { for (ListBox pane : allPanes_) { pane.setItemText(2, StringUtil.join(tabSet1ModuleList_.getValue(), ", ")); pane.setItemText(3, StringUtil.join(tabSet2ModuleList_.getValue(), ", ")); } } private ArrayList<String> toArrayList(JsArrayString strings) { ArrayList<String> results = new ArrayList<String>(); for (int i = 0; i < strings.length(); i++) results.add(strings.get(i)); return results; } private final PreferencesDialogResources res_; private final UIPrefs uiPrefs_; private final ListBox leftTop_; private final ListBox leftBottom_; private final ListBox rightTop_; private final ListBox rightBottom_; private final ListBox[] allPanes_; private final VerticalPanel leftTopPanel_; private final VerticalPanel leftBottomPanel_; private final VerticalPanel rightTopPanel_; private final VerticalPanel rightBottomPanel_; private final VerticalPanel[] allPanePanels_; private final ModuleList tabSet1ModuleList_; private final ModuleList tabSet2ModuleList_; }
true
true
public PaneLayoutPreferencesPane(PreferencesDialogResources res, UIPrefs uiPrefs) { res_ = res; uiPrefs_ = uiPrefs; add(new Label("Choose the layout of the panes in RStudio by selecting from the controls in each quadrant.", true)); String[] allPanes = PaneConfig.getAllPanes(); leftTop_ = new ListBox(); leftBottom_ = new ListBox(); rightTop_ = new ListBox(); rightBottom_ = new ListBox(); allPanes_ = new ListBox[]{leftTop_, leftBottom_, rightTop_, rightBottom_}; for (ListBox lb : allPanes_) { for (String value : allPanes) lb.addItem(value); } PaneConfig value = uiPrefs.paneConfig().getValue(); if (value == null || value.isValid()) uiPrefs.paneConfig().setValue(PaneConfig.createDefault()); JsArrayString origPanes = uiPrefs.paneConfig().getValue().getPanes(); for (int i = 0; i < 4; i++) { boolean success = selectByValue(allPanes_[i], origPanes.get(i)); if (!success) { Debug.log("Bad config! Falling back to a reasonable default"); leftTop_.setSelectedIndex(0); leftBottom_.setSelectedIndex(1); rightTop_.setSelectedIndex(2); rightBottom_.setSelectedIndex(3); break; } } new ExclusiveSelectionMaintainer(allPanes_); Grid grid = new Grid(2, 2); grid.addStyleName(res.styles().paneLayoutTable()); grid.setCellSpacing(8); grid.setCellPadding(6); grid.setWidget(0, 0, leftTopPanel_ = createPane(leftTop_)); grid.setWidget(1, 0, leftBottomPanel_ = createPane(leftBottom_)); grid.setWidget(0, 1, rightTopPanel_ = createPane(rightTop_)); grid.setWidget(1, 1, rightBottomPanel_ = createPane(rightBottom_)); for (int row = 0; row < 2; row++) for (int col = 0; col < 2; col++) grid.getCellFormatter().setStyleName(row, col, res.styles().paneLayoutTable()); add(grid); allPanePanels_ = new VerticalPanel[] {leftTopPanel_, leftBottomPanel_, rightTopPanel_, rightBottomPanel_}; tabSet1ModuleList_ = new ModuleList(); tabSet1ModuleList_.setValue(toArrayList(uiPrefs.paneConfig().getValue().getTabSet1())); tabSet2ModuleList_ = new ModuleList(); tabSet2ModuleList_.setValue(toArrayList(uiPrefs.paneConfig().getValue().getTabSet2())); ValueChangeHandler<ArrayList<Boolean>> vch = new ValueChangeHandler<ArrayList<Boolean>>() { public void onValueChange(ValueChangeEvent<ArrayList<Boolean>> e) { ModuleList source = (ModuleList) e.getSource(); ModuleList other = (source == tabSet1ModuleList_) ? tabSet2ModuleList_ : tabSet1ModuleList_; if (source.getValue().size() == PaneConfig.getAllTabs().length) { ArrayList<Boolean> indices = source.getSelectedIndices(); ArrayList<Boolean> otherIndices = other.getSelectedIndices(); for (int i = 0; i < indices.size(); i++) { if (otherIndices.get(i)) { indices.set(i, false); } } source.setSelectedIndices(indices); } else { ArrayList<Boolean> indices = source.getSelectedIndices(); ArrayList<Boolean> otherIndices = new ArrayList<Boolean>(); for (Boolean b : indices) otherIndices.add(!b); other.setSelectedIndices(otherIndices); updateTabSetLabels(); } } }; tabSet1ModuleList_.addValueChangeHandler(vch); tabSet2ModuleList_.addValueChangeHandler(vch); updateTabSetPositions(); updateTabSetLabels(); }
public PaneLayoutPreferencesPane(PreferencesDialogResources res, UIPrefs uiPrefs) { res_ = res; uiPrefs_ = uiPrefs; add(new Label("Choose the layout of the panes in RStudio by selecting from the controls in each quadrant.", true)); String[] allPanes = PaneConfig.getAllPanes(); leftTop_ = new ListBox(); leftBottom_ = new ListBox(); rightTop_ = new ListBox(); rightBottom_ = new ListBox(); allPanes_ = new ListBox[]{leftTop_, leftBottom_, rightTop_, rightBottom_}; for (ListBox lb : allPanes_) { for (String value : allPanes) lb.addItem(value); } PaneConfig value = uiPrefs.paneConfig().getValue(); if (value == null || !value.isValid()) uiPrefs.paneConfig().setValue(PaneConfig.createDefault()); JsArrayString origPanes = uiPrefs.paneConfig().getValue().getPanes(); for (int i = 0; i < 4; i++) { boolean success = selectByValue(allPanes_[i], origPanes.get(i)); if (!success) { Debug.log("Bad config! Falling back to a reasonable default"); leftTop_.setSelectedIndex(0); leftBottom_.setSelectedIndex(1); rightTop_.setSelectedIndex(2); rightBottom_.setSelectedIndex(3); break; } } new ExclusiveSelectionMaintainer(allPanes_); Grid grid = new Grid(2, 2); grid.addStyleName(res.styles().paneLayoutTable()); grid.setCellSpacing(8); grid.setCellPadding(6); grid.setWidget(0, 0, leftTopPanel_ = createPane(leftTop_)); grid.setWidget(1, 0, leftBottomPanel_ = createPane(leftBottom_)); grid.setWidget(0, 1, rightTopPanel_ = createPane(rightTop_)); grid.setWidget(1, 1, rightBottomPanel_ = createPane(rightBottom_)); for (int row = 0; row < 2; row++) for (int col = 0; col < 2; col++) grid.getCellFormatter().setStyleName(row, col, res.styles().paneLayoutTable()); add(grid); allPanePanels_ = new VerticalPanel[] {leftTopPanel_, leftBottomPanel_, rightTopPanel_, rightBottomPanel_}; tabSet1ModuleList_ = new ModuleList(); tabSet1ModuleList_.setValue(toArrayList(uiPrefs.paneConfig().getValue().getTabSet1())); tabSet2ModuleList_ = new ModuleList(); tabSet2ModuleList_.setValue(toArrayList(uiPrefs.paneConfig().getValue().getTabSet2())); ValueChangeHandler<ArrayList<Boolean>> vch = new ValueChangeHandler<ArrayList<Boolean>>() { public void onValueChange(ValueChangeEvent<ArrayList<Boolean>> e) { ModuleList source = (ModuleList) e.getSource(); ModuleList other = (source == tabSet1ModuleList_) ? tabSet2ModuleList_ : tabSet1ModuleList_; if (source.getValue().size() == PaneConfig.getAllTabs().length) { ArrayList<Boolean> indices = source.getSelectedIndices(); ArrayList<Boolean> otherIndices = other.getSelectedIndices(); for (int i = 0; i < indices.size(); i++) { if (otherIndices.get(i)) { indices.set(i, false); } } source.setSelectedIndices(indices); } else { ArrayList<Boolean> indices = source.getSelectedIndices(); ArrayList<Boolean> otherIndices = new ArrayList<Boolean>(); for (Boolean b : indices) otherIndices.add(!b); other.setSelectedIndices(otherIndices); updateTabSetLabels(); } } }; tabSet1ModuleList_.addValueChangeHandler(vch); tabSet2ModuleList_.addValueChangeHandler(vch); updateTabSetPositions(); updateTabSetLabels(); }
diff --git a/hale/eu.esdihumboldt.hale.schemaprovider/src/test/eu/esdihumboldt/hale/schemaprovider/provider/ShapeSchemaProviderTest.java b/hale/eu.esdihumboldt.hale.schemaprovider/src/test/eu/esdihumboldt/hale/schemaprovider/provider/ShapeSchemaProviderTest.java index 5935a16da..32229a6f8 100644 --- a/hale/eu.esdihumboldt.hale.schemaprovider/src/test/eu/esdihumboldt/hale/schemaprovider/provider/ShapeSchemaProviderTest.java +++ b/hale/eu.esdihumboldt.hale.schemaprovider/src/test/eu/esdihumboldt/hale/schemaprovider/provider/ShapeSchemaProviderTest.java @@ -1,61 +1,61 @@ package test.eu.esdihumboldt.hale.schemaprovider.provider; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.net.URI; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Test; import eu.esdihumboldt.hale.schemaprovider.LogProgressIndicator; import eu.esdihumboldt.hale.schemaprovider.Schema; import eu.esdihumboldt.hale.schemaprovider.model.AttributeDefinition; import eu.esdihumboldt.hale.schemaprovider.model.SchemaElement; import eu.esdihumboldt.hale.schemaprovider.provider.ShapeSchemaProvider; /** * Test class for the {@link ShapeSchemaProvider}. * * @author Thorsten Reitz * @partner 01 / Fraunhofer Institute for Computer Graphics Research * @version $Id$ * @since 2.0.0.M2 */ public class ShapeSchemaProviderTest { private static final Logger log = Logger.getLogger(ShapeSchemaProviderTest.class); /** * test for {@link ShapeSchemaProvider#loadSchema(URI, eu.esdihumboldt.hale.schemaprovider.ProgressIndicator)} */ @Test public void testLoadSchema() { log.setLevel(Level.INFO); ShapeSchemaProvider ssp = new ShapeSchemaProvider(); Schema result = null; try { URI uri = ShapeSchemaProviderTest.class.getResource("DEPARTEMENT.SHP").toURI(); result = ssp.loadSchema(uri, new LogProgressIndicator()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertTrue(result.getElements().size() == 2); for (SchemaElement se : result.getElements().values()) { log.info(se.getDisplayName()); for (AttributeDefinition ad : se.getType().getAttributes()) { log.info(ad.getDisplayName() + ": " - + ad.getAttributeType().getType().getBinding().getSimpleName() - + " (" + ad.getAttributeType().getType().getRestrictions() + ")"); + + ad.getAttributeType().getType(null).getBinding().getSimpleName() + + " (" + ad.getAttributeType().getType(null).getRestrictions() + ")"); } } } }
true
true
public void testLoadSchema() { log.setLevel(Level.INFO); ShapeSchemaProvider ssp = new ShapeSchemaProvider(); Schema result = null; try { URI uri = ShapeSchemaProviderTest.class.getResource("DEPARTEMENT.SHP").toURI(); result = ssp.loadSchema(uri, new LogProgressIndicator()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertTrue(result.getElements().size() == 2); for (SchemaElement se : result.getElements().values()) { log.info(se.getDisplayName()); for (AttributeDefinition ad : se.getType().getAttributes()) { log.info(ad.getDisplayName() + ": " + ad.getAttributeType().getType().getBinding().getSimpleName() + " (" + ad.getAttributeType().getType().getRestrictions() + ")"); } } }
public void testLoadSchema() { log.setLevel(Level.INFO); ShapeSchemaProvider ssp = new ShapeSchemaProvider(); Schema result = null; try { URI uri = ShapeSchemaProviderTest.class.getResource("DEPARTEMENT.SHP").toURI(); result = ssp.loadSchema(uri, new LogProgressIndicator()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertTrue(result.getElements().size() == 2); for (SchemaElement se : result.getElements().values()) { log.info(se.getDisplayName()); for (AttributeDefinition ad : se.getType().getAttributes()) { log.info(ad.getDisplayName() + ": " + ad.getAttributeType().getType(null).getBinding().getSimpleName() + " (" + ad.getAttributeType().getType(null).getRestrictions() + ")"); } } }
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java b/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java index 026cc4f572..0414affc82 100644 --- a/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java +++ b/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java @@ -1,112 +1,112 @@ package org.apache.solr.search.grouping.endresulttransformer; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.grouping.GroupDocs; import org.apache.lucene.search.grouping.TopGroups; import org.apache.lucene.util.BytesRef; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.handler.component.ResponseBuilder; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.SolrIndexSearcher; import org.apache.solr.search.grouping.distributed.command.QueryCommandResult; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Implementation of {@link EndResultTransformer} that keeps each grouped result separate in the final response. */ public class GroupedEndResultTransformer implements EndResultTransformer { private final SolrIndexSearcher searcher; public GroupedEndResultTransformer(SolrIndexSearcher searcher) { this.searcher = searcher; } /** * {@inheritDoc} */ @Override public void transform(Map<String, ?> result, ResponseBuilder rb, SolrDocumentSource solrDocumentSource) { - NamedList<Object> commands = new NamedList<Object>(); + NamedList<Object> commands = new SimpleOrderedMap<Object>(); for (Map.Entry<String, ?> entry : result.entrySet()) { Object value = entry.getValue(); if (TopGroups.class.isInstance(value)) { @SuppressWarnings("unchecked") TopGroups<BytesRef> topGroups = (TopGroups<BytesRef>) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", rb.totalHitCount); Integer totalGroupCount = rb.mergedGroupCounts.get(entry.getKey()); if (totalGroupCount != null) { command.add("ngroups", totalGroupCount); } List<NamedList> groups = new ArrayList<NamedList>(); SchemaField groupField = searcher.getSchema().getField(entry.getKey()); FieldType groupFieldType = groupField.getType(); for (GroupDocs<BytesRef> group : topGroups.groups) { SimpleOrderedMap<Object> groupResult = new SimpleOrderedMap<Object>(); if (group.groupValue != null) { groupResult.add( "groupValue", groupFieldType.toObject(groupField.createField(group.groupValue.utf8ToString(), 1.0f)) ); } else { groupResult.add("groupValue", null); } SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(group.totalHits); if (!Float.isNaN(group.maxScore)) { docList.setMaxScore(group.maxScore); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc : group.scoreDocs) { docList.add(solrDocumentSource.retrieve(scoreDoc)); } groupResult.add("doclist", docList); groups.add(groupResult); } command.add("groups", groups); commands.add(entry.getKey(), command); } else if (QueryCommandResult.class.isInstance(value)) { QueryCommandResult queryCommandResult = (QueryCommandResult) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", queryCommandResult.getMatches()); SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(queryCommandResult.getTopDocs().totalHits); if (!Float.isNaN(queryCommandResult.getTopDocs().getMaxScore())) { docList.setMaxScore(queryCommandResult.getTopDocs().getMaxScore()); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc :queryCommandResult.getTopDocs().scoreDocs){ docList.add(solrDocumentSource.retrieve(scoreDoc)); } command.add("doclist", docList); commands.add(entry.getKey(), command); } } rb.rsp.add("grouped", commands); } }
true
true
public void transform(Map<String, ?> result, ResponseBuilder rb, SolrDocumentSource solrDocumentSource) { NamedList<Object> commands = new NamedList<Object>(); for (Map.Entry<String, ?> entry : result.entrySet()) { Object value = entry.getValue(); if (TopGroups.class.isInstance(value)) { @SuppressWarnings("unchecked") TopGroups<BytesRef> topGroups = (TopGroups<BytesRef>) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", rb.totalHitCount); Integer totalGroupCount = rb.mergedGroupCounts.get(entry.getKey()); if (totalGroupCount != null) { command.add("ngroups", totalGroupCount); } List<NamedList> groups = new ArrayList<NamedList>(); SchemaField groupField = searcher.getSchema().getField(entry.getKey()); FieldType groupFieldType = groupField.getType(); for (GroupDocs<BytesRef> group : topGroups.groups) { SimpleOrderedMap<Object> groupResult = new SimpleOrderedMap<Object>(); if (group.groupValue != null) { groupResult.add( "groupValue", groupFieldType.toObject(groupField.createField(group.groupValue.utf8ToString(), 1.0f)) ); } else { groupResult.add("groupValue", null); } SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(group.totalHits); if (!Float.isNaN(group.maxScore)) { docList.setMaxScore(group.maxScore); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc : group.scoreDocs) { docList.add(solrDocumentSource.retrieve(scoreDoc)); } groupResult.add("doclist", docList); groups.add(groupResult); } command.add("groups", groups); commands.add(entry.getKey(), command); } else if (QueryCommandResult.class.isInstance(value)) { QueryCommandResult queryCommandResult = (QueryCommandResult) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", queryCommandResult.getMatches()); SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(queryCommandResult.getTopDocs().totalHits); if (!Float.isNaN(queryCommandResult.getTopDocs().getMaxScore())) { docList.setMaxScore(queryCommandResult.getTopDocs().getMaxScore()); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc :queryCommandResult.getTopDocs().scoreDocs){ docList.add(solrDocumentSource.retrieve(scoreDoc)); } command.add("doclist", docList); commands.add(entry.getKey(), command); } } rb.rsp.add("grouped", commands); }
public void transform(Map<String, ?> result, ResponseBuilder rb, SolrDocumentSource solrDocumentSource) { NamedList<Object> commands = new SimpleOrderedMap<Object>(); for (Map.Entry<String, ?> entry : result.entrySet()) { Object value = entry.getValue(); if (TopGroups.class.isInstance(value)) { @SuppressWarnings("unchecked") TopGroups<BytesRef> topGroups = (TopGroups<BytesRef>) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", rb.totalHitCount); Integer totalGroupCount = rb.mergedGroupCounts.get(entry.getKey()); if (totalGroupCount != null) { command.add("ngroups", totalGroupCount); } List<NamedList> groups = new ArrayList<NamedList>(); SchemaField groupField = searcher.getSchema().getField(entry.getKey()); FieldType groupFieldType = groupField.getType(); for (GroupDocs<BytesRef> group : topGroups.groups) { SimpleOrderedMap<Object> groupResult = new SimpleOrderedMap<Object>(); if (group.groupValue != null) { groupResult.add( "groupValue", groupFieldType.toObject(groupField.createField(group.groupValue.utf8ToString(), 1.0f)) ); } else { groupResult.add("groupValue", null); } SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(group.totalHits); if (!Float.isNaN(group.maxScore)) { docList.setMaxScore(group.maxScore); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc : group.scoreDocs) { docList.add(solrDocumentSource.retrieve(scoreDoc)); } groupResult.add("doclist", docList); groups.add(groupResult); } command.add("groups", groups); commands.add(entry.getKey(), command); } else if (QueryCommandResult.class.isInstance(value)) { QueryCommandResult queryCommandResult = (QueryCommandResult) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", queryCommandResult.getMatches()); SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(queryCommandResult.getTopDocs().totalHits); if (!Float.isNaN(queryCommandResult.getTopDocs().getMaxScore())) { docList.setMaxScore(queryCommandResult.getTopDocs().getMaxScore()); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc :queryCommandResult.getTopDocs().scoreDocs){ docList.add(solrDocumentSource.retrieve(scoreDoc)); } command.add("doclist", docList); commands.add(entry.getKey(), command); } } rb.rsp.add("grouped", commands); }
diff --git a/mod/jodd-joy/src/jodd/joy/core/DefaultAppCore.java b/mod/jodd-joy/src/jodd/joy/core/DefaultAppCore.java index bfc3db4b7..8ae587fd2 100644 --- a/mod/jodd-joy/src/jodd/joy/core/DefaultAppCore.java +++ b/mod/jodd-joy/src/jodd/joy/core/DefaultAppCore.java @@ -1,362 +1,364 @@ // Copyright (c) 2003-2011, Jodd Team (jodd.org). All Rights Reserved. package jodd.joy.core; import jodd.db.DbDefault; import jodd.db.DbSessionProvider; import jodd.db.connection.ConnectionProvider; import jodd.db.orm.DbOrmManager; import jodd.db.orm.config.AutomagicDbOrmConfigurator; import jodd.db.pool.CoreConnectionPool; import jodd.joy.AppUtil; import jodd.joy.jtx.meta.ReadWriteTransaction; import jodd.joy.petite.ProxettaAwarePetiteContainer; import jodd.jtx.JtxTransactionManager; import jodd.jtx.db.DbJtxSessionProvider; import jodd.jtx.db.DbJtxTransactionManager; import jodd.jtx.meta.Transaction; import jodd.jtx.proxy.AnnotationTxAdvice; import jodd.jtx.proxy.AnnotationTxAdviceManager; import jodd.jtx.proxy.AnnotationTxAdviceSupport; import jodd.petite.PetiteContainer; import jodd.petite.config.AutomagicPetiteConfigurator; import jodd.petite.scope.SessionScope; import jodd.petite.scope.SingletonScope; import jodd.props.Props; import jodd.props.PropsUtil; import jodd.proxetta.MethodInfo; import jodd.proxetta.Proxetta; import jodd.proxetta.ProxyAspect; import jodd.proxetta.pointcuts.MethodAnnotationPointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static jodd.joy.AppUtil.prepareAppLogDir; import static jodd.joy.AppUtil.resolveAppDirs; /** * Default application core frame. */ public abstract class DefaultAppCore { /** * Petite bean names. */ public static final String PETITE_APPCORE = "app"; // AppCore public static final String PETITE_DBPOOL = "dbpool"; // database pool public static final String PETITE_DBORM = "dbOrm"; // DbOrm instance public static final String PETITE_APPINIT = "appInit"; // init bean /** * Logger. */ protected static Logger log; /** * Default scanning path that will be examined by various * Jodd auto-magic tools. */ protected final String[] scanningPath; /** * Default constructor. */ protected DefaultAppCore() { scanningPath = resolveScanningPath(); } /** * Defines the scanning path for Jodd frameworks. * Scanning path will contain all classes inside and bellow * the app core packages and 'jodd' packages. */ protected String[] resolveScanningPath() { return new String[] {this.getClass().getPackage().getName() + ".*", "jodd.*"}; } // ---------------------------------------------------------------- start /** * Returns <code>true</code> if application is started as a part of web application. */ public boolean isWebApplication() { return AppUtil.isWebApplication(); } /** * Starts the application and performs all initialization. */ public synchronized void start() { resolveAppDirs("app.props"); // app directories are resolved from location of 'app.props'. prepareAppLogDir("log"); // creates log folder, depending of application type initLogger(); // logger becomes available after this point log.info("app dir: {}", AppUtil.getAppDir()); log.info("log dir: {}", AppUtil.getLogDir()); log.info("classpath: {}", AppUtil.getClasspathDir()); try { initTypes(); initProxetta(); initPetite(); initDb(); initApp(); log.info("app started"); } catch (RuntimeException rex) { log.error(rex.toString(), rex); try { stop(); } catch (Exception ignore) { } throw rex; } } /** * Stops the application. */ public synchronized void stop() { log.info("shutting down..."); stopApp(); stopDb(); log.info("app stopped"); } // ---------------------------------------------------------------- log /** * Initializes the logger. It must be initialized after the * log path is defined. */ protected void initLogger() { log = LoggerFactory.getLogger(DefaultAppCore.class); } // ---------------------------------------------------------------- proxetta protected Proxetta proxetta; /** * Returns proxetta. */ public Proxetta getProxetta() { return proxetta; } /** * Creates Proxetta with all aspects. The following aspects are created: * * <li>Transaction proxy - applied on all classes that contains public top-level methods * annotated with <code>@Transaction</code> annotation. This is just one way how proxies * can be applied - since base configuration is in Java, everything is possible. */ protected void initProxetta() { log.info("proxetta initialization"); proxetta = Proxetta.withAspects(createAppAspects()).loadsWith(this.getClass().getClassLoader()); } /** * Creates all application aspects. By default it creates just * {@link #createTxProxyAspects() transactional aspect}. */ protected ProxyAspect[] createAppAspects() { return new ProxyAspect[] {createTxProxyAspects()}; } /** * Creates TX aspect that will be applied on all classes * having at least one public top-level method annotated * with <code>@Transaction</code>. */ protected ProxyAspect createTxProxyAspects() { return new ProxyAspect(AnnotationTxAdvice.class, new MethodAnnotationPointcut(Transaction.class, ReadWriteTransaction.class) { @Override public boolean apply(MethodInfo methodInfo) { return isPublic(methodInfo) && isTopLevelMethod(methodInfo) && super.apply(methodInfo); } }); } // ---------------------------------------------------------------- petite protected PetiteContainer petite; /** * Returns application container (Petite). */ public PetiteContainer getPetite() { return petite; } /** * Creates and initializes Petite container. * It will be auto-magically configured by scanning the classpath. * Also, all 'app*.prop*' will be loaded and values will * be injected in the matched beans. At the end it registers * this instance of core into the container. */ protected void initPetite() { log.info("petite initialization"); petite = createPetiteContainer(); boolean isWebApplication = AppUtil.isWebApplication(); log.info("app in web: {}", Boolean.valueOf(isWebApplication)); if (isWebApplication == false) { // make session scope to act as singleton scope // if this is not a web application (and http session is not available). petite.getManager().registerScope(SessionScope.class, new SingletonScope()); } // automagic configuration AutomagicPetiteConfigurator pcfg = new AutomagicPetiteConfigurator(); pcfg.setIncludedEntries(scanningPath); pcfg.configure(petite); // load parameters from properties files Props appProps = PropsUtil.createFromClasspath("/app*.prop*"); petite.defineParameters(appProps); // add AppCore instance to Petite petite.addBean(PETITE_APPCORE, this); } /** * Creates Petite container. By default, it creates * {@link jodd.joy.petite.ProxettaAwarePetiteContainer proxetta aware petite container}. */ protected PetiteContainer createPetiteContainer() { return new ProxettaAwarePetiteContainer(proxetta); } // ---------------------------------------------------------------- database /** * Database debug mode will print out sql statements. */ protected boolean debugMode; /** * Returns <code>true</code> if debug mode is on. */ public boolean isDebugMode() { return debugMode; } /** * JTX manager. */ protected JtxTransactionManager jtxManager; /** * Returns JTX transaction manager. */ public JtxTransactionManager getJtxManager() { return jtxManager; } /** * Database connection provider. */ protected ConnectionProvider connectionProvider; /** * Returns connection provider. */ public ConnectionProvider getConnectionProvider() { return connectionProvider; } /** * Initializes database. First, creates connection pool. * and transaction manager. Then, Jodds DbOrmManager is * configured. It is also configured automagically, by scanning * the class path for entities. */ protected void initDb() { log.info("database initialization"); // connection pool petite.registerBean(PETITE_DBPOOL, CoreConnectionPool.class); connectionProvider = (ConnectionProvider) petite.getBean(PETITE_DBPOOL); connectionProvider.init(); // transactions manager jtxManager = createJtxTransactionManager(connectionProvider); jtxManager.setValidateExistingTransaction(true); - AnnotationTxAdviceSupport.manager = new AnnotationTxAdviceManager(jtxManager, "$class"); + AnnotationTxAdviceManager annTxAdviceManager = new AnnotationTxAdviceManager(jtxManager, "$class"); + annTxAdviceManager.registerAnnotations(Transaction.class, ReadWriteTransaction.class); + AnnotationTxAdviceSupport.manager = annTxAdviceManager; DbSessionProvider sessionProvider = new DbJtxSessionProvider(jtxManager); // global settings DbDefault.debug = debugMode; DbDefault.connectionProvider = connectionProvider; DbDefault.sessionProvider = sessionProvider; DbOrmManager dbOrmManager = createDbOrmManager(); DbOrmManager.setInstance(dbOrmManager); petite.addBean(PETITE_DBORM, dbOrmManager); // automatic configuration AutomagicDbOrmConfigurator dbcfg = new AutomagicDbOrmConfigurator(); dbcfg.setIncludedEntries(scanningPath); dbcfg.configure(dbOrmManager); } /** * Creates JTX transaction manager. */ protected JtxTransactionManager createJtxTransactionManager(ConnectionProvider connectionProvider) { return new DbJtxTransactionManager(connectionProvider); } /** * Creates DbOrmManager. */ protected DbOrmManager createDbOrmManager() { return DbOrmManager.getInstance(); } /** * Closes database resources at the end. */ protected void stopDb() { log.info("database shutdown"); jtxManager.close(); connectionProvider.close(); } // ---------------------------------------------------------------- init protected AppInit appInit; /** * Initializes business part of the application. * Simply delegates to {@link AppInit#init()}. */ protected void initApp() { appInit = (AppInit) petite.getBean(PETITE_APPINIT); if (appInit != null) { appInit.init(); } } /** * Stops business part of the application. * Simply delegates to {@link AppInit#stop()}. */ protected void stopApp() { if (appInit != null) { appInit.stop(); } } // ---------------------------------------------------------------- new types /** * Initializes types for beanutil and db conversions and other usages. */ protected void initTypes() { } }
true
true
protected void initDb() { log.info("database initialization"); // connection pool petite.registerBean(PETITE_DBPOOL, CoreConnectionPool.class); connectionProvider = (ConnectionProvider) petite.getBean(PETITE_DBPOOL); connectionProvider.init(); // transactions manager jtxManager = createJtxTransactionManager(connectionProvider); jtxManager.setValidateExistingTransaction(true); AnnotationTxAdviceSupport.manager = new AnnotationTxAdviceManager(jtxManager, "$class"); DbSessionProvider sessionProvider = new DbJtxSessionProvider(jtxManager); // global settings DbDefault.debug = debugMode; DbDefault.connectionProvider = connectionProvider; DbDefault.sessionProvider = sessionProvider; DbOrmManager dbOrmManager = createDbOrmManager(); DbOrmManager.setInstance(dbOrmManager); petite.addBean(PETITE_DBORM, dbOrmManager); // automatic configuration AutomagicDbOrmConfigurator dbcfg = new AutomagicDbOrmConfigurator(); dbcfg.setIncludedEntries(scanningPath); dbcfg.configure(dbOrmManager); }
protected void initDb() { log.info("database initialization"); // connection pool petite.registerBean(PETITE_DBPOOL, CoreConnectionPool.class); connectionProvider = (ConnectionProvider) petite.getBean(PETITE_DBPOOL); connectionProvider.init(); // transactions manager jtxManager = createJtxTransactionManager(connectionProvider); jtxManager.setValidateExistingTransaction(true); AnnotationTxAdviceManager annTxAdviceManager = new AnnotationTxAdviceManager(jtxManager, "$class"); annTxAdviceManager.registerAnnotations(Transaction.class, ReadWriteTransaction.class); AnnotationTxAdviceSupport.manager = annTxAdviceManager; DbSessionProvider sessionProvider = new DbJtxSessionProvider(jtxManager); // global settings DbDefault.debug = debugMode; DbDefault.connectionProvider = connectionProvider; DbDefault.sessionProvider = sessionProvider; DbOrmManager dbOrmManager = createDbOrmManager(); DbOrmManager.setInstance(dbOrmManager); petite.addBean(PETITE_DBORM, dbOrmManager); // automatic configuration AutomagicDbOrmConfigurator dbcfg = new AutomagicDbOrmConfigurator(); dbcfg.setIncludedEntries(scanningPath); dbcfg.configure(dbOrmManager); }
diff --git a/src/prop/hex/presentacio/auxiliars/VistaDialeg.java b/src/prop/hex/presentacio/auxiliars/VistaDialeg.java index 9a05348..fb1d7e5 100644 --- a/src/prop/hex/presentacio/auxiliars/VistaDialeg.java +++ b/src/prop/hex/presentacio/auxiliars/VistaDialeg.java @@ -1,34 +1,34 @@ package prop.hex.presentacio.auxiliars; import javax.swing.*; /** * Vista de diàleg del joc Hex. * * @author Guillermo Girona San Miguel (Grup 7.3, Hex) */ public final class VistaDialeg { /** * Donat el contingut desitjat per a un diàleg, obre el diàleg corresponent i retorna la opció seleccionada. * * @param titol Títol del diàleg. * @param text Text del diàleg. * @param botons Botons que contindrà el diàleg. * @param tipus_joptionpane Tipus de diàleg. * @return El text del botó seleccionat. */ public String setDialeg( String titol, String text, String[] botons, int tipus_joptionpane ) { JOptionPane opcions = new JOptionPane( text, tipus_joptionpane ); opcions.setOptions( botons ); JDialog dialeg = opcions.createDialog( new JFrame(), titol ); - dialeg.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); + dialeg.setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE ); dialeg.pack(); dialeg.setVisible( true ); return ( String ) opcions.getValue(); } }
true
true
public String setDialeg( String titol, String text, String[] botons, int tipus_joptionpane ) { JOptionPane opcions = new JOptionPane( text, tipus_joptionpane ); opcions.setOptions( botons ); JDialog dialeg = opcions.createDialog( new JFrame(), titol ); dialeg.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE ); dialeg.pack(); dialeg.setVisible( true ); return ( String ) opcions.getValue(); }
public String setDialeg( String titol, String text, String[] botons, int tipus_joptionpane ) { JOptionPane opcions = new JOptionPane( text, tipus_joptionpane ); opcions.setOptions( botons ); JDialog dialeg = opcions.createDialog( new JFrame(), titol ); dialeg.setDefaultCloseOperation( JDialog.DO_NOTHING_ON_CLOSE ); dialeg.pack(); dialeg.setVisible( true ); return ( String ) opcions.getValue(); }
diff --git a/src/main/java/com/moac/android/soundmap/SoundMapApplication.java b/src/main/java/com/moac/android/soundmap/SoundMapApplication.java index 95fa2d9..9006604 100644 --- a/src/main/java/com/moac/android/soundmap/SoundMapApplication.java +++ b/src/main/java/com/moac/android/soundmap/SoundMapApplication.java @@ -1,70 +1,70 @@ package com.moac.android.soundmap; import android.app.Application; import android.util.Log; import com.android.volley.RequestQueue; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.moac.android.soundmap.api.ApiClient; import com.moac.android.soundmap.model.GeoLocation; import com.moac.android.soundmap.model.GeoLocationDeserializer; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class SoundMapApplication extends Application { private static final String TAG = SoundMapApplication.class.getSimpleName(); private static SimpleVolley sVolley; private static ApiClient sApiClient; private static Gson sGson = new GsonBuilder().registerTypeAdapter(GeoLocation.class, new GeoLocationDeserializer()).create(); @Override public void onCreate() { Log.i(TAG, "onCreate() - start"); super.onCreate(); sVolley = initVolley(); sApiClient = initApiClient(sVolley.getRequestQueue(), sGson); } public static ApiClient getApiClient() { return sApiClient; } public static SimpleVolley getVolley() { return sVolley; } private SimpleVolley initVolley() { return new SimpleVolley(getApplicationContext()); } private ApiClient initApiClient(RequestQueue _requestQueue, Gson _gson) { - Log.i(TAG, "initApiWrapper() - start"); + Log.i(TAG, "initApiClient() - start"); InputStream inputStream = null; try { inputStream = getAssets().open("soundcloud.properties"); Properties properties = new Properties(); properties.load(inputStream); String apiScheme = properties.getProperty("host.scheme"); String apiDomain = properties.getProperty("host.domain"); String clientId = properties.getProperty("client.id"); String clientSecret = properties.getProperty("client.secret"); - Log.i(TAG, "initApiWrapper() - creating with clientId: " + clientId + " clientSecret: " + clientSecret); + Log.i(TAG, "initApiClient() - creating with clientId: " + clientId + " clientSecret: " + clientSecret); return new ApiClient(_requestQueue, _gson, apiScheme, apiDomain, clientId); } catch(IOException e) { Log.e(TAG, "Failed to initialise API Client", e); throw new RuntimeException("Unable to initialise API Client"); } finally { safeClose(inputStream); } } private void safeClose(InputStream _stream) { if(_stream != null) { try { _stream.close(); } catch(IOException e) { } } } }
false
true
private ApiClient initApiClient(RequestQueue _requestQueue, Gson _gson) { Log.i(TAG, "initApiWrapper() - start"); InputStream inputStream = null; try { inputStream = getAssets().open("soundcloud.properties"); Properties properties = new Properties(); properties.load(inputStream); String apiScheme = properties.getProperty("host.scheme"); String apiDomain = properties.getProperty("host.domain"); String clientId = properties.getProperty("client.id"); String clientSecret = properties.getProperty("client.secret"); Log.i(TAG, "initApiWrapper() - creating with clientId: " + clientId + " clientSecret: " + clientSecret); return new ApiClient(_requestQueue, _gson, apiScheme, apiDomain, clientId); } catch(IOException e) { Log.e(TAG, "Failed to initialise API Client", e); throw new RuntimeException("Unable to initialise API Client"); } finally { safeClose(inputStream); } }
private ApiClient initApiClient(RequestQueue _requestQueue, Gson _gson) { Log.i(TAG, "initApiClient() - start"); InputStream inputStream = null; try { inputStream = getAssets().open("soundcloud.properties"); Properties properties = new Properties(); properties.load(inputStream); String apiScheme = properties.getProperty("host.scheme"); String apiDomain = properties.getProperty("host.domain"); String clientId = properties.getProperty("client.id"); String clientSecret = properties.getProperty("client.secret"); Log.i(TAG, "initApiClient() - creating with clientId: " + clientId + " clientSecret: " + clientSecret); return new ApiClient(_requestQueue, _gson, apiScheme, apiDomain, clientId); } catch(IOException e) { Log.e(TAG, "Failed to initialise API Client", e); throw new RuntimeException("Unable to initialise API Client"); } finally { safeClose(inputStream); } }
diff --git a/src/com/axelby/podax/SubscriptionUpdater.java b/src/com/axelby/podax/SubscriptionUpdater.java index 50dc9b7..7d956c3 100644 --- a/src/com/axelby/podax/SubscriptionUpdater.java +++ b/src/com/axelby/podax/SubscriptionUpdater.java @@ -1,283 +1,283 @@ package com.axelby.podax; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.util.Xml; import com.axelby.podax.R.drawable; import com.axelby.podax.ui.PodcastDetailActivity; import com.axelby.podax.ui.SubscriptionActivity; import com.axelby.riasel.Feed; import com.axelby.riasel.FeedItem; import com.axelby.riasel.FeedParser; public class SubscriptionUpdater { private Context _context; public SubscriptionUpdater(Context context) { _context = context; } public void update(final long subscriptionId) { Cursor cursor = null; try { if (!Helper.ensureWifi(_context)) return; Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId); String[] projection = new String[] { SubscriptionProvider.COLUMN_ID, SubscriptionProvider.COLUMN_TITLE, SubscriptionProvider.COLUMN_URL, SubscriptionProvider.COLUMN_ETAG, SubscriptionProvider.COLUMN_LAST_MODIFIED, }; final ContentValues subscriptionValues = new ContentValues(); cursor = _context.getContentResolver().query(subscriptionUri, projection, SubscriptionProvider.COLUMN_ID + " = ?", new String[] { String.valueOf(subscriptionId) }, null); if (!cursor.moveToNext()) return; SubscriptionCursor subscription = new SubscriptionCursor(cursor); showNotification(subscription); URL url = new URL(subscription.getUrl()); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); if (subscription.getETag() != null) connection.setRequestProperty("If-None-Match", subscription.getETag()); if (subscription.getLastModified() != null && subscription.getLastModified().getTime() > 0) { SimpleDateFormat imsFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); connection.setRequestProperty("If-Modified-Since", imsFormat.format(subscription.getLastModified())); } int code = connection.getResponseCode(); // only valid response code is 200 // 304 (content not modified) is OK too if (code != 200) { return; } String eTag = connection.getHeaderField("ETag"); if (eTag != null) { subscriptionValues.put(SubscriptionProvider.COLUMN_ETAG, eTag); if (eTag.equals(subscription.getETag())) return; } String encoding = connection.getContentEncoding(); if (encoding == null) { String contentType = connection.getContentType(); if (contentType != null && contentType.indexOf(";") > -1) { encoding = contentType.split(";")[1].trim().substring("charset=".length()); } } try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(connection.getInputStream(), encoding); FeedParser feedParser = new FeedParser(); feedParser.setOnFeedInfoHandler(new FeedParser.FeedInfoHandler() { @Override - public void OnFeedInfo(Feed feed) { + public void OnFeedInfo(FeedParser feedParser, Feed feed) { subscriptionValues.putAll(feed.getContentValues()); changeKeyString(subscriptionValues, "lastBuildDate", SubscriptionProvider.COLUMN_LAST_UPDATE); if (feed.getThumbnail() != null) downloadThumbnail(subscriptionId, feed.getThumbnail()); } }); feedParser.setOnFeedItemHandler(new FeedParser.FeedItemHandler() { @Override - public void OnFeedItem(FeedItem item) { + public void OnFeedItem(FeedParser feedParser, FeedItem item) { if (item.getMediaURL() == null || item.getMediaURL().length() == 0) return; ContentValues podcastValues = item.getContentValues(); podcastValues.put(PodcastProvider.COLUMN_SUBSCRIPTION_ID, subscriptionId); // translate Riasel keys to old Podax keys changeKeyString(podcastValues, "mediaURL", PodcastProvider.COLUMN_MEDIA_URL); changeKeyString(podcastValues, "mediaSize", PodcastProvider.COLUMN_FILE_SIZE); changeKeyString(podcastValues, "paymentURL", PodcastProvider.COLUMN_PAYMENT); if (changeKeyLong(podcastValues, "publicationDate", PodcastProvider.COLUMN_PUB_DATE)) podcastValues.put(PodcastProvider.COLUMN_PUB_DATE, podcastValues.getAsLong(PodcastProvider.COLUMN_PUB_DATE) / 1000); if (podcastValues.containsKey(PodcastProvider.COLUMN_MEDIA_URL)) { try { _context.getContentResolver().insert(PodcastProvider.URI, podcastValues); } catch (IllegalArgumentException e) { Log.w("Podax", "error while inserting podcast: " + e.getMessage()); } } } }); feedParser.parseFeed(parser); } catch (XmlPullParserException e) { // not much we can do about this Log.w("Podax", "error in subscription xml: " + e.getMessage()); showUpdateErrorNotification(subscription, _context.getString(R.string.rss_not_valid)); } // finish grabbing subscription values and update subscriptionValues.put(SubscriptionProvider.COLUMN_LAST_UPDATE, new Date().getTime() / 1000); _context.getContentResolver().update(subscriptionUri, subscriptionValues, null, null); writeSubscriptionOPML(); } catch (Exception e) { Log.w("Podax", "error while updating: " + e.getMessage()); } finally { if (cursor != null) cursor.close(); UpdateService.downloadPodcastsSilently(_context); } } private boolean changeKeyString(ContentValues values, String oldKey, String newKey) { if (values.containsKey(oldKey)) { values.put(newKey, values.getAsString(oldKey)); values.remove(oldKey); return true; } return false; }; private boolean changeKeyLong(ContentValues values, String oldKey, String newKey) { if (values.containsKey(oldKey)) { values.put(newKey, values.getAsLong(oldKey)); values.remove(oldKey); return true; } return false; }; private void showUpdateErrorNotification(SubscriptionCursor subscription, String reason) { Intent notificationIntent = new Intent(_context, SubscriptionActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(_context) .setSmallIcon(drawable.icon) .setTicker("Error Updating Subscription") .setWhen(System.currentTimeMillis()) .setContentTitle("Error updating " + subscription.getTitle()) .setContentText(reason) .setContentIntent(contentIntent) .setOngoing(false) .build(); String ns = Context.NOTIFICATION_SERVICE; NotificationManager notificationManager = (NotificationManager) _context.getSystemService(ns); notificationManager.notify(Constants.SUBSCRIPTION_UPDATE_ERROR, notification); } protected void writeSubscriptionOPML() { try { File file = new File(_context.getExternalFilesDir(null), "podax.opml"); FileOutputStream output = new FileOutputStream(file); XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(output, "UTF-8"); serializer.startDocument("UTF-8", true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.startTag(null, "opml"); serializer.attribute(null, "version", "1.0"); serializer.startTag(null, "head"); serializer.startTag(null, "title"); serializer.text("Podax Subscriptions"); serializer.endTag(null, "title"); serializer.endTag(null, "head"); serializer.startTag(null, "body"); String[] projection = { SubscriptionProvider.COLUMN_TITLE, SubscriptionProvider.COLUMN_URL, }; Cursor c = _context.getContentResolver().query(SubscriptionProvider.URI, projection , null, null, SubscriptionProvider.COLUMN_TITLE); while (c.moveToNext()) { SubscriptionCursor sub = new SubscriptionCursor(c); serializer.startTag(null, "outline"); serializer.attribute(null, "type", "rss"); serializer.attribute(null, "title", sub.getTitle()); serializer.attribute(null, "xmlUrl", sub.getUrl()); serializer.endTag(null, "outline"); } c.close(); serializer.endTag(null, "body"); serializer.endTag(null, "opml"); serializer.endDocument(); output.close(); } catch (IOException e) { e.printStackTrace(); } } private void downloadThumbnail(long subscriptionId, String thumbnailUrl) { File thumbnailFile = new File(SubscriptionProvider.getThumbnailFilename(subscriptionId)); if (thumbnailFile.exists()) return; InputStream thumbIn; try { thumbIn = new URL(thumbnailUrl).openStream(); FileOutputStream thumbOut = new FileOutputStream(thumbnailFile.getAbsolutePath()); byte[] buffer = new byte[1024]; int bufferLength = 0; while ( (bufferLength = thumbIn.read(buffer)) > 0 ) thumbOut.write(buffer, 0, bufferLength); thumbOut.close(); thumbIn.close(); } catch (IOException e) { if (thumbnailFile.exists()) thumbnailFile.delete(); } } void showNotification(SubscriptionCursor subscription) { Intent notificationIntent = new Intent(_context, PodcastDetailActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(_context, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(_context) .setSmallIcon(drawable.icon) .setWhen(System.currentTimeMillis()) .setContentTitle("Updating " + subscription.getTitle()) .setContentIntent(contentIntent) .build(); NotificationManager notificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Constants.NOTIFICATION_UPDATE, notification); } }
false
true
public void update(final long subscriptionId) { Cursor cursor = null; try { if (!Helper.ensureWifi(_context)) return; Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId); String[] projection = new String[] { SubscriptionProvider.COLUMN_ID, SubscriptionProvider.COLUMN_TITLE, SubscriptionProvider.COLUMN_URL, SubscriptionProvider.COLUMN_ETAG, SubscriptionProvider.COLUMN_LAST_MODIFIED, }; final ContentValues subscriptionValues = new ContentValues(); cursor = _context.getContentResolver().query(subscriptionUri, projection, SubscriptionProvider.COLUMN_ID + " = ?", new String[] { String.valueOf(subscriptionId) }, null); if (!cursor.moveToNext()) return; SubscriptionCursor subscription = new SubscriptionCursor(cursor); showNotification(subscription); URL url = new URL(subscription.getUrl()); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); if (subscription.getETag() != null) connection.setRequestProperty("If-None-Match", subscription.getETag()); if (subscription.getLastModified() != null && subscription.getLastModified().getTime() > 0) { SimpleDateFormat imsFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); connection.setRequestProperty("If-Modified-Since", imsFormat.format(subscription.getLastModified())); } int code = connection.getResponseCode(); // only valid response code is 200 // 304 (content not modified) is OK too if (code != 200) { return; } String eTag = connection.getHeaderField("ETag"); if (eTag != null) { subscriptionValues.put(SubscriptionProvider.COLUMN_ETAG, eTag); if (eTag.equals(subscription.getETag())) return; } String encoding = connection.getContentEncoding(); if (encoding == null) { String contentType = connection.getContentType(); if (contentType != null && contentType.indexOf(";") > -1) { encoding = contentType.split(";")[1].trim().substring("charset=".length()); } } try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(connection.getInputStream(), encoding); FeedParser feedParser = new FeedParser(); feedParser.setOnFeedInfoHandler(new FeedParser.FeedInfoHandler() { @Override public void OnFeedInfo(Feed feed) { subscriptionValues.putAll(feed.getContentValues()); changeKeyString(subscriptionValues, "lastBuildDate", SubscriptionProvider.COLUMN_LAST_UPDATE); if (feed.getThumbnail() != null) downloadThumbnail(subscriptionId, feed.getThumbnail()); } }); feedParser.setOnFeedItemHandler(new FeedParser.FeedItemHandler() { @Override public void OnFeedItem(FeedItem item) { if (item.getMediaURL() == null || item.getMediaURL().length() == 0) return; ContentValues podcastValues = item.getContentValues(); podcastValues.put(PodcastProvider.COLUMN_SUBSCRIPTION_ID, subscriptionId); // translate Riasel keys to old Podax keys changeKeyString(podcastValues, "mediaURL", PodcastProvider.COLUMN_MEDIA_URL); changeKeyString(podcastValues, "mediaSize", PodcastProvider.COLUMN_FILE_SIZE); changeKeyString(podcastValues, "paymentURL", PodcastProvider.COLUMN_PAYMENT); if (changeKeyLong(podcastValues, "publicationDate", PodcastProvider.COLUMN_PUB_DATE)) podcastValues.put(PodcastProvider.COLUMN_PUB_DATE, podcastValues.getAsLong(PodcastProvider.COLUMN_PUB_DATE) / 1000); if (podcastValues.containsKey(PodcastProvider.COLUMN_MEDIA_URL)) { try { _context.getContentResolver().insert(PodcastProvider.URI, podcastValues); } catch (IllegalArgumentException e) { Log.w("Podax", "error while inserting podcast: " + e.getMessage()); } } } }); feedParser.parseFeed(parser); } catch (XmlPullParserException e) { // not much we can do about this Log.w("Podax", "error in subscription xml: " + e.getMessage()); showUpdateErrorNotification(subscription, _context.getString(R.string.rss_not_valid)); } // finish grabbing subscription values and update subscriptionValues.put(SubscriptionProvider.COLUMN_LAST_UPDATE, new Date().getTime() / 1000); _context.getContentResolver().update(subscriptionUri, subscriptionValues, null, null); writeSubscriptionOPML(); } catch (Exception e) { Log.w("Podax", "error while updating: " + e.getMessage()); } finally { if (cursor != null) cursor.close(); UpdateService.downloadPodcastsSilently(_context); } }
public void update(final long subscriptionId) { Cursor cursor = null; try { if (!Helper.ensureWifi(_context)) return; Uri subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId); String[] projection = new String[] { SubscriptionProvider.COLUMN_ID, SubscriptionProvider.COLUMN_TITLE, SubscriptionProvider.COLUMN_URL, SubscriptionProvider.COLUMN_ETAG, SubscriptionProvider.COLUMN_LAST_MODIFIED, }; final ContentValues subscriptionValues = new ContentValues(); cursor = _context.getContentResolver().query(subscriptionUri, projection, SubscriptionProvider.COLUMN_ID + " = ?", new String[] { String.valueOf(subscriptionId) }, null); if (!cursor.moveToNext()) return; SubscriptionCursor subscription = new SubscriptionCursor(cursor); showNotification(subscription); URL url = new URL(subscription.getUrl()); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); if (subscription.getETag() != null) connection.setRequestProperty("If-None-Match", subscription.getETag()); if (subscription.getLastModified() != null && subscription.getLastModified().getTime() > 0) { SimpleDateFormat imsFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); connection.setRequestProperty("If-Modified-Since", imsFormat.format(subscription.getLastModified())); } int code = connection.getResponseCode(); // only valid response code is 200 // 304 (content not modified) is OK too if (code != 200) { return; } String eTag = connection.getHeaderField("ETag"); if (eTag != null) { subscriptionValues.put(SubscriptionProvider.COLUMN_ETAG, eTag); if (eTag.equals(subscription.getETag())) return; } String encoding = connection.getContentEncoding(); if (encoding == null) { String contentType = connection.getContentType(); if (contentType != null && contentType.indexOf(";") > -1) { encoding = contentType.split(";")[1].trim().substring("charset=".length()); } } try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(connection.getInputStream(), encoding); FeedParser feedParser = new FeedParser(); feedParser.setOnFeedInfoHandler(new FeedParser.FeedInfoHandler() { @Override public void OnFeedInfo(FeedParser feedParser, Feed feed) { subscriptionValues.putAll(feed.getContentValues()); changeKeyString(subscriptionValues, "lastBuildDate", SubscriptionProvider.COLUMN_LAST_UPDATE); if (feed.getThumbnail() != null) downloadThumbnail(subscriptionId, feed.getThumbnail()); } }); feedParser.setOnFeedItemHandler(new FeedParser.FeedItemHandler() { @Override public void OnFeedItem(FeedParser feedParser, FeedItem item) { if (item.getMediaURL() == null || item.getMediaURL().length() == 0) return; ContentValues podcastValues = item.getContentValues(); podcastValues.put(PodcastProvider.COLUMN_SUBSCRIPTION_ID, subscriptionId); // translate Riasel keys to old Podax keys changeKeyString(podcastValues, "mediaURL", PodcastProvider.COLUMN_MEDIA_URL); changeKeyString(podcastValues, "mediaSize", PodcastProvider.COLUMN_FILE_SIZE); changeKeyString(podcastValues, "paymentURL", PodcastProvider.COLUMN_PAYMENT); if (changeKeyLong(podcastValues, "publicationDate", PodcastProvider.COLUMN_PUB_DATE)) podcastValues.put(PodcastProvider.COLUMN_PUB_DATE, podcastValues.getAsLong(PodcastProvider.COLUMN_PUB_DATE) / 1000); if (podcastValues.containsKey(PodcastProvider.COLUMN_MEDIA_URL)) { try { _context.getContentResolver().insert(PodcastProvider.URI, podcastValues); } catch (IllegalArgumentException e) { Log.w("Podax", "error while inserting podcast: " + e.getMessage()); } } } }); feedParser.parseFeed(parser); } catch (XmlPullParserException e) { // not much we can do about this Log.w("Podax", "error in subscription xml: " + e.getMessage()); showUpdateErrorNotification(subscription, _context.getString(R.string.rss_not_valid)); } // finish grabbing subscription values and update subscriptionValues.put(SubscriptionProvider.COLUMN_LAST_UPDATE, new Date().getTime() / 1000); _context.getContentResolver().update(subscriptionUri, subscriptionValues, null, null); writeSubscriptionOPML(); } catch (Exception e) { Log.w("Podax", "error while updating: " + e.getMessage()); } finally { if (cursor != null) cursor.close(); UpdateService.downloadPodcastsSilently(_context); } }
diff --git a/db/src/main/java/com/psddev/dari/db/Application.java b/db/src/main/java/com/psddev/dari/db/Application.java index 60c19241..b4b987ee 100644 --- a/db/src/main/java/com/psddev/dari/db/Application.java +++ b/db/src/main/java/com/psddev/dari/db/Application.java @@ -1,151 +1,153 @@ package com.psddev.dari.db; import org.slf4j.Logger; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.Settings; import com.psddev.dari.util.SettingsException; /** Represents an application. */ @Record.Abstract public class Application extends Record { /** Specifies the class name used to determine the main application. */ public static final String MAIN_CLASS_SETTING = "dari/mainApplicationClass"; @Indexed private String name; private String url; /** Returns the name. */ public String getName() { return name; } /** Sets the name. */ public void setName(String name) { this.name = name; } /** Returns the URL. */ public String getUrl() { return url; } /** Sets the URL. */ public void setUrl(String url) { this.url = url; } /** * Initializes the application, and writes any messages to the given * {@code logger}. By default, this method does nothing, so the * subclasses are expected to override it to provide the desired behavior. */ public void initialize(Logger logger) throws Exception { } /** {@linkplain Application Application} utility methods. */ public final static class Static { private Static() { } /** * Returns the singleton application object matching the given * {@code applicationClass} within the given {@code database}. */ @SuppressWarnings("unchecked") public static <T extends Application> T getInstanceUsing( Class<T> applicationClass, Database database) { ObjectType type = database.getEnvironment().getTypeByClass(applicationClass); - T app = Query.from(applicationClass).using(database).first(); + Query<T> query = Query.from(applicationClass).where("_type = ?", type.getId()).using(database); + query.as(CachingDatabase.QueryOptions.class).setDisabled(true); + T app = query.first(); if (app == null) { DistributedLock lock = DistributedLock.Static.getInstance(database, applicationClass.getName()); lock.lock(); try { - app = Query.from(applicationClass).using(database).first(); + app = query.first(); if (app == null) { app = (T) type.createObject(null); app.setName(type.getDisplayName()); app.saveImmediately(); return app; } } finally { lock.unlock(); } } String oldName = app.getName(); String newName = type.getDisplayName(); if (!ObjectUtils.equals(oldName, newName)) { app.setName(newName); app.save(); } return app; } /** * Returns the singleton application object matching the given * {@code applicationClass} within the {@linkplain * Database.Static#getDefault default database}. */ public static <T extends Application> T getInstance(Class<T> applicationClass) { return getInstanceUsing(applicationClass, Database.Static.getDefault()); } /** * Returns the main application object as determined by the * {@value com.psddev.dari.db.Application#MAIN_CLASS_SETTING} * {@linkplain Settings#get setting} within the given * {@code database}. * * @return May be {@code null} if the setting is not set. * @throws SettingsException If the class name in the setting is not valid. */ public static Application getMainUsing(Database database) { String appClassName = Settings.get(String.class, MAIN_CLASS_SETTING); if (ObjectUtils.isBlank(appClassName)) { return null; } Class<?> objectClass = ObjectUtils.getClassByName(appClassName); if (objectClass == null) { throw new SettingsException(MAIN_CLASS_SETTING, String.format( "[%s] is not a valid class name!", appClassName)); } if (Application.class.isAssignableFrom(objectClass)) { @SuppressWarnings("unchecked") Class<? extends Application> appClass = (Class<? extends Application>) objectClass; return getInstanceUsing(appClass, database); } else { throw new SettingsException(MAIN_CLASS_SETTING, String.format( "[%s] is not a [%s] class!", appClassName, Application.class.getName())); } } /** * Returns the main application object as determined by the * {@value com.psddev.dari.db.Application#MAIN_CLASS_SETTING} * {@linkplain Settings#get setting} within the * {@linkplain Database.Static#getDefault default database}. * * @return May be {@code null} if the setting is not set. * @throws SettingsException If the class name in the setting is not valid. */ public static Application getMain() { return getMainUsing(Database.Static.getDefault()); } } }
false
true
public static <T extends Application> T getInstanceUsing( Class<T> applicationClass, Database database) { ObjectType type = database.getEnvironment().getTypeByClass(applicationClass); T app = Query.from(applicationClass).using(database).first(); if (app == null) { DistributedLock lock = DistributedLock.Static.getInstance(database, applicationClass.getName()); lock.lock(); try { app = Query.from(applicationClass).using(database).first(); if (app == null) { app = (T) type.createObject(null); app.setName(type.getDisplayName()); app.saveImmediately(); return app; } } finally { lock.unlock(); } } String oldName = app.getName(); String newName = type.getDisplayName(); if (!ObjectUtils.equals(oldName, newName)) { app.setName(newName); app.save(); } return app; }
public static <T extends Application> T getInstanceUsing( Class<T> applicationClass, Database database) { ObjectType type = database.getEnvironment().getTypeByClass(applicationClass); Query<T> query = Query.from(applicationClass).where("_type = ?", type.getId()).using(database); query.as(CachingDatabase.QueryOptions.class).setDisabled(true); T app = query.first(); if (app == null) { DistributedLock lock = DistributedLock.Static.getInstance(database, applicationClass.getName()); lock.lock(); try { app = query.first(); if (app == null) { app = (T) type.createObject(null); app.setName(type.getDisplayName()); app.saveImmediately(); return app; } } finally { lock.unlock(); } } String oldName = app.getName(); String newName = type.getDisplayName(); if (!ObjectUtils.equals(oldName, newName)) { app.setName(newName); app.save(); } return app; }
diff --git a/src/TestForestSize.java b/src/TestForestSize.java index 50949b3..b604a47 100644 --- a/src/TestForestSize.java +++ b/src/TestForestSize.java @@ -1,27 +1,29 @@ import java.io.FileNotFoundException; import java.io.IOException; public class TestForestSize { public static void main(String[] argv) throws FileNotFoundException, IOException { if (argv.length < 4) { System.err.println("argument: filestem forestMin forestMax numTrials"); return; } // data set from filestem DataSet d = new DiscreteDataSet(argv[0]); // min and max sizes for decision forest int forestMin = Integer.parseInt(argv[1]); int forestMax = Integer.parseInt(argv[2]); // number of trials to be run per forest size int numTrials = Integer.parseInt(argv[3]); System.out.println("Data set contains " + d.numTrainExs + " examples."); - System.out.println("[forest size], [training error], [cross-set error]"); + System.out.println("[forest size], [trialNum], [training error], [cross-set error]"); for (int i = forestMin; i <= forestMax; i++) { double[][] error = TestHarness.computeError(d, numTrials); - System.out.printf("%d, %f, %f\n", i, error[0], error[1]); + for (int j = 0; j < numTrials; j++) { + System.out.printf("%d, %d, %f, %f\n", i, j, error[j][0], error[j][1]); + } } } }
false
true
public static void main(String[] argv) throws FileNotFoundException, IOException { if (argv.length < 4) { System.err.println("argument: filestem forestMin forestMax numTrials"); return; } // data set from filestem DataSet d = new DiscreteDataSet(argv[0]); // min and max sizes for decision forest int forestMin = Integer.parseInt(argv[1]); int forestMax = Integer.parseInt(argv[2]); // number of trials to be run per forest size int numTrials = Integer.parseInt(argv[3]); System.out.println("Data set contains " + d.numTrainExs + " examples."); System.out.println("[forest size], [training error], [cross-set error]"); for (int i = forestMin; i <= forestMax; i++) { double[][] error = TestHarness.computeError(d, numTrials); System.out.printf("%d, %f, %f\n", i, error[0], error[1]); } }
public static void main(String[] argv) throws FileNotFoundException, IOException { if (argv.length < 4) { System.err.println("argument: filestem forestMin forestMax numTrials"); return; } // data set from filestem DataSet d = new DiscreteDataSet(argv[0]); // min and max sizes for decision forest int forestMin = Integer.parseInt(argv[1]); int forestMax = Integer.parseInt(argv[2]); // number of trials to be run per forest size int numTrials = Integer.parseInt(argv[3]); System.out.println("Data set contains " + d.numTrainExs + " examples."); System.out.println("[forest size], [trialNum], [training error], [cross-set error]"); for (int i = forestMin; i <= forestMax; i++) { double[][] error = TestHarness.computeError(d, numTrials); for (int j = 0; j < numTrials; j++) { System.out.printf("%d, %d, %f, %f\n", i, j, error[j][0], error[j][1]); } } }
diff --git a/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java b/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java index ab708975d..caa33bef3 100644 --- a/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java +++ b/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java @@ -1,799 +1,799 @@ package edu.cmu.sphinx.util.props; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * A property sheet which defines a collection of properties for a single component in the system. * * @author Holger Brandl */ public class PropertySheet implements Cloneable { public static final String COMP_LOG_LEVEL = "logLevel"; public enum PropertyType { INT, DOUBLE, BOOL, COMP, STRING, COMPLIST } private Map<String, S4PropWrapper> registeredProperties = new HashMap<String, S4PropWrapper>(); private Map<String, Object> propValues = new HashMap<String, Object>(); /** * Maps the names of the component properties to their (possibly unresolved) values. * <p/> * Example: <code>frontend</code> to <code>${myFrontEnd}</code> */ private Map<String, Object> rawProps = new HashMap<String, Object>(); private ConfigurationManager cm; private Configurable owner; private final Class<? extends Configurable> ownerClass; private String instanceName; public PropertySheet(Configurable configurable, String name, RawPropertyData rpd, ConfigurationManager ConfigurationManager) { this(configurable.getClass(), name, ConfigurationManager, rpd); owner = configurable; } public PropertySheet(Class<? extends Configurable> confClass, String name, ConfigurationManager cm, RawPropertyData rpd) { ownerClass = confClass; this.cm = cm; this.instanceName = name; processAnnotations(this, confClass); // now apply all xml properties Map<String, Object> flatProps = rpd.flatten(cm).getProperties(); rawProps = new HashMap<String, Object>(rpd.getProperties()); for (String propName : rawProps.keySet()) propValues.put(propName, flatProps.get(propName)); } /** * Registers a new property which type and default value are defined by the given sphinx property. * * @param propName The name of the property to be registered. * @param property The property annoation masked by a proxy. */ private void registerProperty(String propName, S4PropWrapper property) { if (property == null || propName == null) throw new InternalConfigurationException(getInstanceName(), propName, "property or its value is null"); registeredProperties.put(propName, property); propValues.put(propName, null); rawProps.put(propName, null); } /** Returns the property names <code>name</code> which is still wrapped into the annotation instance. */ public S4PropWrapper getProperty(String name, Class propertyClass) throws PropertyException { if (!propValues.containsKey(name)) throw new InternalConfigurationException(getInstanceName(), name, "Unknown property '" + name + "' ! Make sure that you've annotated it."); S4PropWrapper s4PropWrapper = registeredProperties.get(name); try { propertyClass.cast(s4PropWrapper.getAnnotation()); } catch (ClassCastException e) { throw new InternalConfigurationException(e, getInstanceName(), name, name + " is not an annotated sphinx property of '" + getConfigurableClass().getName() + "' !"); } return s4PropWrapper; } /** * Gets the value associated with this name * * @param name the name * @return the value */ public String getString(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4String.class); S4String s4String = ((S4String) s4PropWrapper.getAnnotation()); if (propValues.get(name) == null) { boolean isDefDefined = !s4String.defaultValue().equals(S4String.NOT_DEFINED); if (s4String.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } // else if(!isDefDefined) // throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, isDefDefined ? s4String.defaultValue() : null); } String propValue = flattenProp(name); //check range List<String> range = Arrays.asList(s4String.range()); if (!range.isEmpty() && !range.contains(propValue)) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } private String flattenProp(String name) { Object value = propValues.get(name); return value instanceof String ? (String) value : (value instanceof GlobalProperty ? (String) ((GlobalProperty) value).getValue() : null); } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public int getInt(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Integer.class); S4Integer s4Integer = (S4Integer) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null) { boolean isDefDefined = !(s4Integer.defaultValue() == S4Integer.NOT_DEFINED); if (s4Integer.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, s4Integer.defaultValue()); } Object propObject = propValues.get(name); Integer propValue = propObject instanceof Integer ? (Integer) propObject : Integer.decode(flattenProp(name)); int[] range = s4Integer.range(); if (range.length != 2) throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)"); if (propValue < range[0] || propValue > range[1]) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public float getFloat(String name) throws PropertyException { return ((Double) getDouble(name)).floatValue(); } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public double getDouble(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Double.class); S4Double s4Double = (S4Double) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null) { boolean isDefDefined = !(s4Double.defaultValue() == S4Double.NOT_DEFINED); if (s4Double.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, s4Double.defaultValue()); } Object propObject = propValues.get(name); Double propValue = propObject instanceof Double ? (Double) propObject : Double.valueOf(flattenProp(name)); double[] range = s4Double.range(); if (range.length != 2) throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)"); if (propValue < range[0] || propValue > range[1]) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public Boolean getBoolean(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Boolean.class); S4Boolean s4Boolean = (S4Boolean) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null && !s4Boolean.isNotDefined()) propValues.put(name, s4Boolean.defaultValue()); Object propValue = propValues.get(name); if (propValue instanceof String) propValue = Boolean.valueOf((String) propValue); return (Boolean) propValue; } /** * Gets a component associated with the given parameter name * * @param name the parameter name * @return the component associated with the name * @throws edu.cmu.sphinx.util.props.PropertyException * if the component does not exist or is of the wrong type. */ public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); Object propVal = propValues.get(name); if (propVal == null || propVal instanceof String || propVal instanceof GlobalProperty) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet(flattenProp(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, make sure that it is set if (defClass.equals(Configurable.class)) { if (s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); } else { return null; } } configurable = ConfigurationManager.getInstance(defClass); if (configurable == null) { throw new InternalConfigurationException(getInstanceName(), name, "instantiation of referenenced Configurable failed"); } } } } catch (ClassNotFoundException e) { - throw new PropertyException(e, getInstanceName(), null, null); + throw new PropertyException(e, getInstanceName(), name, null); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); } /** Returns the class of of a registered component property without instantiating it. */ public Class<? extends Configurable> getComponentClass(String propName) { Class<? extends Configurable> defClass = null; if (propValues.get(propName) != null) try { defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(propName)); } catch (ClassNotFoundException e) { e.printStackTrace(); } else { S4Component comAnno = (S4Component) registeredProperties.get(propName).getAnnotation(); defClass = comAnno.defaultClass(); if (comAnno.mandatory()) defClass = null; } return defClass; } /** * Gets a list of components associated with the given parameter name * * @param name the parameter name * @return the component associated with the name * @throws edu.cmu.sphinx.util.props.PropertyException * if the component does not exist or is of the wrong type. */ public List<? extends Configurable> getComponentList(String name) throws InternalConfigurationException { getProperty(name, S4ComponentList.class); List components = (List) propValues.get(name); assert registeredProperties.get(name).getAnnotation() instanceof S4ComponentList; S4ComponentList annoation = (S4ComponentList) registeredProperties.get(name).getAnnotation(); // no componets names are available and no comp-list was yet loaded // therefore load the default list of components from the annoation if (components == null) { List<Class<? extends Configurable>> defClasses = Arrays.asList(annoation.defaultList()); // if (annoation.mandatory() && defClasses.isEmpty()) // throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); components = new ArrayList(); for (Class<? extends Configurable> defClass : defClasses) { components.add(ConfigurationManager.getInstance(defClass)); } propValues.put(name, components); } if (!components.isEmpty() && !(components.get(0) instanceof Configurable)) { List<Configurable> list = new ArrayList<Configurable>(); for (Object componentName : components) { Configurable configurable = cm.lookup((String) componentName); if (configurable != null) { list.add(configurable); } else if (!annoation.beTolerant()) { throw new InternalConfigurationException(name, (String) componentName, "lookup of list-element '" + componentName + "' failed!"); } } propValues.put(name, list); } return (List<? extends Configurable>) propValues.get(name); } public String getInstanceName() { return instanceName; } public void setInstanceName(String newInstanceName) { this.instanceName = newInstanceName; } /** Returns true if the owner of this property sheet is already instanciated. */ public boolean isInstanciated() { return !(owner == null); } /** * Returns the owner of this property sheet. In most cases this will be the configurable instance which was * instrumented by this property sheet. */ public synchronized Configurable getOwner() { try { if (!isInstanciated()) { // ensure that all mandatory properties are set before instantiating the component Collection<String> undefProps = getUndefinedMandatoryProps(); if (!undefProps.isEmpty()) { throw new InternalConfigurationException(getInstanceName(), undefProps.toString(), "not all mandatory properties are defined"); } owner = ownerClass.newInstance(); owner.newProperties(this); } } catch (IllegalAccessException e) { throw new InternalConfigurationException(e, getInstanceName(), null, "Can't access class " + ownerClass); } catch (InstantiationException e) { throw new InternalConfigurationException(e, getInstanceName(), null, "Can't instantiate class " + ownerClass); } return owner; } /** * Returns the set of all component properties which were tagged as mandatory but which are not set (or no default * value is given). */ public Collection<String> getUndefinedMandatoryProps() { Collection<String> undefProps = new ArrayList<String>(); for (String propName : getRegisteredProperties()) { Proxy anno = registeredProperties.get(propName).getAnnotation(); boolean isMandatory = false; if (anno instanceof S4Component) { isMandatory = ((S4Component) anno).mandatory() && ((S4Component) anno).defaultClass() == null; } else if (anno instanceof S4String) { isMandatory = ((S4String) anno).mandatory() && ((S4String) anno).defaultValue().equals(S4String.NOT_DEFINED); } else if (anno instanceof S4Integer) { isMandatory = ((S4Integer) anno).mandatory() && ((S4Integer) anno).defaultValue() == S4Integer.NOT_DEFINED; } else if (anno instanceof S4Double) { isMandatory = ((S4Double) anno).mandatory() && ((S4Double) anno).defaultValue() == S4Double.NOT_DEFINED; } if (isMandatory && !((rawProps.get(propName) != null) || (propValues.get(propName) != null))) undefProps.add(propName); } return undefProps; } /** Returns the class of the owner configurable of this property sheet. */ public Class<? extends Configurable> getConfigurableClass() { return ownerClass; } /** * Sets the given property to the given name * * @param name the simple property name */ public void setString(String name, String value) throws PropertyException { // ensure that there is such a property if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered string-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4String)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type string"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setInt(String name, int value) throws PropertyException { // ensure that there is such a property if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered int-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Integer)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type int"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setDouble(String name, double value) throws PropertyException { // ensure that there is such a property if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered double-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Double)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type double"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setBoolean(String name, Boolean value) throws PropertyException { if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered boolean-property"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Boolean)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type boolean"); applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param cmName the name of the configurable within the configuration manager (required for serialization only) * @param value the value for the property */ public void setComponent(String name, String cmName, Configurable value) throws PropertyException { if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered compontent"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4Component)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type component"); applyConfigurationChange(name, cmName, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param valueNames the list of names of the configurables within the configuration manager (required for * serialization only) * @param value the value for the property */ public void setComponentList(String name, List<String> valueNames, List<Configurable> value) throws PropertyException { if (!registeredProperties.keySet().contains(name)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is not a registered component-list"); Proxy annotation = registeredProperties.get(name).getAnnotation(); if (!(annotation instanceof S4ComponentList)) throw new InternalConfigurationException(getInstanceName(), name, "'" + name + "' is of type component-list"); rawProps.put(name, valueNames); propValues.put(name, value); applyConfigurationChange(name, valueNames, value); } private void applyConfigurationChange(String propName, Object cmName, Object value) throws PropertyException { rawProps.put(propName, cmName); propValues.put(propName, value != null ? value : cmName); if (getInstanceName() != null) cm.fireConfChanged(getInstanceName(), propName); if (owner != null) owner.newProperties(this); } /** * Sets the raw property to the given name * * @param key the simple property name * @param val the value for the property */ void setRaw(String key, Object val) { rawProps.put(key, val); propValues.put(key, null); } /** * Gets the raw value associated with this name * * @param name the name * @return the value as an object (it could be a String or a String[] depending upon the property type) */ public Object getRaw(String name) { return rawProps.get(name); } /** * Gets the raw value associated with this name, no global symbol replacement is performed. * * @param name the name * @return the value as an object (it could be a String or a String[] depending upon the property type) */ public Object getRawNoReplacement(String name) { return rawProps.get(name); } /** Returns the type of the given property. */ public PropertyType getType(String propName) { Proxy annotation = registeredProperties.get(propName).getAnnotation(); if (annotation instanceof S4Component) return PropertyType.COMP; else if (annotation instanceof S4ComponentList) return PropertyType.COMPLIST; else if (annotation instanceof S4Integer) return PropertyType.INT; else if (annotation instanceof S4Double) return PropertyType.DOUBLE; else if (annotation instanceof S4Boolean) return PropertyType.BOOL; else if (annotation instanceof S4String) return PropertyType.STRING; else throw new RuntimeException("Unknown property type"); } /** * Gets the owning property manager * * @return the property manager */ ConfigurationManager getPropertyManager() { return cm; } /** * Returns a logger to use for this configurable component. The logger can be configured with the property: * 'logLevel' - The default logLevel value is defined (within the xml configuration file by the global property * 'defaultLogLevel' (which defaults to WARNING). * <p/> * implementation note: the logger became configured within the constructor of the parenting configuration manager. * * @return the logger for this component * @throws edu.cmu.sphinx.util.props.PropertyException * if an error occurs */ public Logger getLogger() { Logger logger; String baseName = ConfigurationManagerUtils.getLogPrefix(cm) + ownerClass.getName(); if (instanceName != null) { logger = Logger.getLogger(baseName + "." + instanceName); } else logger = Logger.getLogger(baseName); // if there's a logLevel set for component apply to the logger Object rawLogLevel = rawProps.get(COMP_LOG_LEVEL); if (rawLogLevel != null) logger.setLevel(rawLogLevel instanceof String ? Level.parse((String) rawLogLevel) : (Level) rawLogLevel); return logger; } /** Returns the names of registered properties of this PropertySheet object. */ public Collection<String> getRegisteredProperties() { return Collections.unmodifiableCollection(registeredProperties.keySet()); } public void setCM(ConfigurationManager cm) { this.cm = cm; } /** * Returns true if two property sheet define the same object in terms of configuration. The owner (and the parent * configuration manager) are not expected to be the same. */ public boolean equals(Object obj) { if (obj == null || !(obj instanceof PropertySheet)) return false; PropertySheet ps = (PropertySheet) obj; if (!rawProps.keySet().equals(ps.rawProps.keySet())) return false; // maybe we could test a little bit more here. suggestions? return true; } @Override public String toString() { return getInstanceName() + "; isInstantiated=" + isInstanciated() + "; props=" + rawProps.keySet().toString(); } protected Object clone() throws CloneNotSupportedException { PropertySheet ps = (PropertySheet) super.clone(); ps.registeredProperties = new HashMap<String, S4PropWrapper>(this.registeredProperties); ps.propValues = new HashMap<String, Object>(this.propValues); ps.rawProps = new HashMap<String, Object>(this.rawProps); // make deep copy of raw-lists for (String regProp : ps.getRegisteredProperties()) { if (getType(regProp).equals(PropertyType.COMPLIST)) { ps.rawProps.put(regProp, new ArrayList<String>((Collection<? extends String>) rawProps.get(regProp))); ps.propValues.put(regProp, null); } } ps.cm = cm; ps.owner = null; ps.instanceName = this.instanceName; return ps; } /** * use annotation based class parsing to detect the configurable properties of a <code>Configurable</code>-class * * @param propertySheet of type PropertySheet * @param configurable of type Class<? extends Configurable> */ public static void processAnnotations(PropertySheet propertySheet, Class<? extends Configurable> configurable) { Field[] classFields = configurable.getFields(); for (Field field : classFields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { Annotation[] superAnnotations = annotation.annotationType().getAnnotations(); for (Annotation superAnnotation : superAnnotations) { if (superAnnotation instanceof S4Property) { int fieldModifiers = field.getModifiers(); assert Modifier.isStatic(fieldModifiers) : "property fields are assumed to be static"; assert Modifier.isPublic(fieldModifiers) : "property fields are assumed to be public"; assert field.getType().equals(String.class) : "properties fields are assumed to be instances of java.lang.String"; try { String propertyName = (String) field.get(null); // make sure that there is not already another property with this name assert !propertySheet.getRegisteredProperties().contains(propertyName) : "duplicate property-name for different properties: " + propertyName; propertySheet.registerProperty(propertyName, new S4PropWrapper((Proxy) annotation)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } } }
true
true
public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); Object propVal = propValues.get(name); if (propVal == null || propVal instanceof String || propVal instanceof GlobalProperty) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet(flattenProp(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, make sure that it is set if (defClass.equals(Configurable.class)) { if (s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); } else { return null; } } configurable = ConfigurationManager.getInstance(defClass); if (configurable == null) { throw new InternalConfigurationException(getInstanceName(), name, "instantiation of referenenced Configurable failed"); } } } } catch (ClassNotFoundException e) { throw new PropertyException(e, getInstanceName(), null, null); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); }
public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); Object propVal = propValues.get(name); if (propVal == null || propVal instanceof String || propVal instanceof GlobalProperty) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet(flattenProp(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, make sure that it is set if (defClass.equals(Configurable.class)) { if (s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); } else { return null; } } configurable = ConfigurationManager.getInstance(defClass); if (configurable == null) { throw new InternalConfigurationException(getInstanceName(), name, "instantiation of referenenced Configurable failed"); } } } } catch (ClassNotFoundException e) { throw new PropertyException(e, getInstanceName(), name, null); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); }
diff --git a/src/main/java/water/api/GLMProgressPage.java b/src/main/java/water/api/GLMProgressPage.java index dfed67fa6..9407b34c0 100644 --- a/src/main/java/water/api/GLMProgressPage.java +++ b/src/main/java/water/api/GLMProgressPage.java @@ -1,543 +1,543 @@ package water.api; import hex.*; import hex.DGLM.CaseMode; import hex.DGLM.Family; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DGLM.GLMValidation; import hex.DLSM.LSMSolver; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.*; import java.util.Map.Entry; import water.*; import water.Job.ChunkProgress; import water.util.Log; import water.util.RString; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class GLMProgressPage extends Request { static String getTimeStr(long t){ int hrs = (int)(t/(60*60*1000)); t -= hrs*60*60*1000; int mins = (int)(t/60000); t -= mins * 60000; int secs = (int)(t/1000); t -= secs*1000; int millis = (int)t; return hrs + "hrs " + mins + "m " + secs + "s " + millis + "ms"; } protected final H2OKey _job = new H2OKey(JOB,false); protected final H2OKey _dest = new H2OKey(DEST_KEY,true); protected final H2OKey _progress = new H2OKey(PROGRESS_KEY,false); public static Response redirect(JsonObject resp, Key job, Key dest, Key progress) { JsonObject redir = new JsonObject(); if( job != null ) redir.addProperty(JOB, job.toString()); redir.addProperty(DEST_KEY, dest.toString()); redir.addProperty(PROGRESS_KEY, progress.toString()); return Response.redirect(resp, GLMProgressPage.class, redir); } @Override protected Response serve() { JsonObject response = new JsonObject(); Key dest = _dest.value(); response.addProperty(Constants.DEST_KEY, dest.toString()); ChunkProgress p = null; Value v = _progress.value()==null ? null : DKV.get(_progress.value()); if(v != null){ p = v.get(); if(p.error() != null){ UKV.remove(_progress.value()); return Response.error(p.error()); } } GLMModel m = (GLMModel)UKV.get(dest); if(m!=null){ response.addProperty("computation_time", getTimeStr(m._time)); response.add("GLMModel",m.toJson()); } Response r = null; // Display HTML setup if(_job.value()== null || DKV.get(_job.value()) == null) r = Response.done(response); else if(p != null) r = Response.poll(response,p.progress()); else r = Response.poll(response,0); r.setBuilder(""/*top-level do-it-all builder*/,new GLMBuilder(m,_job.value())); return r; } static class GLMBuilder extends ObjectBuilder { final GLMModel _m; GLMBuilder( GLMModel m, Key job) { _m=m; _job = job;} final Key _job; public String build(Response response, JsonObject json, String contextName) { StringBuilder sb = new StringBuilder();; JsonElement mje = json.get(GLMModel.NAME); if( mje == null ) return "<div class='error'>Cancelled!</div>"; modelHTML(_m,mje.getAsJsonObject(),sb); return sb.toString(); } private void modelHTML( GLMModel m, JsonObject json, StringBuilder sb ) { switch(m.status()){ case Done: sb.append("<div class='alert'>Actions: " + (m.isSolved() ? (GLMScore.link(m._key,m._vals[0].bestThreshold(), "Validate on another dataset") + ", "):"") + GLM.link(m._dataKey,m, "Compute new model") + "</div>"); break; case ComputingModel: case ComputingValidation: if(_job != null) sb.append("<div class='alert'>Actions:" + Cancel.link(_job, "Cancel Job") + "</div>"); break; case Cancelled: sb.append("<div class='error'>Cancelled!</div>"); break; default: assert false:"unexpected status " + m.status(); } RString R = new RString( "<div class='alert %succ'>GLM on data <a href='/Inspect.html?"+KEY+"=%key'>%key</a>.<br>" + "%status %iterations iterations computed in %time. %xval %warnings %action</div>" + "<h4>GLM Parameters</h4>" + " %GLMParams %LSMParams" + "<h4>Equation: </h4>" + "<div><code>%modelSrc</code></div>"+ "<h4>Coefficients</h4>" + "<div>%coefficients</div>" + "<h4>Normalized Coefficients</h4>" + "<div>%normalized_coefficients</div>" ); // Warnings if( m._warnings != null && m._warnings.length > 0) { StringBuilder wsb = new StringBuilder(); for( String s : m._warnings ) wsb.append("<br>").append("<b>Warning:</b>" + s); R.replace("warnings",wsb); R.replace("succ","alert-warning"); if(!m.converged()) R.replace("action","Computation did not converge. Suggested action: Go to " + (m.isSolved() ? (GLMGrid.link(m, "Grid search") + ", "):"") + " to search for better parameters"); } else { R.replace("succ","alert-success"); } // Basic model stuff R.replace("key",m._dataKey); R.replace("time",PrettyPrint.msecs(m._time,true)); long xtime = 0; if(m._vals != null) for( GLMValidation v : m._vals ) xtime += v.computationTime(); if( xtime > 0 ) { R.replace("xval", "<br>validations computed in " + PrettyPrint.msecs(xtime, true) +"."); } else { R.replace("xval", ""); } R.replace("status",m.status() + "."); R.replace("iterations",m._iterations); R.replace("GLMParams",glmParamsHTML(m)); R.replace("LSMParams",lsmParamsHTML(m)); // Pretty equations if( m.isSolved() ) { JsonObject coefs = json.get("coefficients").getAsJsonObject(); R.replace("modelSrc",equationHTML(m,coefs)); R.replace("coefficients",coefsHTML(m,coefs)); if(json.has("normalized_coefficients")) R.replace("normalized_coefficients",coefsHTML(m,json.get("normalized_coefficients").getAsJsonObject())); } sb.append(R); // Validation / scoring if(m._vals != null) validationHTML(m,m._vals,sb); } private static final String ALPHA = "&alpha;"; private static final String LAMBDA = "&lambda;"; private static final String EPSILON = "&epsilon;<sub>&beta;</sub>"; private static final DecimalFormat DFORMAT = new DecimalFormat("###.####"); private static final String dformat( double d ) { return Double.isNaN(d) ? "NaN" : DFORMAT.format(d); } private static void parm( StringBuilder sb, String x, Object... y ) { sb.append("<span><b>").append(x).append(": </b>").append(y[0]).append("</span> "); } private static String glmParamsHTML( GLMModel m ) { StringBuilder sb = new StringBuilder(); GLMParams glmp = m._glmParams; parm(sb,"family",glmp._family._family); parm(sb,"link",glmp._link._link); parm(sb,"&alpha;",m._solver._alpha); parm(sb,"&lambda;",m._solver._lambda); parm(sb,EPSILON,glmp._betaEps); if( glmp._caseMode != CaseMode.none) { parm(sb,"case",glmp._caseMode.exp(glmp._caseVal)); parm(sb,"weight",glmp._caseWeight); } return sb.toString(); } private static String lsmParamsHTML( GLMModel m ) { StringBuilder sb = new StringBuilder(); LSMSolver lsm = m._solver; //parm(sb,LAMBDA,lsm._lambda); //parm(sb,ALPHA ,lsm._alpha); return sb.toString(); } // Pretty equations private static String equationHTML( GLMModel m, JsonObject coefs ) { RString eq = null; switch( m._glmParams._link._link ) { case identity: eq = new RString("y = %equation"); break; case logit: eq = new RString("y = 1/(1 + Math.exp(-(%equation)))"); break; case log: eq = new RString("y = Math.exp((%equation)))"); break; case inverse: eq = new RString("y = 1/(%equation)"); break; case tweedie: eq = new RString("y = (%equation)^(1 - " + m._glmParams._link._tweedieLinkPower + ")"); break; default: eq = new RString("equation display not implemented"); break; } StringBuilder sb = new StringBuilder(); for( Entry<String,JsonElement> e : coefs.entrySet() ) { if( e.getKey().equals("Intercept") ) continue; double v = e.getValue().getAsDouble(); if( v == 0 ) continue; sb.append(dformat(v)).append("*x[").append(e.getKey()).append("] + "); } sb.append(coefs.get("Intercept").getAsDouble()); eq.replace("equation",sb.toString()); return eq.toString(); } private static class Coef { final String _name; final double _d; Coef( Entry<String,JsonElement> e ) { _name = e.getKey(); _d = e.getValue().getAsDouble(); } @Override public String toString() { return _name+"="+_d; } } private static String coefsHTML( GLMModel m, JsonObject coefs ) { Set<Entry<String,JsonElement>> ee = coefs.entrySet(); Coef cs[] = new Coef[ee.size()]; int i=0; for( Entry<String,JsonElement> e : ee ) cs[i++] = new Coef(e); Arrays.sort(cs,new Comparator<Coef>() { @Override public int compare(Coef c0, Coef c1) { return (c0._d<c1._d) ? 1 : (c0._d==c1._d?0:-1);} }); StringBuilder sb = new StringBuilder(); sb.append("<table class='table table-bordered table-condensed'>"); sb.append("<tr>"); for( Coef c : cs ) { if(c._name.equals("Intercept"))continue; sb.append("<th>").append(c._name).append("</th>"); } sb.append("<th>").append("Intercept").append("</th>"); sb.append("</tr>"); sb.append("<tr>"); for( Coef c : cs ) { if(c._name.equals("Intercept"))continue; sb.append("<td>").append(c._d).append("</td>"); } sb.append("<td>").append(coefs.get("Intercept").getAsDouble()).append("</td>"); sb.append("</tr>"); sb.append("</table>"); return sb.toString(); } static void validationHTML(GLMModel m, GLMValidation val, StringBuilder sb){ RString valHeader = new RString("<div class='alert'>Validation on dataset <a href='/Inspect.html?"+KEY+"=%dataKey'>%dataKey</a></div>"); RString xvalHeader = new RString("<div class='alert'>%valName</div>"); RString R = new RString("<table class='table table-striped table-bordered table-condensed'>" + "<tr><th>Degrees of freedom:</th><td>%DegreesOfFreedom total (i.e. Null); %ResidualDegreesOfFreedom Residual</td></tr>" + "<tr><th>Null Deviance</th><td>%nullDev</td></tr>" + "<tr><th>Residual Deviance</th><td>%resDev</td></tr>" + "<tr><th>AIC</th><td>%AIC</td></tr>" + "<tr><th>Training Error Rate Avg</th><td>%err</td></tr>" +"%CM" + "</table>"); RString R2 = new RString( "<tr><th>AUC</th><td>%AUC</td></tr>" + "<tr><th>Best Threshold</th><td>%threshold</td></tr>"); if(val.fold() > 1){ xvalHeader.replace("valName", val.fold() + " fold cross validation"); sb.append(xvalHeader.toString()); } else { valHeader.replace("dataKey",val.dataKey()); sb.append(valHeader.toString()); } R.replace("DegreesOfFreedom",m._nLines-1); R.replace("ResidualDegreesOfFreedom",m._dof); R.replace("nullDev",val._nullDeviance); R.replace("resDev",val._deviance); R.replace("AIC", dformat(val.AIC())); R.replace("err",val.err()); if(val._cm != null){ R2.replace("AUC", dformat(val.AUC())); R2.replace("threshold", dformat(val.bestThreshold())); R.replace("CM",R2); } sb.append(R); ROCplot(val, sb); confusionHTML(val.bestCM(),sb); if(val.fold() > 1){ int nclasses = 2; sb.append("<table class='table table-bordered table-condensed'>"); if(val._cm != null){ sb.append("<tr><th>Model</th><th>Best Threshold</th><th>AUC</th>"); for(int c = 0; c < nclasses; ++c) sb.append("<th>Err(" + c + ")</th>"); sb.append("</tr>"); // Display all completed models int i=0; for(GLMModel xm:val.models()){ String mname = "Model " + i++; sb.append("<tr>"); try { sb.append("<td>" + "<a href='Inspect.html?"+KEY+"="+URLEncoder.encode(xm._key.toString(),"UTF-8")+"'>" + mname + "</a></td>"); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } sb.append("<td>" + dformat(xm._vals[0].bestThreshold()) + "</td>"); sb.append("<td>" + dformat(xm._vals[0].AUC()) + "</td>"); for(double e:xm._vals[0].classError()) sb.append("<td>" + dformat(e) + "</td>"); sb.append("</tr>"); } } else { sb.append("<tr><th>Model</th><th>Error</th>"); sb.append("</tr>"); // Display all completed models int i=0; for(GLMModel xm:val.models()){ String mname = "Model " + i++; sb.append("<tr>"); try { sb.append("<td>" + "<a href='Inspect.html?"+KEY+"="+URLEncoder.encode(xm._key.toString(),"UTF-8")+"'>" + mname + "</a></td>"); } catch( UnsupportedEncodingException e ) { throw Log.errRTExcept(e); } sb.append("<td>" + ((xm._vals != null)?xm._vals[0]._err:Double.NaN) + "</td>"); sb.append("</tr>"); } } sb.append("</table>"); } } private static void validationHTML( GLMModel m, GLMValidation[] vals, StringBuilder sb) { if( vals == null || vals.length == 0 ) return; sb.append("<h4>Validations</h4>"); for( GLMValidation val : vals ) if(val != null)validationHTML(m,val, sb); } private static void cmRow( StringBuilder sb, String hd, double c0, double c1, double cerr ) { sb.append("<tr><th>").append(hd).append("</th><td>"); if( !Double.isNaN(c0 )) sb.append( dformat(c0 )); sb.append("</td><td>"); if( !Double.isNaN(c1 )) sb.append( dformat(c1 )); sb.append("</td><td>"); if( !Double.isNaN(cerr)) sb.append( dformat(cerr)); sb.append("</td></tr>"); } private static void confusionHTML( hex.ConfusionMatrix cm, StringBuilder sb) { if( cm == null ) return; sb.append("<table class='table table-bordered table-condensed'>"); sb.append("<tr><th>Actual / Predicted</th><th>false</th><th>true</th><th>Err</th></tr>"); double err0 = cm._arr[0][1]/(double)(cm._arr[0][0]+cm._arr[0][1]); cmRow(sb,"false",cm._arr[0][0],cm._arr[0][1],err0); double err1 = cm._arr[1][0]/(double)(cm._arr[1][0]+cm._arr[1][1]); cmRow(sb,"true ",cm._arr[1][0],cm._arr[1][1],err1); double err2 = cm._arr[1][0]/(double)(cm._arr[0][0]+cm._arr[1][0]); double err3 = cm._arr[0][1]/(double)(cm._arr[0][1]+cm._arr[1][1]); cmRow(sb,"Err ",err2,err3,cm.err()); sb.append("</table>"); } public static void ROCplot(GLMValidation xval, StringBuilder sb ) { sb.append("<script type=\"text/javascript\" src='/h2o/js/d3.v3.min.js'></script>"); sb.append("<div id=\"ROC\">"); sb.append("<style type=\"text/css\">"); sb.append(".axis path," + ".axis line {\n" + "fill: none;\n" + "stroke: black;\n" + "shape-rendering: crispEdges;\n" + "}\n" + ".axis text {\n" + "font-family: sans-serif;\n" + "font-size: 11px;\n" + "}\n"); sb.append("</style>"); sb.append("<div id=\"rocCurve\" style=\"display:inline;\">"); sb.append("<script type=\"text/javascript\">"); sb.append("//Width and height\n"); sb.append("var w = 500;\n"+ "var h = 300;\n"+ "var padding = 40;\n" ); sb.append("var dataset = ["); - if(xval != null && xval._cm != null) { + if(xval != null && xval._cm != null && xval._fprs != null && xval._tprs != null) { for(int c = 0; c < xval._cm.length; c++) { if (c == 0) { sb.append("["+String.valueOf(xval._fprs[c])+",").append(String.valueOf(xval._tprs[c])).append("]"); } sb.append(", ["+String.valueOf(xval._fprs[c])+",").append(String.valueOf(xval._tprs[c])).append("]"); } for(int c = 0; c < 2*xval._cm.length; c++) { sb.append(", ["+String.valueOf(c/(2.0*xval._cm.length))+",").append(String.valueOf(c/(2.0*xval._cm.length))).append("]"); } } sb.append("];\n"); sb.append( "//Create scale functions\n"+ "var xScale = d3.scale.linear()\n"+ ".domain([0, d3.max(dataset, function(d) { return d[0]; })])\n"+ ".range([padding, w - padding * 2]);\n"+ "var yScale = d3.scale.linear()"+ ".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+ ".range([h - padding, padding]);\n"+ "var rScale = d3.scale.linear()"+ ".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+ ".range([2, 5]);\n"+ "//Define X axis\n"+ "var xAxis = d3.svg.axis()\n"+ ".scale(xScale)\n"+ ".orient(\"bottom\")\n"+ ".ticks(5);\n"+ "//Define Y axis\n"+ "var yAxis = d3.svg.axis()\n"+ ".scale(yScale)\n"+ ".orient(\"left\")\n"+ ".ticks(5);\n"+ "//Create SVG element\n"+ "var svg = d3.select(\"#rocCurve\")\n"+ ".append(\"svg\")\n"+ ".attr(\"width\", w)\n"+ ".attr(\"height\", h);\n"+ "//Create circles\n"+ "svg.selectAll(\"circle\")\n"+ ".data(dataset)\n"+ ".enter()\n"+ ".append(\"circle\")\n"+ ".attr(\"cx\", function(d) {\n"+ "return xScale(d[0]);\n"+ "})\n"+ ".attr(\"cy\", function(d) {\n"+ "return yScale(d[1]);\n"+ "})\n"+ ".attr(\"fill\", function(d) {\n"+ " if (d[0] == d[1]) {\n"+ " return \"red\"\n"+ " } else {\n"+ " return \"blue\"\n"+ " }\n"+ "})\n"+ ".attr(\"r\", function(d) {\n"+ " if (d[0] == d[1]) {\n"+ " return 1\n"+ " } else {\n"+ " return 2\n"+ " }\n"+ "})\n" + ".on(\"mouseover\", function(d,i){\n" + " if(i <= 100) {" + " document.getElementById(\"select\").selectedIndex = 100 - i\n" + " show_cm(i)\n" + " }\n" + "});\n"+ "/*"+ "//Create labels\n"+ "svg.selectAll(\"text\")"+ ".data(dataset)"+ ".enter()"+ ".append(\"text\")"+ ".text(function(d) {"+ "return d[0] + \",\" + d[1];"+ "})"+ ".attr(\"x\", function(d) {"+ "return xScale(d[0]);"+ "})"+ ".attr(\"y\", function(d) {"+ "return yScale(d[1]);"+ "})"+ ".attr(\"font-family\", \"sans-serif\")"+ ".attr(\"font-size\", \"11px\")"+ ".attr(\"fill\", \"red\");"+ "*/\n"+ "//Create X axis\n"+ "svg.append(\"g\")"+ ".attr(\"class\", \"axis\")"+ ".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+ ".call(xAxis);\n"+ "//X axis label\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",w/2)"+ ".attr(\"y\",h - 5)"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"False Positive Rate\");\n"+ "//Create Y axis\n"+ "svg.append(\"g\")"+ ".attr(\"class\", \"axis\")"+ ".attr(\"transform\", \"translate(\" + padding + \",0)\")"+ ".call(yAxis);\n"+ "//Y axis label\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",150)"+ ".attr(\"y\",-5)"+ ".attr(\"transform\", \"rotate(90)\")"+ //".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"True Positive Rate\");\n"+ "//Title\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",w/2)"+ ".attr(\"y\",padding - 20)"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"ROC\");\n"); sb.append("</script>"); sb.append("</div>"); } } }
true
true
public static void ROCplot(GLMValidation xval, StringBuilder sb ) { sb.append("<script type=\"text/javascript\" src='/h2o/js/d3.v3.min.js'></script>"); sb.append("<div id=\"ROC\">"); sb.append("<style type=\"text/css\">"); sb.append(".axis path," + ".axis line {\n" + "fill: none;\n" + "stroke: black;\n" + "shape-rendering: crispEdges;\n" + "}\n" + ".axis text {\n" + "font-family: sans-serif;\n" + "font-size: 11px;\n" + "}\n"); sb.append("</style>"); sb.append("<div id=\"rocCurve\" style=\"display:inline;\">"); sb.append("<script type=\"text/javascript\">"); sb.append("//Width and height\n"); sb.append("var w = 500;\n"+ "var h = 300;\n"+ "var padding = 40;\n" ); sb.append("var dataset = ["); if(xval != null && xval._cm != null) { for(int c = 0; c < xval._cm.length; c++) { if (c == 0) { sb.append("["+String.valueOf(xval._fprs[c])+",").append(String.valueOf(xval._tprs[c])).append("]"); } sb.append(", ["+String.valueOf(xval._fprs[c])+",").append(String.valueOf(xval._tprs[c])).append("]"); } for(int c = 0; c < 2*xval._cm.length; c++) { sb.append(", ["+String.valueOf(c/(2.0*xval._cm.length))+",").append(String.valueOf(c/(2.0*xval._cm.length))).append("]"); } } sb.append("];\n"); sb.append( "//Create scale functions\n"+ "var xScale = d3.scale.linear()\n"+ ".domain([0, d3.max(dataset, function(d) { return d[0]; })])\n"+ ".range([padding, w - padding * 2]);\n"+ "var yScale = d3.scale.linear()"+ ".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+ ".range([h - padding, padding]);\n"+ "var rScale = d3.scale.linear()"+ ".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+ ".range([2, 5]);\n"+ "//Define X axis\n"+ "var xAxis = d3.svg.axis()\n"+ ".scale(xScale)\n"+ ".orient(\"bottom\")\n"+ ".ticks(5);\n"+ "//Define Y axis\n"+ "var yAxis = d3.svg.axis()\n"+ ".scale(yScale)\n"+ ".orient(\"left\")\n"+ ".ticks(5);\n"+ "//Create SVG element\n"+ "var svg = d3.select(\"#rocCurve\")\n"+ ".append(\"svg\")\n"+ ".attr(\"width\", w)\n"+ ".attr(\"height\", h);\n"+ "//Create circles\n"+ "svg.selectAll(\"circle\")\n"+ ".data(dataset)\n"+ ".enter()\n"+ ".append(\"circle\")\n"+ ".attr(\"cx\", function(d) {\n"+ "return xScale(d[0]);\n"+ "})\n"+ ".attr(\"cy\", function(d) {\n"+ "return yScale(d[1]);\n"+ "})\n"+ ".attr(\"fill\", function(d) {\n"+ " if (d[0] == d[1]) {\n"+ " return \"red\"\n"+ " } else {\n"+ " return \"blue\"\n"+ " }\n"+ "})\n"+ ".attr(\"r\", function(d) {\n"+ " if (d[0] == d[1]) {\n"+ " return 1\n"+ " } else {\n"+ " return 2\n"+ " }\n"+ "})\n" + ".on(\"mouseover\", function(d,i){\n" + " if(i <= 100) {" + " document.getElementById(\"select\").selectedIndex = 100 - i\n" + " show_cm(i)\n" + " }\n" + "});\n"+ "/*"+ "//Create labels\n"+ "svg.selectAll(\"text\")"+ ".data(dataset)"+ ".enter()"+ ".append(\"text\")"+ ".text(function(d) {"+ "return d[0] + \",\" + d[1];"+ "})"+ ".attr(\"x\", function(d) {"+ "return xScale(d[0]);"+ "})"+ ".attr(\"y\", function(d) {"+ "return yScale(d[1]);"+ "})"+ ".attr(\"font-family\", \"sans-serif\")"+ ".attr(\"font-size\", \"11px\")"+ ".attr(\"fill\", \"red\");"+ "*/\n"+ "//Create X axis\n"+ "svg.append(\"g\")"+ ".attr(\"class\", \"axis\")"+ ".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+ ".call(xAxis);\n"+ "//X axis label\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",w/2)"+ ".attr(\"y\",h - 5)"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"False Positive Rate\");\n"+ "//Create Y axis\n"+ "svg.append(\"g\")"+ ".attr(\"class\", \"axis\")"+ ".attr(\"transform\", \"translate(\" + padding + \",0)\")"+ ".call(yAxis);\n"+ "//Y axis label\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",150)"+ ".attr(\"y\",-5)"+ ".attr(\"transform\", \"rotate(90)\")"+ //".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"True Positive Rate\");\n"+ "//Title\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",w/2)"+ ".attr(\"y\",padding - 20)"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"ROC\");\n"); sb.append("</script>"); sb.append("</div>"); }
public static void ROCplot(GLMValidation xval, StringBuilder sb ) { sb.append("<script type=\"text/javascript\" src='/h2o/js/d3.v3.min.js'></script>"); sb.append("<div id=\"ROC\">"); sb.append("<style type=\"text/css\">"); sb.append(".axis path," + ".axis line {\n" + "fill: none;\n" + "stroke: black;\n" + "shape-rendering: crispEdges;\n" + "}\n" + ".axis text {\n" + "font-family: sans-serif;\n" + "font-size: 11px;\n" + "}\n"); sb.append("</style>"); sb.append("<div id=\"rocCurve\" style=\"display:inline;\">"); sb.append("<script type=\"text/javascript\">"); sb.append("//Width and height\n"); sb.append("var w = 500;\n"+ "var h = 300;\n"+ "var padding = 40;\n" ); sb.append("var dataset = ["); if(xval != null && xval._cm != null && xval._fprs != null && xval._tprs != null) { for(int c = 0; c < xval._cm.length; c++) { if (c == 0) { sb.append("["+String.valueOf(xval._fprs[c])+",").append(String.valueOf(xval._tprs[c])).append("]"); } sb.append(", ["+String.valueOf(xval._fprs[c])+",").append(String.valueOf(xval._tprs[c])).append("]"); } for(int c = 0; c < 2*xval._cm.length; c++) { sb.append(", ["+String.valueOf(c/(2.0*xval._cm.length))+",").append(String.valueOf(c/(2.0*xval._cm.length))).append("]"); } } sb.append("];\n"); sb.append( "//Create scale functions\n"+ "var xScale = d3.scale.linear()\n"+ ".domain([0, d3.max(dataset, function(d) { return d[0]; })])\n"+ ".range([padding, w - padding * 2]);\n"+ "var yScale = d3.scale.linear()"+ ".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+ ".range([h - padding, padding]);\n"+ "var rScale = d3.scale.linear()"+ ".domain([0, d3.max(dataset, function(d) { return d[1]; })])\n"+ ".range([2, 5]);\n"+ "//Define X axis\n"+ "var xAxis = d3.svg.axis()\n"+ ".scale(xScale)\n"+ ".orient(\"bottom\")\n"+ ".ticks(5);\n"+ "//Define Y axis\n"+ "var yAxis = d3.svg.axis()\n"+ ".scale(yScale)\n"+ ".orient(\"left\")\n"+ ".ticks(5);\n"+ "//Create SVG element\n"+ "var svg = d3.select(\"#rocCurve\")\n"+ ".append(\"svg\")\n"+ ".attr(\"width\", w)\n"+ ".attr(\"height\", h);\n"+ "//Create circles\n"+ "svg.selectAll(\"circle\")\n"+ ".data(dataset)\n"+ ".enter()\n"+ ".append(\"circle\")\n"+ ".attr(\"cx\", function(d) {\n"+ "return xScale(d[0]);\n"+ "})\n"+ ".attr(\"cy\", function(d) {\n"+ "return yScale(d[1]);\n"+ "})\n"+ ".attr(\"fill\", function(d) {\n"+ " if (d[0] == d[1]) {\n"+ " return \"red\"\n"+ " } else {\n"+ " return \"blue\"\n"+ " }\n"+ "})\n"+ ".attr(\"r\", function(d) {\n"+ " if (d[0] == d[1]) {\n"+ " return 1\n"+ " } else {\n"+ " return 2\n"+ " }\n"+ "})\n" + ".on(\"mouseover\", function(d,i){\n" + " if(i <= 100) {" + " document.getElementById(\"select\").selectedIndex = 100 - i\n" + " show_cm(i)\n" + " }\n" + "});\n"+ "/*"+ "//Create labels\n"+ "svg.selectAll(\"text\")"+ ".data(dataset)"+ ".enter()"+ ".append(\"text\")"+ ".text(function(d) {"+ "return d[0] + \",\" + d[1];"+ "})"+ ".attr(\"x\", function(d) {"+ "return xScale(d[0]);"+ "})"+ ".attr(\"y\", function(d) {"+ "return yScale(d[1]);"+ "})"+ ".attr(\"font-family\", \"sans-serif\")"+ ".attr(\"font-size\", \"11px\")"+ ".attr(\"fill\", \"red\");"+ "*/\n"+ "//Create X axis\n"+ "svg.append(\"g\")"+ ".attr(\"class\", \"axis\")"+ ".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+ ".call(xAxis);\n"+ "//X axis label\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",w/2)"+ ".attr(\"y\",h - 5)"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"False Positive Rate\");\n"+ "//Create Y axis\n"+ "svg.append(\"g\")"+ ".attr(\"class\", \"axis\")"+ ".attr(\"transform\", \"translate(\" + padding + \",0)\")"+ ".call(yAxis);\n"+ "//Y axis label\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",150)"+ ".attr(\"y\",-5)"+ ".attr(\"transform\", \"rotate(90)\")"+ //".attr(\"transform\", \"translate(0,\" + (h - padding) + \")\")"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"True Positive Rate\");\n"+ "//Title\n"+ "d3.select('#rocCurve svg')"+ ".append(\"text\")"+ ".attr(\"x\",w/2)"+ ".attr(\"y\",padding - 20)"+ ".attr(\"text-anchor\", \"middle\")"+ ".text(\"ROC\");\n"); sb.append("</script>"); sb.append("</div>"); }
diff --git a/src/edu/uvm/nesc/SyntaxViewer.java b/src/edu/uvm/nesc/SyntaxViewer.java index 82180dd..ef48077 100644 --- a/src/edu/uvm/nesc/SyntaxViewer.java +++ b/src/edu/uvm/nesc/SyntaxViewer.java @@ -1,876 +1,876 @@ //----------------------------------------------------------------------- // FILE : SyntaxViewer.java // SUBJECT : Class that allows an abstract syntax tree to be viewed. // AUTHOR : (C) Copyright 2012 by Peter C. Chapin <[email protected]> // //----------------------------------------------------------------------- package edu.uvm.nesc; import java.io.PrintStream; import java.util.Stack; import org.antlr.runtime.tree.*; /** * Provides a nice way to view SpartanRPC abstract syntax trees. * @author Peter C. Chapin */ public class SyntaxViewer { private PrintStream sink; private Tree syntaxTree; private int indentationLevel = 0; private boolean suppressRewriting = false; // Used to handle parentheses in nested declarators in a nice way. Consider, for example, // int (*p)(int x); // In this case the declarator '*p' should be parenthesized, but neither the declarator 'x' nor the overall // declarator needs to be. (Note that they could be, but that is ugly). // private Stack<Integer> declaratorNestingLevels = new Stack<>(); // Used to prevent the top level expression from being parenthesized. For example, normally we have something like // this: // ( x = ( a * ( b + c ) ) ); // If this flag is set to false before rewriting this expression we have instead: // x = ( a * ( b + c ) ); // This looks a little nicer (especially in, for example, the conditional expressions of if, while, and for loops). // Fully "correct" handling of this issue would require the rewriter to consider operator precedence when deciding // when to parenthesize. // private boolean enableExpressionParentheses = true; /** * Constructs a SyntaxViewer. * * @param outputDestination The object into which the output is sent. * @param syntax The tree that this viewer will use. */ public SyntaxViewer(PrintStream outputDestination, Tree syntax) { sink = outputDestination; syntaxTree = syntax; declaratorNestingLevels.push(0); } /** * Outputs the entire syntax tree in ANTLR's tree notation. The output is sent to the PrintStream object previously * given to the constructor. This method adds a '\n' to the end of the output. * */ public void writeAST() { sink.print(syntaxTree.toStringTree()); sink.print("\n"); } /** * Indents by an amount related to the current indentation level. This method is used during rewriting to make the * output look approximately nice. */ private void indent() { for (int i = 0; i < indentationLevel; ++i) { sink.print(" "); } } /** * Outputs the entire syntax tree in source code form. The output is sent to the PrintStream object previously given * to the constructor. This method adds a '\n' to the end of the output. * */ public void rewrite() { rewrite(syntaxTree); sink.print("\n"); } /** * Outputs the syntax tree rooted at t in source code form. The output is sent to the PrintStream object previously * given to the constructor. * * @param t The tree to output. */ private void rewrite(Tree t) { int value; int currentChild; // Used when processing structure or enumeration declarations. switch (t.getType()) { // Putting a space after all occurrences of RAW_IDENTIFIER is overkill. However it is important to include a // space after RAW_IDENTIFIERS that are type names (at least when they appear as a declaration specifier in // a declaration or function definition). Ideally the rewriter for those constructs would include the extra // space when necessary. However, it is easier to just include it here. Aside from making the output look a // little funny, the extra space is harmless in other cases. // case nesCLexer.RAW_IDENTIFIER: sink.print(t.getText()); sink.print(" "); break; // Declarations // ------------ // Raw tokens. These tokens just stand for themselves in the AST. These cases could be handled by the // default case instead. However, having them here makes it explicit which tokens should be processed in // this way. (Eventually the default case should probably be changed to throw an exception of some kind to // indicate that an unexpected token was encountered). // case nesCLexer.ASYNC: case nesCLexer.AUTO: case nesCLexer.CALL: case nesCLexer.CHAR: case nesCLexer.COMMAND: case nesCLexer.CONST: case nesCLexer.EXTERN: case nesCLexer.EVENT: case nesCLexer.INLINE: case nesCLexer.INT: case nesCLexer.NORACE: case nesCLexer.POST: case nesCLexer.REGISTER: case nesCLexer.RESTRICT: case nesCLexer.SHORT: case nesCLexer.SIGNAL: case nesCLexer.SIGNED: case nesCLexer.STATIC: case nesCLexer.TASK: case nesCLexer.TYPEDEF: case nesCLexer.UNSIGNED: case nesCLexer.VOID: case nesCLexer.VOLATILE: sink.print(t.getText()); sink.print(" "); break; case nesCLexer.DECLARATION: indent(); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.RAW_IDENTIFIER) sink.print(" "); } if (t.getChild(0).getType() != nesCLexer.FUNCTION_DEFINITION) { sink.print(";"); } sink.print("\n"); break; case nesCLexer.STRUCT: case nesCLexer.UNION: case nesCLexer.NX_STRUCT: case nesCLexer.NX_UNION: sink.print(t.getText()); sink.print(" "); currentChild = 0; if (t.getChild(currentChild).getType() != nesCLexer.DECLARATION) { rewrite(t.getChild(currentChild)); sink.print(" "); ++currentChild; } if (currentChild < t.getChildCount()) { sink.print("{\n"); ++indentationLevel; while (currentChild < t.getChildCount()) { rewrite(t.getChild(currentChild)); ++currentChild; } --indentationLevel; indent(); sink.print("} "); } break; case nesCLexer.ENUM: sink.print("enum "); currentChild = 0; if (t.getChild(currentChild).getType() != nesCLexer.ENUMERATOR) { rewrite(t.getChild(currentChild)); sink.print(" "); ++currentChild; } if (currentChild < t.getChildCount()) { sink.print("{ "); boolean firstTime = true; while (currentChild < t.getChildCount()) { if (!firstTime) sink.print(", "); rewrite(t.getChild(currentChild)); firstTime = false; ++currentChild; } sink.print("} "); } break; case nesCLexer.ENUMERATOR: rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" = "); rewrite(t.getChild(1)); } break; case nesCLexer.DECLARATOR_LIST: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } break; case nesCLexer.INIT_DECLARATOR: rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" = "); for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } } break; case nesCLexer.DECLARATOR: if (declaratorNestingLevels.peek() != 0) sink.print("("); value = declaratorNestingLevels.pop(); declaratorNestingLevels.push(value + 1); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); sink.print(" "); } value = declaratorNestingLevels.pop(); declaratorNestingLevels.push(value - 1); if (declaratorNestingLevels.peek() != 0) sink.print(")"); break; case nesCLexer.INITIALIZER_LIST: sink.print("{ "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(" }"); break; case nesCLexer.POINTER_QUALIFIER: sink.print("*"); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; case nesCLexer.DECLARATOR_ARRAY_MODIFIER: sink.print("["); if (t.getChildCount() != 0) rewrite(t.getChild(0)); sink.print("]"); break; case nesCLexer.DECLARATOR_PARAMETER_LIST_MODIFIER: sink.print("( "); rewrite(t.getChild(0)); sink.print(" )"); break; case nesCLexer.PARAMETER_LIST: declaratorNestingLevels.push(0); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } declaratorNestingLevels.pop(); break; case nesCLexer.PARAMETER: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.RAW_IDENTIFIER) sink.print(" "); } break; case nesCLexer.FUNCTION_DEFINITION: for (int i = 0; i < t.getChildCount(); ++i) { if (t.getChild(i).getType() == nesCLexer.COMPOUND_STATEMENT) { sink.print("\n"); ++indentationLevel; // This is a hack. } rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.COMPOUND_STATEMENT) { --indentationLevel; } } break; // Statements // ---------- // Expression statements are handled here. case nesCLexer.STATEMENT: indent(); enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(";\n"); break; case nesCLexer.COMPOUND_STATEMENT: // Outdent the braces. --indentationLevel; indent(); sink.print("{\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); ++indentationLevel; break; case nesCLexer.LABELED_STATEMENT: // Outdent the label. --indentationLevel; indent(); sink.print(t.getChild(0)); ++indentationLevel; sink.print(":\n"); rewrite(t.getChild(1)); break; case nesCLexer.CASE: // Outdent the case label. --indentationLevel; indent(); sink.print("case "); rewrite(t.getChild(0)); sink.print(":\n"); ++indentationLevel; rewrite(t.getChild(1)); break; // This handles 'default' in switch statements, but not in declarations. case nesCLexer.DEFAULT: // Outdent the default label. --indentationLevel; indent(); sink.print("default:\n"); ++indentationLevel; rewrite(t.getChild(0)); case nesCLexer.ATOMIC: indent(); sink.print("atomic\n"); ++indentationLevel; rewrite(t.getChild(0)); --indentationLevel; break; case nesCLexer.IF: indent(); sink.print("if( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; if (t.getChildCount() == 3) { indent(); sink.print("else\n"); ++indentationLevel; rewrite(t.getChild(2)); --indentationLevel; } break; case nesCLexer.SWITCH: indent(); sink.print("switch( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; break; case nesCLexer.WHILE: indent(); sink.print("while( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; break; case nesCLexer.DO: indent(); sink.print("do\n"); ++indentationLevel; rewrite(t.getChild(0)); --indentationLevel; indent(); sink.print("while( "); enableExpressionParentheses = false; rewrite(t.getChild(1)); enableExpressionParentheses = true; sink.print(");\n"); break; case nesCLexer.FOR: indent(); sink.print("for( "); // The loop header. for (int i = 0; i < 3; ++i) { if (i != 0) sink.print("; "); rewrite(t.getChild(i)); } sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(3)); // The controlled statement. --indentationLevel; break; case nesCLexer.FOR_INITIALIZE: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.FOR_CONDITION: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.FOR_ITERATION: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.GOTO: indent(); sink.print("goto "); rewrite(t.getChild(1)); sink.print(";\n"); break; case nesCLexer.CONTINUE: indent(); sink.print("continue;\n"); break; case nesCLexer.BREAK: indent(); sink.print("break;\n"); break; case nesCLexer.RETURN: indent(); sink.print("return "); if (t.getChildCount() == 1) rewrite(t.getChild(0)); sink.print(";\n"); break; // Expressions // ----------- // All binary infix operators are handled the same way. case nesCLexer.AMP: case nesCLexer.AND: case nesCLexer.ASSIGN: case nesCLexer.BITANDASSIGN: case nesCLexer.BITOR: case nesCLexer.BITORASSIGN: case nesCLexer.BITXOR: case nesCLexer.BITXORASSIGN: case nesCLexer.COMMA: case nesCLexer.DIVASSIGN: case nesCLexer.DIVIDE: case nesCLexer.EQUAL: case nesCLexer.GREATER: case nesCLexer.GREATEREQUAL: case nesCLexer.LESS: case nesCLexer.LESSEQUAL: case nesCLexer.LSHIFT: case nesCLexer.LSHIFTASSIGN: case nesCLexer.MINUS: case nesCLexer.MINUSASSIGN: case nesCLexer.MODULUS: case nesCLexer.MODASSIGN: case nesCLexer.NOTEQUAL: case nesCLexer.OR: case nesCLexer.PLUS: case nesCLexer.PLUSASSIGN: case nesCLexer.RSHIFT: case nesCLexer.RSHIFTASSIGN: case nesCLexer.STAR: boolean oldExpressionParentheses = enableExpressionParentheses; if (enableExpressionParentheses) sink.print("( "); enableExpressionParentheses = true; rewrite(t.getChild(0)); // The left operand. sink.print(" "); sink.print(t.getText()); // The operator itself. sink.print(" "); rewrite(t.getChild(1)); // The right operand. enableExpressionParentheses = oldExpressionParentheses; if (enableExpressionParentheses) sink.print(" )"); break; case nesCLexer.POSTFIX_EXPRESSION: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; case nesCLexer.BUILTIN_VA_ARG: sink.print("__builtin_va_arg("); rewrite(t.getChild(0)); sink.print(", "); rewrite(t.getChild(1)); sink.print(")"); break; case nesCLexer.ARGUMENT_LIST: sink.print("( "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(" )"); break; case nesCLexer.ARRAY_ELEMENT_SELECTION: sink.print("["); rewrite(t.getChild(0)); sink.print("]"); break; case nesCLexer.DOT: sink.print("."); rewrite(t.getChild(0)); break; case nesCLexer.ARROW: sink.print("->"); rewrite(t.getChild(0)); break; case nesCLexer.PLUSPLUS: sink.print("++"); break; case nesCLexer.MINUSMINUS: sink.print("--"); break; case nesCLexer.PRE_INCREMENT: sink.print("++"); rewrite(t.getChild(0)); break; case nesCLexer.PRE_DECREMENT: sink.print("--"); rewrite(t.getChild(0)); break; case nesCLexer.ADDRESS_OF: sink.print("&"); rewrite(t.getChild(0)); break; case nesCLexer.UNARY_PLUS: sink.print("+"); rewrite(t.getChild(0)); break; case nesCLexer.UNARY_MINUS: sink.print("-"); rewrite(t.getChild(0)); break; // Perhaps the AST does not need to distinguish between these cases. case nesCLexer.SIZEOF_TYPE: case nesCLexer.SIZEOF_EXPRESSION: sink.print("sizeof( "); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } sink.print(" )"); break; case nesCLexer.CAST: sink.print("("); for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } sink.print(")( "); rewrite(t.getChild(0)); sink.print(" )"); break; case nesCLexer.BITCOMPLEMENT: sink.print("~"); rewrite(t.getChild(0)); break; case nesCLexer.NOT: sink.print("!"); rewrite(t.getChild(0)); break; // The AST distinguishes this use of '*' from multiplication. How nice. case nesCLexer.DEREFERENCE: sink.print("( *"); rewrite(t.getChild(0)); sink.print(" )"); break; // Large Scale Structure // --------------------- case nesCLexer.FILE: for (int i = 0; i < t.getChildCount(); ++i) { if (!suppressRewriting || t.getChild(i).getType() == nesCLexer.LINE_DIRECTIVE) rewrite(t.getChild(i)); } break; // This is a simple hack. Emit a #include for line directives that reference header files. If #includes were // nested this will cause spurious #include directives to be emitted here. However, that should not cause // any problems for the back end nesC compiler. Note that the AST for material in a header file should not // be rewritten. However, when a line directive for the main .nc file is encountered, rewriting should be // turned on again. // case nesCLexer.LINE_DIRECTIVE: String fileNameWithQuotes = t.getChild(0).getText(); if (fileNameWithQuotes.endsWith(".h\"") || fileNameWithQuotes.endsWith(".h>")) { // We always output Unix style names. Even on Windows, the program will be compiled under Cygwin. fileNameWithQuotes = fileNameWithQuotes.replace("\\\\", "/"); // // TODO: Generalize to produce Cygwin paths on Windows and normal paths on Unix. // if (fileNameWithQuotes.startsWith("\"/cygwin")) { // fileNameWithQuotes = "\"" + fileNameWithQuotes.substring(8); // } // // I assume absolute paths need to be replaced for Cygwin. This will be false on Unix systems. // else if (fileNameWithQuotes.startsWith("\"/")) { // fileNameWithQuotes = "\"/cygdrive/c" + fileNameWithQuotes.substring(1); // } // Output the reconstructed #include directive. sink.print("#include " + fileNameWithQuotes + "\n"); suppressRewriting = true; } else { suppressRewriting = false; } break; case nesCLexer.INTERFACE: // This is correct for 'interface' as it appears in specifications. if (t.getChild(0).getType() == nesCLexer.INTERFACE_TYPE) { indent(); sink.print("interface "); rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" as "); rewrite(t.getChild(1)); } sink.print(";\n"); } // Otherwise we are defining an interface type. else { sink.print("interface "); sink.print(t.getChild(0)); sink.print(" {\n"); ++indentationLevel; for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); } break; case nesCLexer.COMPONENT_DEFINITION: rewrite(t.getChild(0)); // The kind of component. rewrite(t.getChild(1)); // Name of the configuration. // Component parameters, if present. Tree componentParameters = null; if (t.getChildCount() == 5) { componentParameters = t.getChild(4); } else if (t.getChildCount() == 4 && t.getChild(3).getType() == nesCLexer.COMPONENT_PARAMETER_LIST) { componentParameters = t.getChild(3); } if (componentParameters != null) rewrite(componentParameters); rewrite(t.getChild(2)); // Specification. // Implementation, if present. if (t.getChildCount() >= 4 && t.getChild(3).getType() == nesCLexer.IMPLEMENTATION) { rewrite(t.getChild(3)); } break; case nesCLexer.COMPONENT_KIND: switch (t.getChild(0).getType()) { case nesCLexer.CONFIGURATION: sink.print("configuration "); break; case nesCLexer.MODULE: sink.print("module "); break; case nesCLexer.GENERIC: switch (t.getChild(1).getType()) { case nesCLexer.CONFIGURATION: sink.print("generic configuration "); break; case nesCLexer.MODULE: sink.print("generic module "); break; } break; } break; case nesCLexer.COMPONENT_PARAMETER_LIST: sink.print("("); for (int i = 0; i < t.getChildCount(); ++i) { if (i > 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(") "); break; case nesCLexer.SPECIFICATION: sink.print(" {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); break; case nesCLexer.USES: indent(); sink.print("uses {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); break; case nesCLexer.PROVIDES: indent(); sink.print("provides {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); break; case nesCLexer.INTERFACE_TYPE: // Assume there is no 'remotable' or 'with' parts left in the AST. sink.print(t.getChild(0)); if (t.getChildCount() > 1) { sink.print("<"); for (int i = 1; i < t.getChildCount(); ++i) { if (i != 1) sink.print(", "); rewrite(t.getChild(i)); } sink.print(">"); } break; case nesCLexer.IMPLEMENTATION: sink.print("implementation {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { if (!suppressRewriting || t.getChild(i).getType() == nesCLexer.LINE_DIRECTIVE) rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); break; // Configuration Implementation // ---------------------------- case nesCLexer.COMPONENTS: indent(); sink.print("components "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(";\n"); break; case nesCLexer.COMPONENT_DECLARATION: rewrite(t.getChild(0)); // The component_ref. if (t.getChildCount() == 2) { sink.print(" as "); rewrite(t.getChild(1)); // The component's alias (if there is one). } break; case nesCLexer.COMPONENT_INSTANTIATION: sink.print("new "); rewrite(t.getChild(0)); sink.print("( "); if (t.getChildCount() > 1) { rewrite(t.getChild(1)); } sink.print(" )"); break; case nesCLexer.COMPONENT_ARGUMENTS: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } break; case nesCLexer.CONNECTION: indent(); rewrite(t.getChild(1)); sink.print(" "); sink.print(t.getChild(0).getText()); sink.print(" "); - rewrite(t.getChild(2)); + rewrite(t.getChild(0).getChild(0)); sink.print(";\n"); break; case nesCLexer.IDENTIFIER_PATH: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print("."); rewrite(t.getChild(i)); } break; // The NULL token should probably not appear in the trees given to this method. It is intended to be used as // a placeholder by other programs that manipulate trees (such as Sprocket). The idea is that all NULL // tokens would be removed from the tree before rewriting. However, in case a NULL token does remain, the // code below does the most natural thing with it. // case nesCLexer.NULL: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; // Is it right to have this default case? It is useful during development because it shows the "next" token // that needs to be implemented in order to get a proper rewriting. // default: sink.print(t.getText()); sink.print(" "); break; } } }
true
true
private void rewrite(Tree t) { int value; int currentChild; // Used when processing structure or enumeration declarations. switch (t.getType()) { // Putting a space after all occurrences of RAW_IDENTIFIER is overkill. However it is important to include a // space after RAW_IDENTIFIERS that are type names (at least when they appear as a declaration specifier in // a declaration or function definition). Ideally the rewriter for those constructs would include the extra // space when necessary. However, it is easier to just include it here. Aside from making the output look a // little funny, the extra space is harmless in other cases. // case nesCLexer.RAW_IDENTIFIER: sink.print(t.getText()); sink.print(" "); break; // Declarations // ------------ // Raw tokens. These tokens just stand for themselves in the AST. These cases could be handled by the // default case instead. However, having them here makes it explicit which tokens should be processed in // this way. (Eventually the default case should probably be changed to throw an exception of some kind to // indicate that an unexpected token was encountered). // case nesCLexer.ASYNC: case nesCLexer.AUTO: case nesCLexer.CALL: case nesCLexer.CHAR: case nesCLexer.COMMAND: case nesCLexer.CONST: case nesCLexer.EXTERN: case nesCLexer.EVENT: case nesCLexer.INLINE: case nesCLexer.INT: case nesCLexer.NORACE: case nesCLexer.POST: case nesCLexer.REGISTER: case nesCLexer.RESTRICT: case nesCLexer.SHORT: case nesCLexer.SIGNAL: case nesCLexer.SIGNED: case nesCLexer.STATIC: case nesCLexer.TASK: case nesCLexer.TYPEDEF: case nesCLexer.UNSIGNED: case nesCLexer.VOID: case nesCLexer.VOLATILE: sink.print(t.getText()); sink.print(" "); break; case nesCLexer.DECLARATION: indent(); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.RAW_IDENTIFIER) sink.print(" "); } if (t.getChild(0).getType() != nesCLexer.FUNCTION_DEFINITION) { sink.print(";"); } sink.print("\n"); break; case nesCLexer.STRUCT: case nesCLexer.UNION: case nesCLexer.NX_STRUCT: case nesCLexer.NX_UNION: sink.print(t.getText()); sink.print(" "); currentChild = 0; if (t.getChild(currentChild).getType() != nesCLexer.DECLARATION) { rewrite(t.getChild(currentChild)); sink.print(" "); ++currentChild; } if (currentChild < t.getChildCount()) { sink.print("{\n"); ++indentationLevel; while (currentChild < t.getChildCount()) { rewrite(t.getChild(currentChild)); ++currentChild; } --indentationLevel; indent(); sink.print("} "); } break; case nesCLexer.ENUM: sink.print("enum "); currentChild = 0; if (t.getChild(currentChild).getType() != nesCLexer.ENUMERATOR) { rewrite(t.getChild(currentChild)); sink.print(" "); ++currentChild; } if (currentChild < t.getChildCount()) { sink.print("{ "); boolean firstTime = true; while (currentChild < t.getChildCount()) { if (!firstTime) sink.print(", "); rewrite(t.getChild(currentChild)); firstTime = false; ++currentChild; } sink.print("} "); } break; case nesCLexer.ENUMERATOR: rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" = "); rewrite(t.getChild(1)); } break; case nesCLexer.DECLARATOR_LIST: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } break; case nesCLexer.INIT_DECLARATOR: rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" = "); for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } } break; case nesCLexer.DECLARATOR: if (declaratorNestingLevels.peek() != 0) sink.print("("); value = declaratorNestingLevels.pop(); declaratorNestingLevels.push(value + 1); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); sink.print(" "); } value = declaratorNestingLevels.pop(); declaratorNestingLevels.push(value - 1); if (declaratorNestingLevels.peek() != 0) sink.print(")"); break; case nesCLexer.INITIALIZER_LIST: sink.print("{ "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(" }"); break; case nesCLexer.POINTER_QUALIFIER: sink.print("*"); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; case nesCLexer.DECLARATOR_ARRAY_MODIFIER: sink.print("["); if (t.getChildCount() != 0) rewrite(t.getChild(0)); sink.print("]"); break; case nesCLexer.DECLARATOR_PARAMETER_LIST_MODIFIER: sink.print("( "); rewrite(t.getChild(0)); sink.print(" )"); break; case nesCLexer.PARAMETER_LIST: declaratorNestingLevels.push(0); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } declaratorNestingLevels.pop(); break; case nesCLexer.PARAMETER: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.RAW_IDENTIFIER) sink.print(" "); } break; case nesCLexer.FUNCTION_DEFINITION: for (int i = 0; i < t.getChildCount(); ++i) { if (t.getChild(i).getType() == nesCLexer.COMPOUND_STATEMENT) { sink.print("\n"); ++indentationLevel; // This is a hack. } rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.COMPOUND_STATEMENT) { --indentationLevel; } } break; // Statements // ---------- // Expression statements are handled here. case nesCLexer.STATEMENT: indent(); enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(";\n"); break; case nesCLexer.COMPOUND_STATEMENT: // Outdent the braces. --indentationLevel; indent(); sink.print("{\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); ++indentationLevel; break; case nesCLexer.LABELED_STATEMENT: // Outdent the label. --indentationLevel; indent(); sink.print(t.getChild(0)); ++indentationLevel; sink.print(":\n"); rewrite(t.getChild(1)); break; case nesCLexer.CASE: // Outdent the case label. --indentationLevel; indent(); sink.print("case "); rewrite(t.getChild(0)); sink.print(":\n"); ++indentationLevel; rewrite(t.getChild(1)); break; // This handles 'default' in switch statements, but not in declarations. case nesCLexer.DEFAULT: // Outdent the default label. --indentationLevel; indent(); sink.print("default:\n"); ++indentationLevel; rewrite(t.getChild(0)); case nesCLexer.ATOMIC: indent(); sink.print("atomic\n"); ++indentationLevel; rewrite(t.getChild(0)); --indentationLevel; break; case nesCLexer.IF: indent(); sink.print("if( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; if (t.getChildCount() == 3) { indent(); sink.print("else\n"); ++indentationLevel; rewrite(t.getChild(2)); --indentationLevel; } break; case nesCLexer.SWITCH: indent(); sink.print("switch( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; break; case nesCLexer.WHILE: indent(); sink.print("while( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; break; case nesCLexer.DO: indent(); sink.print("do\n"); ++indentationLevel; rewrite(t.getChild(0)); --indentationLevel; indent(); sink.print("while( "); enableExpressionParentheses = false; rewrite(t.getChild(1)); enableExpressionParentheses = true; sink.print(");\n"); break; case nesCLexer.FOR: indent(); sink.print("for( "); // The loop header. for (int i = 0; i < 3; ++i) { if (i != 0) sink.print("; "); rewrite(t.getChild(i)); } sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(3)); // The controlled statement. --indentationLevel; break; case nesCLexer.FOR_INITIALIZE: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.FOR_CONDITION: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.FOR_ITERATION: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.GOTO: indent(); sink.print("goto "); rewrite(t.getChild(1)); sink.print(";\n"); break; case nesCLexer.CONTINUE: indent(); sink.print("continue;\n"); break; case nesCLexer.BREAK: indent(); sink.print("break;\n"); break; case nesCLexer.RETURN: indent(); sink.print("return "); if (t.getChildCount() == 1) rewrite(t.getChild(0)); sink.print(";\n"); break; // Expressions // ----------- // All binary infix operators are handled the same way. case nesCLexer.AMP: case nesCLexer.AND: case nesCLexer.ASSIGN: case nesCLexer.BITANDASSIGN: case nesCLexer.BITOR: case nesCLexer.BITORASSIGN: case nesCLexer.BITXOR: case nesCLexer.BITXORASSIGN: case nesCLexer.COMMA: case nesCLexer.DIVASSIGN: case nesCLexer.DIVIDE: case nesCLexer.EQUAL: case nesCLexer.GREATER: case nesCLexer.GREATEREQUAL: case nesCLexer.LESS: case nesCLexer.LESSEQUAL: case nesCLexer.LSHIFT: case nesCLexer.LSHIFTASSIGN: case nesCLexer.MINUS: case nesCLexer.MINUSASSIGN: case nesCLexer.MODULUS: case nesCLexer.MODASSIGN: case nesCLexer.NOTEQUAL: case nesCLexer.OR: case nesCLexer.PLUS: case nesCLexer.PLUSASSIGN: case nesCLexer.RSHIFT: case nesCLexer.RSHIFTASSIGN: case nesCLexer.STAR: boolean oldExpressionParentheses = enableExpressionParentheses; if (enableExpressionParentheses) sink.print("( "); enableExpressionParentheses = true; rewrite(t.getChild(0)); // The left operand. sink.print(" "); sink.print(t.getText()); // The operator itself. sink.print(" "); rewrite(t.getChild(1)); // The right operand. enableExpressionParentheses = oldExpressionParentheses; if (enableExpressionParentheses) sink.print(" )"); break; case nesCLexer.POSTFIX_EXPRESSION: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; case nesCLexer.BUILTIN_VA_ARG: sink.print("__builtin_va_arg("); rewrite(t.getChild(0)); sink.print(", "); rewrite(t.getChild(1)); sink.print(")"); break; case nesCLexer.ARGUMENT_LIST: sink.print("( "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(" )"); break; case nesCLexer.ARRAY_ELEMENT_SELECTION: sink.print("["); rewrite(t.getChild(0)); sink.print("]"); break; case nesCLexer.DOT: sink.print("."); rewrite(t.getChild(0)); break; case nesCLexer.ARROW: sink.print("->"); rewrite(t.getChild(0)); break; case nesCLexer.PLUSPLUS: sink.print("++"); break; case nesCLexer.MINUSMINUS: sink.print("--"); break; case nesCLexer.PRE_INCREMENT: sink.print("++"); rewrite(t.getChild(0)); break; case nesCLexer.PRE_DECREMENT: sink.print("--"); rewrite(t.getChild(0)); break; case nesCLexer.ADDRESS_OF: sink.print("&"); rewrite(t.getChild(0)); break; case nesCLexer.UNARY_PLUS: sink.print("+"); rewrite(t.getChild(0)); break; case nesCLexer.UNARY_MINUS: sink.print("-"); rewrite(t.getChild(0)); break; // Perhaps the AST does not need to distinguish between these cases. case nesCLexer.SIZEOF_TYPE: case nesCLexer.SIZEOF_EXPRESSION: sink.print("sizeof( "); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } sink.print(" )"); break; case nesCLexer.CAST: sink.print("("); for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } sink.print(")( "); rewrite(t.getChild(0)); sink.print(" )"); break; case nesCLexer.BITCOMPLEMENT: sink.print("~"); rewrite(t.getChild(0)); break; case nesCLexer.NOT: sink.print("!"); rewrite(t.getChild(0)); break; // The AST distinguishes this use of '*' from multiplication. How nice. case nesCLexer.DEREFERENCE: sink.print("( *"); rewrite(t.getChild(0)); sink.print(" )"); break; // Large Scale Structure // --------------------- case nesCLexer.FILE: for (int i = 0; i < t.getChildCount(); ++i) { if (!suppressRewriting || t.getChild(i).getType() == nesCLexer.LINE_DIRECTIVE) rewrite(t.getChild(i)); } break; // This is a simple hack. Emit a #include for line directives that reference header files. If #includes were // nested this will cause spurious #include directives to be emitted here. However, that should not cause // any problems for the back end nesC compiler. Note that the AST for material in a header file should not // be rewritten. However, when a line directive for the main .nc file is encountered, rewriting should be // turned on again. // case nesCLexer.LINE_DIRECTIVE: String fileNameWithQuotes = t.getChild(0).getText(); if (fileNameWithQuotes.endsWith(".h\"") || fileNameWithQuotes.endsWith(".h>")) { // We always output Unix style names. Even on Windows, the program will be compiled under Cygwin. fileNameWithQuotes = fileNameWithQuotes.replace("\\\\", "/"); // // TODO: Generalize to produce Cygwin paths on Windows and normal paths on Unix. // if (fileNameWithQuotes.startsWith("\"/cygwin")) { // fileNameWithQuotes = "\"" + fileNameWithQuotes.substring(8); // } // // I assume absolute paths need to be replaced for Cygwin. This will be false on Unix systems. // else if (fileNameWithQuotes.startsWith("\"/")) { // fileNameWithQuotes = "\"/cygdrive/c" + fileNameWithQuotes.substring(1); // } // Output the reconstructed #include directive. sink.print("#include " + fileNameWithQuotes + "\n"); suppressRewriting = true; } else { suppressRewriting = false; } break; case nesCLexer.INTERFACE: // This is correct for 'interface' as it appears in specifications. if (t.getChild(0).getType() == nesCLexer.INTERFACE_TYPE) { indent(); sink.print("interface "); rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" as "); rewrite(t.getChild(1)); } sink.print(";\n"); } // Otherwise we are defining an interface type. else { sink.print("interface "); sink.print(t.getChild(0)); sink.print(" {\n"); ++indentationLevel; for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); } break; case nesCLexer.COMPONENT_DEFINITION: rewrite(t.getChild(0)); // The kind of component. rewrite(t.getChild(1)); // Name of the configuration. // Component parameters, if present. Tree componentParameters = null; if (t.getChildCount() == 5) { componentParameters = t.getChild(4); } else if (t.getChildCount() == 4 && t.getChild(3).getType() == nesCLexer.COMPONENT_PARAMETER_LIST) { componentParameters = t.getChild(3); } if (componentParameters != null) rewrite(componentParameters); rewrite(t.getChild(2)); // Specification. // Implementation, if present. if (t.getChildCount() >= 4 && t.getChild(3).getType() == nesCLexer.IMPLEMENTATION) { rewrite(t.getChild(3)); } break; case nesCLexer.COMPONENT_KIND: switch (t.getChild(0).getType()) { case nesCLexer.CONFIGURATION: sink.print("configuration "); break; case nesCLexer.MODULE: sink.print("module "); break; case nesCLexer.GENERIC: switch (t.getChild(1).getType()) { case nesCLexer.CONFIGURATION: sink.print("generic configuration "); break; case nesCLexer.MODULE: sink.print("generic module "); break; } break; } break; case nesCLexer.COMPONENT_PARAMETER_LIST: sink.print("("); for (int i = 0; i < t.getChildCount(); ++i) { if (i > 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(") "); break; case nesCLexer.SPECIFICATION: sink.print(" {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); break; case nesCLexer.USES: indent(); sink.print("uses {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); break; case nesCLexer.PROVIDES: indent(); sink.print("provides {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); break; case nesCLexer.INTERFACE_TYPE: // Assume there is no 'remotable' or 'with' parts left in the AST. sink.print(t.getChild(0)); if (t.getChildCount() > 1) { sink.print("<"); for (int i = 1; i < t.getChildCount(); ++i) { if (i != 1) sink.print(", "); rewrite(t.getChild(i)); } sink.print(">"); } break; case nesCLexer.IMPLEMENTATION: sink.print("implementation {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { if (!suppressRewriting || t.getChild(i).getType() == nesCLexer.LINE_DIRECTIVE) rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); break; // Configuration Implementation // ---------------------------- case nesCLexer.COMPONENTS: indent(); sink.print("components "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(";\n"); break; case nesCLexer.COMPONENT_DECLARATION: rewrite(t.getChild(0)); // The component_ref. if (t.getChildCount() == 2) { sink.print(" as "); rewrite(t.getChild(1)); // The component's alias (if there is one). } break; case nesCLexer.COMPONENT_INSTANTIATION: sink.print("new "); rewrite(t.getChild(0)); sink.print("( "); if (t.getChildCount() > 1) { rewrite(t.getChild(1)); } sink.print(" )"); break; case nesCLexer.COMPONENT_ARGUMENTS: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } break; case nesCLexer.CONNECTION: indent(); rewrite(t.getChild(1)); sink.print(" "); sink.print(t.getChild(0).getText()); sink.print(" "); rewrite(t.getChild(2)); sink.print(";\n"); break; case nesCLexer.IDENTIFIER_PATH: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print("."); rewrite(t.getChild(i)); } break; // The NULL token should probably not appear in the trees given to this method. It is intended to be used as // a placeholder by other programs that manipulate trees (such as Sprocket). The idea is that all NULL // tokens would be removed from the tree before rewriting. However, in case a NULL token does remain, the // code below does the most natural thing with it. // case nesCLexer.NULL: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; // Is it right to have this default case? It is useful during development because it shows the "next" token // that needs to be implemented in order to get a proper rewriting. // default: sink.print(t.getText()); sink.print(" "); break; } }
private void rewrite(Tree t) { int value; int currentChild; // Used when processing structure or enumeration declarations. switch (t.getType()) { // Putting a space after all occurrences of RAW_IDENTIFIER is overkill. However it is important to include a // space after RAW_IDENTIFIERS that are type names (at least when they appear as a declaration specifier in // a declaration or function definition). Ideally the rewriter for those constructs would include the extra // space when necessary. However, it is easier to just include it here. Aside from making the output look a // little funny, the extra space is harmless in other cases. // case nesCLexer.RAW_IDENTIFIER: sink.print(t.getText()); sink.print(" "); break; // Declarations // ------------ // Raw tokens. These tokens just stand for themselves in the AST. These cases could be handled by the // default case instead. However, having them here makes it explicit which tokens should be processed in // this way. (Eventually the default case should probably be changed to throw an exception of some kind to // indicate that an unexpected token was encountered). // case nesCLexer.ASYNC: case nesCLexer.AUTO: case nesCLexer.CALL: case nesCLexer.CHAR: case nesCLexer.COMMAND: case nesCLexer.CONST: case nesCLexer.EXTERN: case nesCLexer.EVENT: case nesCLexer.INLINE: case nesCLexer.INT: case nesCLexer.NORACE: case nesCLexer.POST: case nesCLexer.REGISTER: case nesCLexer.RESTRICT: case nesCLexer.SHORT: case nesCLexer.SIGNAL: case nesCLexer.SIGNED: case nesCLexer.STATIC: case nesCLexer.TASK: case nesCLexer.TYPEDEF: case nesCLexer.UNSIGNED: case nesCLexer.VOID: case nesCLexer.VOLATILE: sink.print(t.getText()); sink.print(" "); break; case nesCLexer.DECLARATION: indent(); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.RAW_IDENTIFIER) sink.print(" "); } if (t.getChild(0).getType() != nesCLexer.FUNCTION_DEFINITION) { sink.print(";"); } sink.print("\n"); break; case nesCLexer.STRUCT: case nesCLexer.UNION: case nesCLexer.NX_STRUCT: case nesCLexer.NX_UNION: sink.print(t.getText()); sink.print(" "); currentChild = 0; if (t.getChild(currentChild).getType() != nesCLexer.DECLARATION) { rewrite(t.getChild(currentChild)); sink.print(" "); ++currentChild; } if (currentChild < t.getChildCount()) { sink.print("{\n"); ++indentationLevel; while (currentChild < t.getChildCount()) { rewrite(t.getChild(currentChild)); ++currentChild; } --indentationLevel; indent(); sink.print("} "); } break; case nesCLexer.ENUM: sink.print("enum "); currentChild = 0; if (t.getChild(currentChild).getType() != nesCLexer.ENUMERATOR) { rewrite(t.getChild(currentChild)); sink.print(" "); ++currentChild; } if (currentChild < t.getChildCount()) { sink.print("{ "); boolean firstTime = true; while (currentChild < t.getChildCount()) { if (!firstTime) sink.print(", "); rewrite(t.getChild(currentChild)); firstTime = false; ++currentChild; } sink.print("} "); } break; case nesCLexer.ENUMERATOR: rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" = "); rewrite(t.getChild(1)); } break; case nesCLexer.DECLARATOR_LIST: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } break; case nesCLexer.INIT_DECLARATOR: rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" = "); for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } } break; case nesCLexer.DECLARATOR: if (declaratorNestingLevels.peek() != 0) sink.print("("); value = declaratorNestingLevels.pop(); declaratorNestingLevels.push(value + 1); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); sink.print(" "); } value = declaratorNestingLevels.pop(); declaratorNestingLevels.push(value - 1); if (declaratorNestingLevels.peek() != 0) sink.print(")"); break; case nesCLexer.INITIALIZER_LIST: sink.print("{ "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(" }"); break; case nesCLexer.POINTER_QUALIFIER: sink.print("*"); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; case nesCLexer.DECLARATOR_ARRAY_MODIFIER: sink.print("["); if (t.getChildCount() != 0) rewrite(t.getChild(0)); sink.print("]"); break; case nesCLexer.DECLARATOR_PARAMETER_LIST_MODIFIER: sink.print("( "); rewrite(t.getChild(0)); sink.print(" )"); break; case nesCLexer.PARAMETER_LIST: declaratorNestingLevels.push(0); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } declaratorNestingLevels.pop(); break; case nesCLexer.PARAMETER: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.RAW_IDENTIFIER) sink.print(" "); } break; case nesCLexer.FUNCTION_DEFINITION: for (int i = 0; i < t.getChildCount(); ++i) { if (t.getChild(i).getType() == nesCLexer.COMPOUND_STATEMENT) { sink.print("\n"); ++indentationLevel; // This is a hack. } rewrite(t.getChild(i)); if (t.getChild(i).getType() == nesCLexer.COMPOUND_STATEMENT) { --indentationLevel; } } break; // Statements // ---------- // Expression statements are handled here. case nesCLexer.STATEMENT: indent(); enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(";\n"); break; case nesCLexer.COMPOUND_STATEMENT: // Outdent the braces. --indentationLevel; indent(); sink.print("{\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); ++indentationLevel; break; case nesCLexer.LABELED_STATEMENT: // Outdent the label. --indentationLevel; indent(); sink.print(t.getChild(0)); ++indentationLevel; sink.print(":\n"); rewrite(t.getChild(1)); break; case nesCLexer.CASE: // Outdent the case label. --indentationLevel; indent(); sink.print("case "); rewrite(t.getChild(0)); sink.print(":\n"); ++indentationLevel; rewrite(t.getChild(1)); break; // This handles 'default' in switch statements, but not in declarations. case nesCLexer.DEFAULT: // Outdent the default label. --indentationLevel; indent(); sink.print("default:\n"); ++indentationLevel; rewrite(t.getChild(0)); case nesCLexer.ATOMIC: indent(); sink.print("atomic\n"); ++indentationLevel; rewrite(t.getChild(0)); --indentationLevel; break; case nesCLexer.IF: indent(); sink.print("if( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; if (t.getChildCount() == 3) { indent(); sink.print("else\n"); ++indentationLevel; rewrite(t.getChild(2)); --indentationLevel; } break; case nesCLexer.SWITCH: indent(); sink.print("switch( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; break; case nesCLexer.WHILE: indent(); sink.print("while( "); enableExpressionParentheses = false; rewrite(t.getChild(0)); enableExpressionParentheses = true; sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(1)); --indentationLevel; break; case nesCLexer.DO: indent(); sink.print("do\n"); ++indentationLevel; rewrite(t.getChild(0)); --indentationLevel; indent(); sink.print("while( "); enableExpressionParentheses = false; rewrite(t.getChild(1)); enableExpressionParentheses = true; sink.print(");\n"); break; case nesCLexer.FOR: indent(); sink.print("for( "); // The loop header. for (int i = 0; i < 3; ++i) { if (i != 0) sink.print("; "); rewrite(t.getChild(i)); } sink.print(" )\n"); ++indentationLevel; rewrite(t.getChild(3)); // The controlled statement. --indentationLevel; break; case nesCLexer.FOR_INITIALIZE: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.FOR_CONDITION: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.FOR_ITERATION: enableExpressionParentheses = false; if (t.getChildCount() == 1) rewrite(t.getChild(0)); enableExpressionParentheses = true; break; case nesCLexer.GOTO: indent(); sink.print("goto "); rewrite(t.getChild(1)); sink.print(";\n"); break; case nesCLexer.CONTINUE: indent(); sink.print("continue;\n"); break; case nesCLexer.BREAK: indent(); sink.print("break;\n"); break; case nesCLexer.RETURN: indent(); sink.print("return "); if (t.getChildCount() == 1) rewrite(t.getChild(0)); sink.print(";\n"); break; // Expressions // ----------- // All binary infix operators are handled the same way. case nesCLexer.AMP: case nesCLexer.AND: case nesCLexer.ASSIGN: case nesCLexer.BITANDASSIGN: case nesCLexer.BITOR: case nesCLexer.BITORASSIGN: case nesCLexer.BITXOR: case nesCLexer.BITXORASSIGN: case nesCLexer.COMMA: case nesCLexer.DIVASSIGN: case nesCLexer.DIVIDE: case nesCLexer.EQUAL: case nesCLexer.GREATER: case nesCLexer.GREATEREQUAL: case nesCLexer.LESS: case nesCLexer.LESSEQUAL: case nesCLexer.LSHIFT: case nesCLexer.LSHIFTASSIGN: case nesCLexer.MINUS: case nesCLexer.MINUSASSIGN: case nesCLexer.MODULUS: case nesCLexer.MODASSIGN: case nesCLexer.NOTEQUAL: case nesCLexer.OR: case nesCLexer.PLUS: case nesCLexer.PLUSASSIGN: case nesCLexer.RSHIFT: case nesCLexer.RSHIFTASSIGN: case nesCLexer.STAR: boolean oldExpressionParentheses = enableExpressionParentheses; if (enableExpressionParentheses) sink.print("( "); enableExpressionParentheses = true; rewrite(t.getChild(0)); // The left operand. sink.print(" "); sink.print(t.getText()); // The operator itself. sink.print(" "); rewrite(t.getChild(1)); // The right operand. enableExpressionParentheses = oldExpressionParentheses; if (enableExpressionParentheses) sink.print(" )"); break; case nesCLexer.POSTFIX_EXPRESSION: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; case nesCLexer.BUILTIN_VA_ARG: sink.print("__builtin_va_arg("); rewrite(t.getChild(0)); sink.print(", "); rewrite(t.getChild(1)); sink.print(")"); break; case nesCLexer.ARGUMENT_LIST: sink.print("( "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(" )"); break; case nesCLexer.ARRAY_ELEMENT_SELECTION: sink.print("["); rewrite(t.getChild(0)); sink.print("]"); break; case nesCLexer.DOT: sink.print("."); rewrite(t.getChild(0)); break; case nesCLexer.ARROW: sink.print("->"); rewrite(t.getChild(0)); break; case nesCLexer.PLUSPLUS: sink.print("++"); break; case nesCLexer.MINUSMINUS: sink.print("--"); break; case nesCLexer.PRE_INCREMENT: sink.print("++"); rewrite(t.getChild(0)); break; case nesCLexer.PRE_DECREMENT: sink.print("--"); rewrite(t.getChild(0)); break; case nesCLexer.ADDRESS_OF: sink.print("&"); rewrite(t.getChild(0)); break; case nesCLexer.UNARY_PLUS: sink.print("+"); rewrite(t.getChild(0)); break; case nesCLexer.UNARY_MINUS: sink.print("-"); rewrite(t.getChild(0)); break; // Perhaps the AST does not need to distinguish between these cases. case nesCLexer.SIZEOF_TYPE: case nesCLexer.SIZEOF_EXPRESSION: sink.print("sizeof( "); for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } sink.print(" )"); break; case nesCLexer.CAST: sink.print("("); for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } sink.print(")( "); rewrite(t.getChild(0)); sink.print(" )"); break; case nesCLexer.BITCOMPLEMENT: sink.print("~"); rewrite(t.getChild(0)); break; case nesCLexer.NOT: sink.print("!"); rewrite(t.getChild(0)); break; // The AST distinguishes this use of '*' from multiplication. How nice. case nesCLexer.DEREFERENCE: sink.print("( *"); rewrite(t.getChild(0)); sink.print(" )"); break; // Large Scale Structure // --------------------- case nesCLexer.FILE: for (int i = 0; i < t.getChildCount(); ++i) { if (!suppressRewriting || t.getChild(i).getType() == nesCLexer.LINE_DIRECTIVE) rewrite(t.getChild(i)); } break; // This is a simple hack. Emit a #include for line directives that reference header files. If #includes were // nested this will cause spurious #include directives to be emitted here. However, that should not cause // any problems for the back end nesC compiler. Note that the AST for material in a header file should not // be rewritten. However, when a line directive for the main .nc file is encountered, rewriting should be // turned on again. // case nesCLexer.LINE_DIRECTIVE: String fileNameWithQuotes = t.getChild(0).getText(); if (fileNameWithQuotes.endsWith(".h\"") || fileNameWithQuotes.endsWith(".h>")) { // We always output Unix style names. Even on Windows, the program will be compiled under Cygwin. fileNameWithQuotes = fileNameWithQuotes.replace("\\\\", "/"); // // TODO: Generalize to produce Cygwin paths on Windows and normal paths on Unix. // if (fileNameWithQuotes.startsWith("\"/cygwin")) { // fileNameWithQuotes = "\"" + fileNameWithQuotes.substring(8); // } // // I assume absolute paths need to be replaced for Cygwin. This will be false on Unix systems. // else if (fileNameWithQuotes.startsWith("\"/")) { // fileNameWithQuotes = "\"/cygdrive/c" + fileNameWithQuotes.substring(1); // } // Output the reconstructed #include directive. sink.print("#include " + fileNameWithQuotes + "\n"); suppressRewriting = true; } else { suppressRewriting = false; } break; case nesCLexer.INTERFACE: // This is correct for 'interface' as it appears in specifications. if (t.getChild(0).getType() == nesCLexer.INTERFACE_TYPE) { indent(); sink.print("interface "); rewrite(t.getChild(0)); if (t.getChildCount() > 1) { sink.print(" as "); rewrite(t.getChild(1)); } sink.print(";\n"); } // Otherwise we are defining an interface type. else { sink.print("interface "); sink.print(t.getChild(0)); sink.print(" {\n"); ++indentationLevel; for (int i = 1; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); } break; case nesCLexer.COMPONENT_DEFINITION: rewrite(t.getChild(0)); // The kind of component. rewrite(t.getChild(1)); // Name of the configuration. // Component parameters, if present. Tree componentParameters = null; if (t.getChildCount() == 5) { componentParameters = t.getChild(4); } else if (t.getChildCount() == 4 && t.getChild(3).getType() == nesCLexer.COMPONENT_PARAMETER_LIST) { componentParameters = t.getChild(3); } if (componentParameters != null) rewrite(componentParameters); rewrite(t.getChild(2)); // Specification. // Implementation, if present. if (t.getChildCount() >= 4 && t.getChild(3).getType() == nesCLexer.IMPLEMENTATION) { rewrite(t.getChild(3)); } break; case nesCLexer.COMPONENT_KIND: switch (t.getChild(0).getType()) { case nesCLexer.CONFIGURATION: sink.print("configuration "); break; case nesCLexer.MODULE: sink.print("module "); break; case nesCLexer.GENERIC: switch (t.getChild(1).getType()) { case nesCLexer.CONFIGURATION: sink.print("generic configuration "); break; case nesCLexer.MODULE: sink.print("generic module "); break; } break; } break; case nesCLexer.COMPONENT_PARAMETER_LIST: sink.print("("); for (int i = 0; i < t.getChildCount(); ++i) { if (i > 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(") "); break; case nesCLexer.SPECIFICATION: sink.print(" {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); break; case nesCLexer.USES: indent(); sink.print("uses {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); break; case nesCLexer.PROVIDES: indent(); sink.print("provides {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } --indentationLevel; indent(); sink.print("}\n"); break; case nesCLexer.INTERFACE_TYPE: // Assume there is no 'remotable' or 'with' parts left in the AST. sink.print(t.getChild(0)); if (t.getChildCount() > 1) { sink.print("<"); for (int i = 1; i < t.getChildCount(); ++i) { if (i != 1) sink.print(", "); rewrite(t.getChild(i)); } sink.print(">"); } break; case nesCLexer.IMPLEMENTATION: sink.print("implementation {\n"); ++indentationLevel; for (int i = 0; i < t.getChildCount(); ++i) { if (!suppressRewriting || t.getChild(i).getType() == nesCLexer.LINE_DIRECTIVE) rewrite(t.getChild(i)); } --indentationLevel; sink.print("}\n"); break; // Configuration Implementation // ---------------------------- case nesCLexer.COMPONENTS: indent(); sink.print("components "); for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } sink.print(";\n"); break; case nesCLexer.COMPONENT_DECLARATION: rewrite(t.getChild(0)); // The component_ref. if (t.getChildCount() == 2) { sink.print(" as "); rewrite(t.getChild(1)); // The component's alias (if there is one). } break; case nesCLexer.COMPONENT_INSTANTIATION: sink.print("new "); rewrite(t.getChild(0)); sink.print("( "); if (t.getChildCount() > 1) { rewrite(t.getChild(1)); } sink.print(" )"); break; case nesCLexer.COMPONENT_ARGUMENTS: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print(", "); rewrite(t.getChild(i)); } break; case nesCLexer.CONNECTION: indent(); rewrite(t.getChild(1)); sink.print(" "); sink.print(t.getChild(0).getText()); sink.print(" "); rewrite(t.getChild(0).getChild(0)); sink.print(";\n"); break; case nesCLexer.IDENTIFIER_PATH: for (int i = 0; i < t.getChildCount(); ++i) { if (i != 0) sink.print("."); rewrite(t.getChild(i)); } break; // The NULL token should probably not appear in the trees given to this method. It is intended to be used as // a placeholder by other programs that manipulate trees (such as Sprocket). The idea is that all NULL // tokens would be removed from the tree before rewriting. However, in case a NULL token does remain, the // code below does the most natural thing with it. // case nesCLexer.NULL: for (int i = 0; i < t.getChildCount(); ++i) { rewrite(t.getChild(i)); } break; // Is it right to have this default case? It is useful during development because it shows the "next" token // that needs to be implemented in order to get a proper rewriting. // default: sink.print(t.getText()); sink.print(" "); break; } }
diff --git a/src/controller/Controller.java b/src/controller/Controller.java index 7fd1778..fc12b98 100755 --- a/src/controller/Controller.java +++ b/src/controller/Controller.java @@ -1,167 +1,167 @@ /* * The thing that controls everything.... */ package controller; import importing.Parser; import importing.XGL_Parser; import input.Input; import javax.vecmath.Vector3f; import physics.Physics; import com.bulletphysics.collision.shapes.BoxShape; import com.bulletphysics.collision.shapes.CollisionShape; import com.bulletphysics.linearmath.DefaultMotionState; import entity.Camera; import entity.Entity; import entity.EntityList; import render.Renderer; public class Controller { // the game always runs (except when it doesn't) private static boolean isRunning = true; private Renderer renderer; private Physics physics; private long frames = 0; private Input input; private EntityList objectList; public static void main(String[] args) throws Exception { new Controller(); } public Controller() throws Exception { start(); loadLevel(); } /* Diagram of dependencies (:D). Arrows mean "depends on" * * /------(Renderer) * | ^ * V | * (Physics) <-- (Entity List) | * ^ | * | | * \------(Input) */ private void start() { //Instantiate Physics first, as it depends on nothing physics = new Physics(); physics_thread.start(); //Next is the entity list, since it only depends on the physics objectList = new EntityList(physics); //Renderer has to be after entity list renderer = new Renderer(objectList); render_thread.start(); //Input has to be after entity list and after the render thread has been started (Display must be created) input = new Input(objectList); input_thread.start(); } /* THREAD DEFINITIONS */ // Create the Input Listening thread Thread input_thread = new Thread() { public void run() { //Wait for display to be created try { render_thread.join(); } catch (InterruptedException e) {/*Nothing to do, render thread is telling us its done creating display*/} input.init(); while(isRunning){ input.run(); } } }; // Create the Physics Listening thread Thread physics_thread = new Thread() { public void run() { while (isRunning) { physics.clientUpdate(); } } }; // Create the vidya thread Thread render_thread = new Thread() { public void run() { renderer.initGL(); input_thread.interrupt(); //If input thread is waiting (it should be) let it go while (isRunning) { renderer.draw(); } } }; public long getFrames() { return frames; } public void resetFrames() { frames = 0; } public static void quit() { isRunning = false; } public void loadLevel() throws Exception{ Entity ent; Camera cam; //Physics.getInstance().getDynamicsWorld().setGravity(new Vector3f(0.0f,-10.0f,0.0f)); Parser p = new XGL_Parser(); try{ //p.readFile("./lib/legoman.xgl"); - //p.readFile("./lib/10010260.xgl"); - p.readFile("./lib/box2.xgl"); + p.readFile("./lib/10010260.xgl"); + //p.readFile("./lib/box2.xgl"); //p.readFile("./lib/cath.xgl"); }catch(Exception e){ //TODO: What to do here? } //Make a camera CollisionShape boxShape = new BoxShape(new Vector3f(1, 1, 1)); cam = new Camera(0.0f, new DefaultMotionState(), boxShape, false); //ent.setLinearVelocity(new Vector3f(10,10,10)); objectList.addItem(cam); //ent.setGravity(new Vector3f(0.0f, 0.0f, 0.0f)); //Make a cathode boxShape = new BoxShape(new Vector3f(1, 1, 1)); ent = new Entity(1.0f, new DefaultMotionState(), boxShape, false); ent.setModel(p.createModel()); ent.setPosition(new Vector3f(0.0f,0.0f,-20.0f)); objectList.addItem(ent); ent.applyImpulse(new Vector3f(0,0,4), new Vector3f(0,0,1)); //Make a green box thing try{ //p.readFile("./lib/legoman.xgl"); //p.readFile("./lib/10010260.xgl"); p.readFile("./lib/box2.xgl"); //p.readFile("./lib/cath.xgl"); }catch(Exception e){ //TODO: What to do here? } boxShape = new BoxShape(new Vector3f(1, 1, 1)); ent = new Entity(1.0f, new DefaultMotionState(), boxShape, false); ent.setModel(p.createModel()); ent.setPosition(new Vector3f(0.0f,0.0f,0.0f)); objectList.addItem(ent); physics.reduceHull(ent); cam.setDistance(25.0f); cam.focusOn(ent); ent.applyImpulse(new Vector3f(0,0,-4), new Vector3f(0,0,-1)); } }
true
true
public void loadLevel() throws Exception{ Entity ent; Camera cam; //Physics.getInstance().getDynamicsWorld().setGravity(new Vector3f(0.0f,-10.0f,0.0f)); Parser p = new XGL_Parser(); try{ //p.readFile("./lib/legoman.xgl"); //p.readFile("./lib/10010260.xgl"); p.readFile("./lib/box2.xgl"); //p.readFile("./lib/cath.xgl"); }catch(Exception e){ //TODO: What to do here? } //Make a camera CollisionShape boxShape = new BoxShape(new Vector3f(1, 1, 1)); cam = new Camera(0.0f, new DefaultMotionState(), boxShape, false); //ent.setLinearVelocity(new Vector3f(10,10,10)); objectList.addItem(cam); //ent.setGravity(new Vector3f(0.0f, 0.0f, 0.0f)); //Make a cathode boxShape = new BoxShape(new Vector3f(1, 1, 1)); ent = new Entity(1.0f, new DefaultMotionState(), boxShape, false); ent.setModel(p.createModel()); ent.setPosition(new Vector3f(0.0f,0.0f,-20.0f)); objectList.addItem(ent); ent.applyImpulse(new Vector3f(0,0,4), new Vector3f(0,0,1)); //Make a green box thing try{ //p.readFile("./lib/legoman.xgl"); //p.readFile("./lib/10010260.xgl"); p.readFile("./lib/box2.xgl"); //p.readFile("./lib/cath.xgl"); }catch(Exception e){ //TODO: What to do here? } boxShape = new BoxShape(new Vector3f(1, 1, 1)); ent = new Entity(1.0f, new DefaultMotionState(), boxShape, false); ent.setModel(p.createModel()); ent.setPosition(new Vector3f(0.0f,0.0f,0.0f)); objectList.addItem(ent); physics.reduceHull(ent); cam.setDistance(25.0f); cam.focusOn(ent); ent.applyImpulse(new Vector3f(0,0,-4), new Vector3f(0,0,-1)); }
public void loadLevel() throws Exception{ Entity ent; Camera cam; //Physics.getInstance().getDynamicsWorld().setGravity(new Vector3f(0.0f,-10.0f,0.0f)); Parser p = new XGL_Parser(); try{ //p.readFile("./lib/legoman.xgl"); p.readFile("./lib/10010260.xgl"); //p.readFile("./lib/box2.xgl"); //p.readFile("./lib/cath.xgl"); }catch(Exception e){ //TODO: What to do here? } //Make a camera CollisionShape boxShape = new BoxShape(new Vector3f(1, 1, 1)); cam = new Camera(0.0f, new DefaultMotionState(), boxShape, false); //ent.setLinearVelocity(new Vector3f(10,10,10)); objectList.addItem(cam); //ent.setGravity(new Vector3f(0.0f, 0.0f, 0.0f)); //Make a cathode boxShape = new BoxShape(new Vector3f(1, 1, 1)); ent = new Entity(1.0f, new DefaultMotionState(), boxShape, false); ent.setModel(p.createModel()); ent.setPosition(new Vector3f(0.0f,0.0f,-20.0f)); objectList.addItem(ent); ent.applyImpulse(new Vector3f(0,0,4), new Vector3f(0,0,1)); //Make a green box thing try{ //p.readFile("./lib/legoman.xgl"); //p.readFile("./lib/10010260.xgl"); p.readFile("./lib/box2.xgl"); //p.readFile("./lib/cath.xgl"); }catch(Exception e){ //TODO: What to do here? } boxShape = new BoxShape(new Vector3f(1, 1, 1)); ent = new Entity(1.0f, new DefaultMotionState(), boxShape, false); ent.setModel(p.createModel()); ent.setPosition(new Vector3f(0.0f,0.0f,0.0f)); objectList.addItem(ent); physics.reduceHull(ent); cam.setDistance(25.0f); cam.focusOn(ent); ent.applyImpulse(new Vector3f(0,0,-4), new Vector3f(0,0,-1)); }
diff --git a/java/AP2DX/src/AP2DX/coordinator/UsarMessageParser.java b/java/AP2DX/src/AP2DX/coordinator/UsarMessageParser.java index a5167b1..4381381 100644 --- a/java/AP2DX/src/AP2DX/coordinator/UsarMessageParser.java +++ b/java/AP2DX/src/AP2DX/coordinator/UsarMessageParser.java @@ -1,139 +1,139 @@ package AP2DX.coordinator; import java.net.*; import java.util.ArrayList; import java.io.*; import java.util.Map; import AP2DX.*; import AP2DX.specializedMessages.*; import AP2DX.usarsim.*; import AP2DX.usarsim.specialized.*; /** * This is the class that will take care of receiving messages from UsarSim, and forwarding them to * the Sensor module. * @author Maarten de Waard */ public class UsarMessageParser extends Thread { /** An UsarSimMessageReader to read the messages USARSim sends us. */ private UsarSimMessageReader in; /** The module this parser relates to (For message sending purposes) */ private Module IAM; /** The module this parser sends to */ private Module send; /** The connectionHandler that handles the send connection */ private ConnectionHandler sendConnection; /** The base class (supposed to be the AP2DXBase of coordinator */ private AP2DXBase base; /** * This constructor configures the connection with usarsim, * with the data that is specified in the config file. * @param base The base (should be coordinator) * @param IAM The module from which this parser will send messages * @param send The module this parser will send to */ public UsarMessageParser(AP2DXBase base, Module IAM, Module send, Socket socket) { this.base = base; this.IAM = IAM; this.send = send; try { this.sendConnection = base.getSendConnection(send); in = new UsarSimMessageReader(socket.getInputStream()); } catch (Exception ex) { ex.printStackTrace(); } } public void run() { while (true) { Message messageIn = null; try { System.out.println("Reading message"); messageIn = in.readMessage(); System.out.println(messageIn.toString()); } catch (Exception e) { e.printStackTrace(); base.logger .severe("Error in UsarMessageParser.run, attempted to retrieve item out of messageReader"); } //Initialize the message we will return. This shouldn't stay null. AP2DXMessage message = null; switch (messageIn.getMsgType()) { case USAR_SENSOR: System.out.println("USAR SENSOR message detected!"); UsarSimSensorMessage sensorMessage = null; try { sensorMessage = new UsarSimSensorMessage((UsarSimMessage) messageIn); } catch (Exception e) { e.printStackTrace(); } switch (sensorMessage.getSensorType()) { case USAR_SONAR: try { USonarSensorMessage sonarMessage= new USonarSensorMessage(sensorMessage); // Put the right values in the message message = (SonarSensorMessage) sonarMessage.toAp2dxMessage(); } catch (Exception e) { System.err.println("Some exception occured while making a SonarMessage"); System.err.println(e.getMessage()); } break; - /*case USAR_RANGE: + case USAR_RANGE: try { URangeSensorMessage rangeMessage = new URangeSensorMessage(sensorMessage); message = (RangeScannerSensorMessage) rangeMessage.toAp2dxMessage(); } catch (Exception e) { System.err.println("Some exception occured while making a SonarMessage"); System.err.println(e.getMessage()); } - break;*/ + break; default: System.out.println("Somethings wrong!?"); }; break; default: System.out.println("Unexpected message type in ap2dx.coordonator.UsarMessageParser: " + messageIn.getMsgType()); }; //Try to send the message to the right connection. if(message != null && message.getMsgType() != Message.MessageType.UNKNOWN) { try { System.out.println("Sending message"); sendConnection.sendMessage(message); } catch (Exception e) { e.printStackTrace(); base.logger .severe("Error in UsarMessageParser.run, attempted get the connection of message: " + message); } } System.out.printf("End of while loop, message %s may be sent.\n", message); } } }
false
true
public void run() { while (true) { Message messageIn = null; try { System.out.println("Reading message"); messageIn = in.readMessage(); System.out.println(messageIn.toString()); } catch (Exception e) { e.printStackTrace(); base.logger .severe("Error in UsarMessageParser.run, attempted to retrieve item out of messageReader"); } //Initialize the message we will return. This shouldn't stay null. AP2DXMessage message = null; switch (messageIn.getMsgType()) { case USAR_SENSOR: System.out.println("USAR SENSOR message detected!"); UsarSimSensorMessage sensorMessage = null; try { sensorMessage = new UsarSimSensorMessage((UsarSimMessage) messageIn); } catch (Exception e) { e.printStackTrace(); } switch (sensorMessage.getSensorType()) { case USAR_SONAR: try { USonarSensorMessage sonarMessage= new USonarSensorMessage(sensorMessage); // Put the right values in the message message = (SonarSensorMessage) sonarMessage.toAp2dxMessage(); } catch (Exception e) { System.err.println("Some exception occured while making a SonarMessage"); System.err.println(e.getMessage()); } break; /*case USAR_RANGE: try { URangeSensorMessage rangeMessage = new URangeSensorMessage(sensorMessage); message = (RangeScannerSensorMessage) rangeMessage.toAp2dxMessage(); } catch (Exception e) { System.err.println("Some exception occured while making a SonarMessage"); System.err.println(e.getMessage()); } break;*/ default: System.out.println("Somethings wrong!?"); }; break; default: System.out.println("Unexpected message type in ap2dx.coordonator.UsarMessageParser: " + messageIn.getMsgType()); }; //Try to send the message to the right connection. if(message != null && message.getMsgType() != Message.MessageType.UNKNOWN) { try { System.out.println("Sending message"); sendConnection.sendMessage(message); } catch (Exception e) { e.printStackTrace(); base.logger .severe("Error in UsarMessageParser.run, attempted get the connection of message: " + message); } } System.out.printf("End of while loop, message %s may be sent.\n", message); } }
public void run() { while (true) { Message messageIn = null; try { System.out.println("Reading message"); messageIn = in.readMessage(); System.out.println(messageIn.toString()); } catch (Exception e) { e.printStackTrace(); base.logger .severe("Error in UsarMessageParser.run, attempted to retrieve item out of messageReader"); } //Initialize the message we will return. This shouldn't stay null. AP2DXMessage message = null; switch (messageIn.getMsgType()) { case USAR_SENSOR: System.out.println("USAR SENSOR message detected!"); UsarSimSensorMessage sensorMessage = null; try { sensorMessage = new UsarSimSensorMessage((UsarSimMessage) messageIn); } catch (Exception e) { e.printStackTrace(); } switch (sensorMessage.getSensorType()) { case USAR_SONAR: try { USonarSensorMessage sonarMessage= new USonarSensorMessage(sensorMessage); // Put the right values in the message message = (SonarSensorMessage) sonarMessage.toAp2dxMessage(); } catch (Exception e) { System.err.println("Some exception occured while making a SonarMessage"); System.err.println(e.getMessage()); } break; case USAR_RANGE: try { URangeSensorMessage rangeMessage = new URangeSensorMessage(sensorMessage); message = (RangeScannerSensorMessage) rangeMessage.toAp2dxMessage(); } catch (Exception e) { System.err.println("Some exception occured while making a SonarMessage"); System.err.println(e.getMessage()); } break; default: System.out.println("Somethings wrong!?"); }; break; default: System.out.println("Unexpected message type in ap2dx.coordonator.UsarMessageParser: " + messageIn.getMsgType()); }; //Try to send the message to the right connection. if(message != null && message.getMsgType() != Message.MessageType.UNKNOWN) { try { System.out.println("Sending message"); sendConnection.sendMessage(message); } catch (Exception e) { e.printStackTrace(); base.logger .severe("Error in UsarMessageParser.run, attempted get the connection of message: " + message); } } System.out.printf("End of while loop, message %s may be sent.\n", message); } }
diff --git a/src/minecraft/net/minecraft/src/GuiIngame.java b/src/minecraft/net/minecraft/src/GuiIngame.java index 0af2e44b..136813f8 100644 --- a/src/minecraft/net/minecraft/src/GuiIngame.java +++ b/src/minecraft/net/minecraft/src/GuiIngame.java @@ -1,640 +1,640 @@ package net.minecraft.src; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; //Spout Start import org.spoutcraft.client.SpoutClient; import org.spoutcraft.client.config.ConfigReader; import org.spoutcraft.client.gui.minimap.ZanMinimap; import org.spoutcraft.spoutcraftapi.Spoutcraft; import org.spoutcraft.spoutcraftapi.gui.ChatTextBox; import org.spoutcraft.spoutcraftapi.gui.Color; import org.spoutcraft.spoutcraftapi.gui.InGameHUD; import org.spoutcraft.spoutcraftapi.gui.ServerPlayerList; //Spout End import org.spoutcraft.spoutcraftapi.player.ChatMessage; public class GuiIngame extends Gui { private static RenderItem itemRenderer = new RenderItem(); //Spout Start private final ZanMinimap map = new ZanMinimap(); //Spout End public static final Random rand = new Random(); //Spout private -> public static final private Minecraft mc; private int updateCounter; /** The string specifying which record music is playing */ private String recordPlaying; /** How many ticks the record playing message will be displayed */ private int recordPlayingUpFor; private boolean recordIsPlaying; /** Damage partial time (GUI) */ public float damageGuiPartialTime; /** Previous frame vignette brightness (slowly changes by 1% each frame) */ float prevVignetteBrightness; public GuiIngame(Minecraft par1Minecraft) { //rand = new Random(); //Spout removed updateCounter = 0; recordPlaying = ""; recordPlayingUpFor = 0; recordIsPlaying = false; prevVignetteBrightness = 1.0F; mc = par1Minecraft; } /** * Render the ingame overlay with quick icon bar, ... */ //Spout Start //TODO Rewrite again, it's in a horrible state, i'm surprised it works... //Most of function rewritten public void renderGameOverlay(float f, boolean flag, int i, int j) { SpoutClient.getInstance().onTick(); InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen(); ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int screenWidth = scaledRes.getScaledWidth(); int screenHeight = scaledRes.getScaledHeight(); FontRenderer font = this.mc.fontRenderer; this.mc.entityRenderer.setupOverlayRendering(); GL11.glEnable(3042 /*GL_BLEND*/); if(Minecraft.isFancyGraphicsEnabled()) { this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight); } ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3); if(this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) { this.renderPumpkinBlur(screenWidth, screenHeight); } if(!this.mc.thePlayer.isPotionActive(Potion.confusion)) { float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f; if(var10 > 0.0F) { this.renderPortalOverlay(var10, screenWidth, screenHeight); } } GL11.glBlendFunc(770, 771); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png")); InventoryPlayer var11 = this.mc.thePlayer.inventory; this.zLevel = -90.0F; this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22); this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22); GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png")); GL11.glEnable(3042 /* GL_BLEND */); GL11.glBlendFunc(775, 769); this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16); GL11.glDisable(3042 /* GL_BLEND */); GuiIngame.rand.setSeed((long) (this.updateCounter * 312871)); int var15; int var17; this.renderBossHealth(); //better safe than sorry SpoutClient.enableSandbox(); //Toggle visibility if needed if(mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) { mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode()); } // Hunger Bar Begin mainScreen.getHungerBar().render(); // Hunger Bar End // Armor Bar Begin mainScreen.getArmorBar().render(); // Armor Bar End // Health Bar Begin mainScreen.getHealthBar().render(); // Health Bar End // Bubble Bar Begin mainScreen.getBubbleBar().render(); // Bubble Bar End // Exp Bar Begin mainScreen.getExpBar().render(); // Exp Bar End SpoutClient.disableSandbox(); map.onRenderTick(); GL11.glDisable(3042 /* GL_BLEND */); GL11.glEnable('\u803a'); GL11.glPushMatrix(); GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F); - RenderHelper.enableStandardItemLighting(); GL11.glPopMatrix(); + RenderHelper.enableGUIStandardItemLighting(); for (var15 = 0; var15 < 9; ++var15) { int x = screenWidth / 2 - 90 + var15 * 20 + 2; var17 = screenHeight - 16 - 3; this.renderInventorySlot(var15, x, var17, f); } RenderHelper.disableStandardItemLighting(); GL11.glDisable('\u803a'); if (this.mc.thePlayer.getSleepTimer() > 0) { GL11.glDisable(2929 /*GL_DEPTH_TEST*/); GL11.glDisable(3008 /*GL_ALPHA_TEST*/); var15 = this.mc.thePlayer.getSleepTimer(); float var26 = (float)var15 / 100.0F; if(var26 > 1.0F) { var26 = 1.0F - (float)(var15 - 100) / 10.0F; } var17 = (int)(220.0F * var26) << 24 | 1052704; this.drawRect(0, 0, screenWidth, screenHeight, var17); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); GL11.glEnable(2929 /*GL_DEPTH_TEST*/); } SpoutClient.enableSandbox(); mainScreen.render(); SpoutClient.disableSandbox(); if (this.mc.gameSettings.showDebugInfo) { this.mc.mcProfiler.startSection("debug"); GL11.glPushMatrix(); font.drawStringWithShadow("Minecraft 1.3.2 (" + this.mc.debug + ")", 2, 2, 16777215); font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215); font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215); font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215); font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215); long var41 = Runtime.getRuntime().maxMemory(); long var34 = Runtime.getRuntime().totalMemory(); long var42 = Runtime.getRuntime().freeMemory(); long var43 = var34 - var42; String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB"; this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632); var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)"; this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632); if(SpoutClient.getInstance().isCoordsCheat()) { this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632); this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632); this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632); this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632); } int var47 = MathHelper.floor_double(this.mc.thePlayer.posX); int var22 = MathHelper.floor_double(this.mc.thePlayer.posY); int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ); if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) { Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233); this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632); } this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632); GL11.glPopMatrix(); this.mc.mcProfiler.endSection(); } if(this.recordPlayingUpFor > 0) { float var24 = (float)this.recordPlayingUpFor - f; int fontColor = (int)(var24 * 256.0F / 20.0F); if(fontColor > 255) { fontColor = 255; } if(fontColor > 0) { GL11.glPushMatrix(); GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F); GL11.glEnable(3042 /*GL_BLEND*/); GL11.glBlendFunc(770, 771); var17 = 16777215; if(this.recordIsPlaying) { var17 = java.awt.Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215; } font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24)); GL11.glDisable(3042 /*GL_BLEND*/); GL11.glPopMatrix(); } } SpoutClient.enableSandbox(); //boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat; //int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines(); // GL11.glEnable(3042 /*GL_BLEND*/); // GL11.glBlendFunc(770, 771); // GL11.glDisable(3008 /*GL_ALPHA_TEST*/); ChatTextBox chatTextWidget = mainScreen.getChatTextBox(); GL11.glPushMatrix(); boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat; if (chatTextWidget.isVisible() || chatOpen) { chatTextWidget.setChatOpen(chatOpen); chatTextWidget.render(); } GL11.glPopMatrix(); // if (chatTextWidget.isVisible()) { // int viewedLine = 0; // for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size(), (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) { // if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) { // double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks(); // opacity *= 10D; // if(opacity < 0.0D) { // opacity = 0.0D; // } // if(opacity > 1.0D) { // opacity = 1.0D; // } // opacity *= opacity; // int color = chatOpen ? 255 : (int)(255D * opacity); // if (color > 0) { // int x = 2 + chatTextWidget.getX(); // int y = chatTextWidget.getY() + (-viewedLine * 9); // String chat = chatMessageList.get(line).message; // chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat); // // boolean mentioned = false; // if (ConfigReader.highlightMentions) { // String[] split = chat.toLowerCase().split(":"); // if (split.length == 1) { // split = chat.toLowerCase().split(">"); // } // if (split.length > 1) { // String name = this.mc.thePlayer.username.toLowerCase(); // if (!split[0].contains(name)) { // for (int part = 1; part < split.length; part++) { // if (split[part].contains(name)) { // mentioned = true; // break; // } // } // } // } // } // // if (mentioned) { // drawRect(x, y - 1, x + 320, y + 8, RED); // } // else { // drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24); // } // GL11.glEnable(3042 /*GL_BLEND*/); // font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24)); // } // viewedLine++; // } // } // } SpoutClient.disableSandbox(); ServerPlayerList playerList = mainScreen.getServerPlayerList(); if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.keyBindPlayerList.pressed && playerList.isVisible()) { NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue; List var44 = var41.playerInfoList; int var40 = var41.currentServerMaxPlayers; int var38 = var40; int var16; for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) { ++var16; } var17 = 300 / var16; if(var17 > 150) { var17 = 150; } int var18 = (screenWidth - var16 * var17) / 2; byte var46 = 10; this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE); for(int var20 = 0; var20 < var40; ++var20) { int var47 = var18 + var20 % var16 * var17; int var22 = var46 + var20 / var16 * 9; this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); if(var20 < var44.size()) { GuiPlayerInfo var50 = (GuiPlayerInfo)var44.get(var20); font.drawStringWithShadow(var50.name, var47, var22, 16777215); this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png")); boolean var48 = false; boolean var53 = false; byte var49 = 0; var53 = false; byte var54; if(var50.responseTime < 0) { var54 = 5; } else if(var50.responseTime < 150) { var54 = 0; } else if(var50.responseTime < 300) { var54 = 1; } else if(var50.responseTime < 600) { var54 = 2; } else if(var50.responseTime < 1000) { var54 = 3; } else { var54 = 4; } this.zLevel += 100.0F; this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8); this.zLevel -= 100.0F; } } } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(2896 /*GL_LIGHTING*/); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); GL11.glDisable(3042 /*GL_BLEND*/); } /** * Renders dragon's (boss) health on the HUD */ private void renderBossHealth() { if (RenderDragon.entityDragon == null) { return; } EntityDragon entitydragon = RenderDragon.entityDragon; RenderDragon.entityDragon = null; FontRenderer fontrenderer = mc.fontRenderer; ScaledResolution scaledresolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight); int i = scaledresolution.getScaledWidth(); char c = '\266'; int j = i / 2 - c / 2; int k = (int)(((float)entitydragon.getDragonHealth() / (float)entitydragon.getMaxHealth()) * (float)(c + 1)); byte byte0 = 12; drawTexturedModalRect(j, byte0, 0, 74, c, 5); drawTexturedModalRect(j, byte0, 0, 74, c, 5); if (k > 0) { drawTexturedModalRect(j, byte0, 0, 79, k, 5); } String s = "Boss health"; fontrenderer.drawStringWithShadow(s, i / 2 - fontrenderer.getStringWidth(s) / 2, byte0 - 10, 0xff00ff); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("/gui/icons.png")); } private void renderPumpkinBlur(int par1, int par2) { GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("%blur%/misc/pumpkinblur.png")); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(0.0D, par2, -90D, 0.0D, 1.0D); tessellator.addVertexWithUV(par1, par2, -90D, 1.0D, 1.0D); tessellator.addVertexWithUV(par1, 0.0D, -90D, 1.0D, 0.0D); tessellator.addVertexWithUV(0.0D, 0.0D, -90D, 0.0D, 0.0D); tessellator.draw(); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } /** * Renders the vignette. Args: vignetteBrightness, width, height */ private void renderVignette(float par1, int par2, int par3) { par1 = 1.0F - par1; if (par1 < 0.0F) { par1 = 0.0F; } if (par1 > 1.0F) { par1 = 1.0F; } prevVignetteBrightness += (double)(par1 - prevVignetteBrightness) * 0.01D; GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); GL11.glBlendFunc(GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_COLOR); GL11.glColor4f(prevVignetteBrightness, prevVignetteBrightness, prevVignetteBrightness, 1.0F); GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("%blur%/misc/vignette.png")); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(0.0D, par3, -90D, 0.0D, 1.0D); tessellator.addVertexWithUV(par2, par3, -90D, 1.0D, 1.0D); tessellator.addVertexWithUV(par2, 0.0D, -90D, 1.0D, 0.0D); tessellator.addVertexWithUV(0.0D, 0.0D, -90D, 0.0D, 0.0D); tessellator.draw(); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } /** * Renders the portal overlay. Args: portalStrength, width, height */ private void renderPortalOverlay(float par1, int par2, int par3) { if (par1 < 1.0F) { par1 *= par1; par1 *= par1; par1 = par1 * 0.8F + 0.2F; } GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(1.0F, 1.0F, 1.0F, par1); GL11.glBindTexture(GL11.GL_TEXTURE_2D, mc.renderEngine.getTexture("/terrain.png")); float f = (float)(Block.portal.blockIndexInTexture % 16) / 16F; float f1 = (float)(Block.portal.blockIndexInTexture / 16) / 16F; float f2 = (float)(Block.portal.blockIndexInTexture % 16 + 1) / 16F; float f3 = (float)(Block.portal.blockIndexInTexture / 16 + 1) / 16F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(0.0D, par3, -90D, f, f3); tessellator.addVertexWithUV(par2, par3, -90D, f2, f3); tessellator.addVertexWithUV(par2, 0.0D, -90D, f2, f1); tessellator.addVertexWithUV(0.0D, 0.0D, -90D, f, f1); tessellator.draw(); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_ALPHA_TEST); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } /** * Renders the specified item of the inventory slot at the specified location. Args: slot, x, y, partialTick */ private void renderInventorySlot(int par1, int par2, int par3, float par4) { ItemStack itemstack = mc.thePlayer.inventory.mainInventory[par1]; if (itemstack == null) { return; } float f = (float)itemstack.animationsToGo - par4; if (f > 0.0F) { GL11.glPushMatrix(); float f1 = 1.0F + f / 5F; GL11.glTranslatef(par2 + 8, par3 + 12, 0.0F); GL11.glScalef(1.0F / f1, (f1 + 1.0F) / 2.0F, 1.0F); GL11.glTranslatef(-(par2 + 8), -(par3 + 12), 0.0F); } itemRenderer.renderItemIntoGUI(mc.fontRenderer, mc.renderEngine, itemstack, par2, par3); if (f > 0.0F) { GL11.glPopMatrix(); } itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, itemstack, par2, par3); } /** * The update tick for the ingame UI */ public void updateTick() { if(Spoutcraft.getActivePlayer() != null) { Spoutcraft.getActivePlayer().getMainScreen().getChatTextBox().increaseAge(); } if (recordPlayingUpFor > 0) { recordPlayingUpFor--; } updateCounter++; } /** * Clear all chat messages. */ public void clearChatMessages() { ChatTextBox.clearChat(); } /** * Adds a chat message to the list of chat messages. Args: msg */ public void addChatMessage(String message) { /* Spout start */ if (!ConfigReader.showJoinMessages && message.toLowerCase().contains("joined the game")) { return; } String mess[] = (mc.fontRenderer.func_50113_d(message, 320)).split("\n"); for(int i=0;i<mess.length;i++) { SpoutClient.enableSandbox(); if (Spoutcraft.getActivePlayer() != null) { ChatTextBox.addChatMessage(ChatMessage.parseMessage(mess[i])); } else { ChatTextBox.addChatMessage(new ChatMessage(mess[i], mess[i])); } SpoutClient.disableSandbox(); } /* Spout end */ } // public void addChatMessage(String message) { // /* Spout start */ // if (!ConfigReader.showJoinMessages && message.toLowerCase().contains("joined the game")) { // return; // } // SpoutClient.enableSandbox(); // if (Spoutcraft.getActivePlayer() != null) { // ChatTextBox.addChatMessage(ChatMessage.parseMessage(message)); // } // else { // ChatTextBox.addChatMessage(new ChatMessage(message, message)); // } // SpoutClient.disableSandbox(); // /* Spout end */ // int i; // for (; mc.fontRenderer.getStringWidth(message) > 320; message = message.substring(i)) { // for (i = 1; i < message.length() && mc.fontRenderer.getStringWidth(message.substring(0, i + 1)) <= 320; i++) { } // addChatMessage(message.substring(0, i)); // } // } public void setRecordPlayingMessage(String par1Str) { recordPlaying = (new StringBuilder()).append("Now playing: ").append(par1Str).toString(); recordPlayingUpFor = 60; recordIsPlaying = true; } /** * Adds the string to chat message after translate it with the language file. */ public void addChatMessageTranslate(String par1Str, Object ... par2ArrayOfObj) { StringTranslate stringtranslate = StringTranslate.getInstance(); String s = stringtranslate.translateKeyFormat(par1Str, par2ArrayOfObj); addChatMessage(s); } public boolean isChatOpen() { return this.mc.currentScreen instanceof GuiChat; } public ChatClickData func_50012_a(int par1, int par2) { if (!this.isChatOpen()) { return null; } else { ScaledResolution var3 = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int chatScroll = SpoutClient.getInstance().getChatManager().chatScroll; //don't ask, it's much better than vanilla matching though par2 = par2 / var3.getScaleFactor() - 33 - ((20 - Math.min(20, chatScroll)) / 2); par1 = par1 / var3.getScaleFactor() - 3; if (par1 >= 0 && par2 >= 0) { int var4 = Math.min(20, ChatTextBox.getNumChatMessages()); if (par1 <= 320 && par2 < this.mc.fontRenderer.FONT_HEIGHT * var4 + var4) { int var5 = par2 / (this.mc.fontRenderer.FONT_HEIGHT + 1) + chatScroll; return new ChatClickData(this.mc.fontRenderer, new ChatLine(this.mc.ingameGUI.getUpdateCounter(), ChatTextBox.getChatMessageAt(var5), par2), par1, par2 - (var5 - chatScroll) * this.mc.fontRenderer.FONT_HEIGHT + var5); } else { return null; } } else { return null; } } } public int getUpdateCounter() { return this.updateCounter++; } }
false
true
public void renderGameOverlay(float f, boolean flag, int i, int j) { SpoutClient.getInstance().onTick(); InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen(); ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int screenWidth = scaledRes.getScaledWidth(); int screenHeight = scaledRes.getScaledHeight(); FontRenderer font = this.mc.fontRenderer; this.mc.entityRenderer.setupOverlayRendering(); GL11.glEnable(3042 /*GL_BLEND*/); if(Minecraft.isFancyGraphicsEnabled()) { this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight); } ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3); if(this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) { this.renderPumpkinBlur(screenWidth, screenHeight); } if(!this.mc.thePlayer.isPotionActive(Potion.confusion)) { float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f; if(var10 > 0.0F) { this.renderPortalOverlay(var10, screenWidth, screenHeight); } } GL11.glBlendFunc(770, 771); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png")); InventoryPlayer var11 = this.mc.thePlayer.inventory; this.zLevel = -90.0F; this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22); this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22); GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png")); GL11.glEnable(3042 /* GL_BLEND */); GL11.glBlendFunc(775, 769); this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16); GL11.glDisable(3042 /* GL_BLEND */); GuiIngame.rand.setSeed((long) (this.updateCounter * 312871)); int var15; int var17; this.renderBossHealth(); //better safe than sorry SpoutClient.enableSandbox(); //Toggle visibility if needed if(mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) { mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode()); } // Hunger Bar Begin mainScreen.getHungerBar().render(); // Hunger Bar End // Armor Bar Begin mainScreen.getArmorBar().render(); // Armor Bar End // Health Bar Begin mainScreen.getHealthBar().render(); // Health Bar End // Bubble Bar Begin mainScreen.getBubbleBar().render(); // Bubble Bar End // Exp Bar Begin mainScreen.getExpBar().render(); // Exp Bar End SpoutClient.disableSandbox(); map.onRenderTick(); GL11.glDisable(3042 /* GL_BLEND */); GL11.glEnable('\u803a'); GL11.glPushMatrix(); GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F); RenderHelper.enableStandardItemLighting(); GL11.glPopMatrix(); for (var15 = 0; var15 < 9; ++var15) { int x = screenWidth / 2 - 90 + var15 * 20 + 2; var17 = screenHeight - 16 - 3; this.renderInventorySlot(var15, x, var17, f); } RenderHelper.disableStandardItemLighting(); GL11.glDisable('\u803a'); if (this.mc.thePlayer.getSleepTimer() > 0) { GL11.glDisable(2929 /*GL_DEPTH_TEST*/); GL11.glDisable(3008 /*GL_ALPHA_TEST*/); var15 = this.mc.thePlayer.getSleepTimer(); float var26 = (float)var15 / 100.0F; if(var26 > 1.0F) { var26 = 1.0F - (float)(var15 - 100) / 10.0F; } var17 = (int)(220.0F * var26) << 24 | 1052704; this.drawRect(0, 0, screenWidth, screenHeight, var17); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); GL11.glEnable(2929 /*GL_DEPTH_TEST*/); } SpoutClient.enableSandbox(); mainScreen.render(); SpoutClient.disableSandbox(); if (this.mc.gameSettings.showDebugInfo) { this.mc.mcProfiler.startSection("debug"); GL11.glPushMatrix(); font.drawStringWithShadow("Minecraft 1.3.2 (" + this.mc.debug + ")", 2, 2, 16777215); font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215); font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215); font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215); font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215); long var41 = Runtime.getRuntime().maxMemory(); long var34 = Runtime.getRuntime().totalMemory(); long var42 = Runtime.getRuntime().freeMemory(); long var43 = var34 - var42; String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB"; this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632); var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)"; this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632); if(SpoutClient.getInstance().isCoordsCheat()) { this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632); this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632); this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632); this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632); } int var47 = MathHelper.floor_double(this.mc.thePlayer.posX); int var22 = MathHelper.floor_double(this.mc.thePlayer.posY); int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ); if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) { Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233); this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632); } this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632); GL11.glPopMatrix(); this.mc.mcProfiler.endSection(); } if(this.recordPlayingUpFor > 0) { float var24 = (float)this.recordPlayingUpFor - f; int fontColor = (int)(var24 * 256.0F / 20.0F); if(fontColor > 255) { fontColor = 255; } if(fontColor > 0) { GL11.glPushMatrix(); GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F); GL11.glEnable(3042 /*GL_BLEND*/); GL11.glBlendFunc(770, 771); var17 = 16777215; if(this.recordIsPlaying) { var17 = java.awt.Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215; } font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24)); GL11.glDisable(3042 /*GL_BLEND*/); GL11.glPopMatrix(); } } SpoutClient.enableSandbox(); //boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat; //int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines(); // GL11.glEnable(3042 /*GL_BLEND*/); // GL11.glBlendFunc(770, 771); // GL11.glDisable(3008 /*GL_ALPHA_TEST*/); ChatTextBox chatTextWidget = mainScreen.getChatTextBox(); GL11.glPushMatrix(); boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat; if (chatTextWidget.isVisible() || chatOpen) { chatTextWidget.setChatOpen(chatOpen); chatTextWidget.render(); } GL11.glPopMatrix(); // if (chatTextWidget.isVisible()) { // int viewedLine = 0; // for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size(), (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) { // if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) { // double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks(); // opacity *= 10D; // if(opacity < 0.0D) { // opacity = 0.0D; // } // if(opacity > 1.0D) { // opacity = 1.0D; // } // opacity *= opacity; // int color = chatOpen ? 255 : (int)(255D * opacity); // if (color > 0) { // int x = 2 + chatTextWidget.getX(); // int y = chatTextWidget.getY() + (-viewedLine * 9); // String chat = chatMessageList.get(line).message; // chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat); // // boolean mentioned = false; // if (ConfigReader.highlightMentions) { // String[] split = chat.toLowerCase().split(":"); // if (split.length == 1) { // split = chat.toLowerCase().split(">"); // } // if (split.length > 1) { // String name = this.mc.thePlayer.username.toLowerCase(); // if (!split[0].contains(name)) { // for (int part = 1; part < split.length; part++) { // if (split[part].contains(name)) { // mentioned = true; // break; // } // } // } // } // } // // if (mentioned) { // drawRect(x, y - 1, x + 320, y + 8, RED); // } // else { // drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24); // } // GL11.glEnable(3042 /*GL_BLEND*/); // font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24)); // } // viewedLine++; // } // } // } SpoutClient.disableSandbox(); ServerPlayerList playerList = mainScreen.getServerPlayerList(); if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.keyBindPlayerList.pressed && playerList.isVisible()) { NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue; List var44 = var41.playerInfoList; int var40 = var41.currentServerMaxPlayers; int var38 = var40; int var16; for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) { ++var16; } var17 = 300 / var16; if(var17 > 150) { var17 = 150; } int var18 = (screenWidth - var16 * var17) / 2; byte var46 = 10; this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE); for(int var20 = 0; var20 < var40; ++var20) { int var47 = var18 + var20 % var16 * var17; int var22 = var46 + var20 / var16 * 9; this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); if(var20 < var44.size()) { GuiPlayerInfo var50 = (GuiPlayerInfo)var44.get(var20); font.drawStringWithShadow(var50.name, var47, var22, 16777215); this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png")); boolean var48 = false; boolean var53 = false; byte var49 = 0; var53 = false; byte var54; if(var50.responseTime < 0) { var54 = 5; } else if(var50.responseTime < 150) { var54 = 0; } else if(var50.responseTime < 300) { var54 = 1; } else if(var50.responseTime < 600) { var54 = 2; } else if(var50.responseTime < 1000) { var54 = 3; } else { var54 = 4; } this.zLevel += 100.0F; this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8); this.zLevel -= 100.0F; } } } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(2896 /*GL_LIGHTING*/); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); GL11.glDisable(3042 /*GL_BLEND*/); }
public void renderGameOverlay(float f, boolean flag, int i, int j) { SpoutClient.getInstance().onTick(); InGameHUD mainScreen = SpoutClient.getInstance().getActivePlayer().getMainScreen(); ScaledResolution scaledRes = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); int screenWidth = scaledRes.getScaledWidth(); int screenHeight = scaledRes.getScaledHeight(); FontRenderer font = this.mc.fontRenderer; this.mc.entityRenderer.setupOverlayRendering(); GL11.glEnable(3042 /*GL_BLEND*/); if(Minecraft.isFancyGraphicsEnabled()) { this.renderVignette(this.mc.thePlayer.getBrightness(f), screenWidth, screenHeight); } ItemStack helmet = this.mc.thePlayer.inventory.armorItemInSlot(3); if(this.mc.gameSettings.thirdPersonView == 0 && helmet != null && helmet.itemID == Block.pumpkin.blockID) { this.renderPumpkinBlur(screenWidth, screenHeight); } if(!this.mc.thePlayer.isPotionActive(Potion.confusion)) { float var10 = this.mc.thePlayer.prevTimeInPortal + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * f; if(var10 > 0.0F) { this.renderPortalOverlay(var10, screenWidth, screenHeight); } } GL11.glBlendFunc(770, 771); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/gui.png")); InventoryPlayer var11 = this.mc.thePlayer.inventory; this.zLevel = -90.0F; this.drawTexturedModalRect(screenWidth / 2 - 91, screenHeight - 22, 0, 0, 182, 22); this.drawTexturedModalRect(screenWidth / 2 - 91 - 1 + var11.currentItem * 20, screenHeight - 22 - 1, 0, 22, 24, 22); GL11.glBindTexture(3553 /* GL_TEXTURE_2D */, this.mc.renderEngine.getTexture("/gui/icons.png")); GL11.glEnable(3042 /* GL_BLEND */); GL11.glBlendFunc(775, 769); this.drawTexturedModalRect(screenWidth / 2 - 7, screenHeight / 2 - 7, 0, 0, 16, 16); GL11.glDisable(3042 /* GL_BLEND */); GuiIngame.rand.setSeed((long) (this.updateCounter * 312871)); int var15; int var17; this.renderBossHealth(); //better safe than sorry SpoutClient.enableSandbox(); //Toggle visibility if needed if(mainScreen.getHealthBar().isVisible() == mc.playerController.isInCreativeMode()) { mainScreen.toggleSurvivalHUD(!mc.playerController.isInCreativeMode()); } // Hunger Bar Begin mainScreen.getHungerBar().render(); // Hunger Bar End // Armor Bar Begin mainScreen.getArmorBar().render(); // Armor Bar End // Health Bar Begin mainScreen.getHealthBar().render(); // Health Bar End // Bubble Bar Begin mainScreen.getBubbleBar().render(); // Bubble Bar End // Exp Bar Begin mainScreen.getExpBar().render(); // Exp Bar End SpoutClient.disableSandbox(); map.onRenderTick(); GL11.glDisable(3042 /* GL_BLEND */); GL11.glEnable('\u803a'); GL11.glPushMatrix(); GL11.glRotatef(120.0F, 1.0F, 0.0F, 0.0F); GL11.glPopMatrix(); RenderHelper.enableGUIStandardItemLighting(); for (var15 = 0; var15 < 9; ++var15) { int x = screenWidth / 2 - 90 + var15 * 20 + 2; var17 = screenHeight - 16 - 3; this.renderInventorySlot(var15, x, var17, f); } RenderHelper.disableStandardItemLighting(); GL11.glDisable('\u803a'); if (this.mc.thePlayer.getSleepTimer() > 0) { GL11.glDisable(2929 /*GL_DEPTH_TEST*/); GL11.glDisable(3008 /*GL_ALPHA_TEST*/); var15 = this.mc.thePlayer.getSleepTimer(); float var26 = (float)var15 / 100.0F; if(var26 > 1.0F) { var26 = 1.0F - (float)(var15 - 100) / 10.0F; } var17 = (int)(220.0F * var26) << 24 | 1052704; this.drawRect(0, 0, screenWidth, screenHeight, var17); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); GL11.glEnable(2929 /*GL_DEPTH_TEST*/); } SpoutClient.enableSandbox(); mainScreen.render(); SpoutClient.disableSandbox(); if (this.mc.gameSettings.showDebugInfo) { this.mc.mcProfiler.startSection("debug"); GL11.glPushMatrix(); font.drawStringWithShadow("Minecraft 1.3.2 (" + this.mc.debug + ")", 2, 2, 16777215); font.drawStringWithShadow(this.mc.debugInfoRenders(), 2, 12, 16777215); font.drawStringWithShadow(this.mc.getEntityDebug(), 2, 22, 16777215); font.drawStringWithShadow(this.mc.debugInfoEntities(), 2, 32, 16777215); font.drawStringWithShadow(this.mc.getWorldProviderName(), 2, 42, 16777215); long var41 = Runtime.getRuntime().maxMemory(); long var34 = Runtime.getRuntime().totalMemory(); long var42 = Runtime.getRuntime().freeMemory(); long var43 = var34 - var42; String var45 = "Used memory: " + var43 * 100L / var41 + "% (" + var43 / 1024L / 1024L + "MB) of " + var41 / 1024L / 1024L + "MB"; this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 2, 14737632); var45 = "Allocated memory: " + var34 * 100L / var41 + "% (" + var34 / 1024L / 1024L + "MB)"; this.drawString(font, var45, screenWidth - font.getStringWidth(var45) - 2, 12, 14737632); if(SpoutClient.getInstance().isCoordsCheat()) { this.drawString(font, String.format("x: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posX)}), 2, 64, 14737632); this.drawString(font, String.format("y: %.3f (feet pos, %.3f eyes pos)", new Object[] {Double.valueOf(this.mc.thePlayer.boundingBox.minY), Double.valueOf(this.mc.thePlayer.posY)}), 2, 72, 14737632); this.drawString(font, String.format("z: %.5f", new Object[] {Double.valueOf(this.mc.thePlayer.posZ)}), 2, 80, 14737632); this.drawString(font, "f: " + (MathHelper.floor_double((double)(this.mc.thePlayer.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3), 2, 88, 14737632); } int var47 = MathHelper.floor_double(this.mc.thePlayer.posX); int var22 = MathHelper.floor_double(this.mc.thePlayer.posY); int var233 = MathHelper.floor_double(this.mc.thePlayer.posZ); if (this.mc.theWorld != null && this.mc.theWorld.blockExists(var47, var22, var233)) { Chunk var48 = this.mc.theWorld.getChunkFromBlockCoords(var47, var233); this.drawString(font, "lc: " + (var48.getTopFilledSegment() + 15) + " b: " + var48.getBiomeGenForWorldCoords(var47 & 15, var233 & 15, this.mc.theWorld.getWorldChunkManager()).biomeName + " bl: " + var48.getSavedLightValue(EnumSkyBlock.Block, var47 & 15, var22, var233 & 15) + " sl: " + var48.getSavedLightValue(EnumSkyBlock.Sky, var47 & 15, var22, var233 & 15) + " rl: " + var48.getBlockLightValue(var47 & 15, var22, var233 & 15, 0), 2, 96, 14737632); } this.drawString(font, String.format("ws: %.3f, fs: %.3f, g: %b", new Object[] {Float.valueOf(this.mc.thePlayer.capabilities.getWalkSpeed()), Float.valueOf(this.mc.thePlayer.capabilities.getFlySpeed()), Boolean.valueOf(this.mc.thePlayer.onGround)}), 2, 104, 14737632); GL11.glPopMatrix(); this.mc.mcProfiler.endSection(); } if(this.recordPlayingUpFor > 0) { float var24 = (float)this.recordPlayingUpFor - f; int fontColor = (int)(var24 * 256.0F / 20.0F); if(fontColor > 255) { fontColor = 255; } if(fontColor > 0) { GL11.glPushMatrix(); GL11.glTranslatef((float)(screenWidth / 2), (float)(screenHeight - 48), 0.0F); GL11.glEnable(3042 /*GL_BLEND*/); GL11.glBlendFunc(770, 771); var17 = 16777215; if(this.recordIsPlaying) { var17 = java.awt.Color.HSBtoRGB(var24 / 50.0F, 0.7F, 0.6F) & 16777215; } font.drawString(this.recordPlaying, -font.getStringWidth(this.recordPlaying) / 2, -4, var17 + (fontColor << 24)); GL11.glDisable(3042 /*GL_BLEND*/); GL11.glPopMatrix(); } } SpoutClient.enableSandbox(); //boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat; //int lines = chatOpen ? mainScreen.getChatTextBox().getNumVisibleChatLines() : mainScreen.getChatTextBox().getNumVisibleLines(); // GL11.glEnable(3042 /*GL_BLEND*/); // GL11.glBlendFunc(770, 771); // GL11.glDisable(3008 /*GL_ALPHA_TEST*/); ChatTextBox chatTextWidget = mainScreen.getChatTextBox(); GL11.glPushMatrix(); boolean chatOpen = mainScreen.getChatBar().isVisible() && mc.currentScreen instanceof GuiChat; if (chatTextWidget.isVisible() || chatOpen) { chatTextWidget.setChatOpen(chatOpen); chatTextWidget.render(); } GL11.glPopMatrix(); // if (chatTextWidget.isVisible()) { // int viewedLine = 0; // for (int line = SpoutClient.getInstance().getChatManager().chatScroll; line < Math.min(chatMessageList.size(), (lines + SpoutClient.getInstance().getChatManager().chatScroll)); line++) { // if (chatOpen || chatMessageList.get(line).updateCounter < chatTextWidget.getFadeoutTicks()) { // double opacity = 1.0D - chatMessageList.get(line).updateCounter / (double)chatTextWidget.getFadeoutTicks(); // opacity *= 10D; // if(opacity < 0.0D) { // opacity = 0.0D; // } // if(opacity > 1.0D) { // opacity = 1.0D; // } // opacity *= opacity; // int color = chatOpen ? 255 : (int)(255D * opacity); // if (color > 0) { // int x = 2 + chatTextWidget.getX(); // int y = chatTextWidget.getY() + (-viewedLine * 9); // String chat = chatMessageList.get(line).message; // chat = SpoutClient.getInstance().getChatManager().formatChatColors(chat); // // boolean mentioned = false; // if (ConfigReader.highlightMentions) { // String[] split = chat.toLowerCase().split(":"); // if (split.length == 1) { // split = chat.toLowerCase().split(">"); // } // if (split.length > 1) { // String name = this.mc.thePlayer.username.toLowerCase(); // if (!split[0].contains(name)) { // for (int part = 1; part < split.length; part++) { // if (split[part].contains(name)) { // mentioned = true; // break; // } // } // } // } // } // // if (mentioned) { // drawRect(x, y - 1, x + 320, y + 8, RED); // } // else { // drawRect(x, y - 1, x + 320, y + 8, color / 2 << 24); // } // GL11.glEnable(3042 /*GL_BLEND*/); // font.drawStringWithShadow(chat, x, y, 0xffffff + (color << 24)); // } // viewedLine++; // } // } // } SpoutClient.disableSandbox(); ServerPlayerList playerList = mainScreen.getServerPlayerList(); if(this.mc.thePlayer instanceof EntityClientPlayerMP && this.mc.gameSettings.keyBindPlayerList.pressed && playerList.isVisible()) { NetClientHandler var41 = ((EntityClientPlayerMP)this.mc.thePlayer).sendQueue; List var44 = var41.playerInfoList; int var40 = var41.currentServerMaxPlayers; int var38 = var40; int var16; for(var16 = 1; var38 > 20; var38 = (var40 + var16 - 1) / var16) { ++var16; } var17 = 300 / var16; if(var17 > 150) { var17 = 150; } int var18 = (screenWidth - var16 * var17) / 2; byte var46 = 10; this.drawRect(var18 - 1, var46 - 1, var18 + var17 * var16, var46 + 9 * var38, Integer.MIN_VALUE); for(int var20 = 0; var20 < var40; ++var20) { int var47 = var18 + var20 % var16 * var17; int var22 = var46 + var20 / var16 * 9; this.drawRect(var47, var22, var47 + var17 - 1, var22 + 8, 553648127); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); if(var20 < var44.size()) { GuiPlayerInfo var50 = (GuiPlayerInfo)var44.get(var20); font.drawStringWithShadow(var50.name, var47, var22, 16777215); this.mc.renderEngine.bindTexture(this.mc.renderEngine.getTexture("/gui/icons.png")); boolean var48 = false; boolean var53 = false; byte var49 = 0; var53 = false; byte var54; if(var50.responseTime < 0) { var54 = 5; } else if(var50.responseTime < 150) { var54 = 0; } else if(var50.responseTime < 300) { var54 = 1; } else if(var50.responseTime < 600) { var54 = 2; } else if(var50.responseTime < 1000) { var54 = 3; } else { var54 = 4; } this.zLevel += 100.0F; this.drawTexturedModalRect(var47 + var17 - 12, var22, 0 + var49 * 10, 176 + var54 * 8, 10, 8); this.zLevel -= 100.0F; } } } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(2896 /*GL_LIGHTING*/); GL11.glEnable(3008 /*GL_ALPHA_TEST*/); GL11.glDisable(3042 /*GL_BLEND*/); }
diff --git a/src/webservice/AplicacionWeb.java b/src/webservice/AplicacionWeb.java index 88bee6f..dd3aa20 100644 --- a/src/webservice/AplicacionWeb.java +++ b/src/webservice/AplicacionWeb.java @@ -1,77 +1,77 @@ package webservice; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import android.util.Log; public class AplicacionWeb{ private Coneccion coneccion; // WebServices URL String serverName = "www.informaticacurico.cl"; String urlLogin = "/listas/login.php"; public AplicacionWeb(){ coneccion = new Coneccion(serverName); } /** * Autentificar al usuario * parametros : usuario, password * retorno : boleano indicando el estado de la autentificacion * @throws AppWebException * @throws IOException * @throws ClientProtocolException */ public String loginUsuario(String usuario, String password) throws AppWebException { // PRIMERO: Enviar el POST y obtener el string de retorno String str = "nada..."; try { str = coneccion.GET_generico(urlLogin); //Log.i("INTERNET", "logeando con usuario:"+usuario+" y password:"+password); - //Log.i("INTERNET", "El servidor responde: "+str ); + Log.i("INTERNET", "El servidor responde correctamente: "+str); } catch (ClientProtocolException e) { - Log.i("DEBUG", "CPE "+e.toString() ); + Log.i("INTERNET", "CPE "+e.toString() ); throw new AppWebException("Problemas al conectar con el servidor"); } catch (IOException e) { - Log.i("DEBUG", "EXC "+e.toString() ); + Log.i("INTERNET", "EXC "+e.toString() ); throw new AppWebException("Coneccion no disponible"); } return str; // SEGUNDO: Convertir el String a JSON //JSONObject jso_resumen; //try{ // jso_resumen = new JSONObject( strRespuesta ); //}catch( org.json.JSONException e2){ // throw new Exception("JSON mal formateado o desconocido"); //} // TERCERO: se ha logeado correctamente? } /** * Obtiene todos los grupos que exisetn en el servidor * retorno : un arreglo con todos los grupos del servidor */ public void getGroups(){} /** * Obtiene los ultimos N mensajes de un grupo * parametros : el id del grupo, la cantidad de mensajes * retorno : un arreglo con los ultimos 10 mensajes del grupo */ public void getLastMessagesFromGroup(){} /** * Obtiene los mensajes de todo los grupos en los que esta subscrito * parametros : conjunto de ID de los grupos a los que seta subscrito * retorna : los ultimos N mensajes de cada uno de los grupos */ public void getLastMessagesFromSubscribedGroups(){} }
false
true
public String loginUsuario(String usuario, String password) throws AppWebException { // PRIMERO: Enviar el POST y obtener el string de retorno String str = "nada..."; try { str = coneccion.GET_generico(urlLogin); //Log.i("INTERNET", "logeando con usuario:"+usuario+" y password:"+password); //Log.i("INTERNET", "El servidor responde: "+str ); } catch (ClientProtocolException e) { Log.i("DEBUG", "CPE "+e.toString() ); throw new AppWebException("Problemas al conectar con el servidor"); } catch (IOException e) { Log.i("DEBUG", "EXC "+e.toString() ); throw new AppWebException("Coneccion no disponible"); } return str; // SEGUNDO: Convertir el String a JSON //JSONObject jso_resumen; //try{ // jso_resumen = new JSONObject( strRespuesta ); //}catch( org.json.JSONException e2){ // throw new Exception("JSON mal formateado o desconocido"); //} // TERCERO: se ha logeado correctamente? }
public String loginUsuario(String usuario, String password) throws AppWebException { // PRIMERO: Enviar el POST y obtener el string de retorno String str = "nada..."; try { str = coneccion.GET_generico(urlLogin); //Log.i("INTERNET", "logeando con usuario:"+usuario+" y password:"+password); Log.i("INTERNET", "El servidor responde correctamente: "+str); } catch (ClientProtocolException e) { Log.i("INTERNET", "CPE "+e.toString() ); throw new AppWebException("Problemas al conectar con el servidor"); } catch (IOException e) { Log.i("INTERNET", "EXC "+e.toString() ); throw new AppWebException("Coneccion no disponible"); } return str; // SEGUNDO: Convertir el String a JSON //JSONObject jso_resumen; //try{ // jso_resumen = new JSONObject( strRespuesta ); //}catch( org.json.JSONException e2){ // throw new Exception("JSON mal formateado o desconocido"); //} // TERCERO: se ha logeado correctamente? }
diff --git a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/DeleteDataversePage.java b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/DeleteDataversePage.java index af46be474..1d6db2359 100644 --- a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/DeleteDataversePage.java +++ b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/DeleteDataversePage.java @@ -1,183 +1,183 @@ /* Copyright (C) 2005-2012, by the President and Fellows of Harvard College. 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. Dataverse Network - A web application to share, preserve and analyze research data. Developed at the Institute for Quantitative Social Science, Harvard University. Version 3.0. */ /* * StudyPage.java * * Created on September 5, 2006, 4:25 PM * Copyright mcrosas */ package edu.harvard.iq.dvn.core.web.site; import edu.harvard.iq.dvn.core.vdc.VDC; import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal; import edu.harvard.iq.dvn.core.web.common.VDCBaseBean; import javax.ejb.EJB; import com.icesoft.faces.component.ext.HtmlInputHidden; import edu.harvard.iq.dvn.core.admin.DvnTimerRemote; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; /** * <p>Page bean that corresponds to a similarly named JSP page. This * class contains component definitions (and initialization code) for * all components that you have defined on this page, as well as * lifecycle methods and event handlers where you may add behavior * to respond to incoming events.</p> */ @ViewScoped @Named("DeleteDataversePage") public class DeleteDataversePage extends VDCBaseBean implements java.io.Serializable { @EJB VDCServiceLocal vdcService; @EJB (name="dvnTimer") DvnTimerRemote remoteTimerService; HtmlInputHidden hiddenVdcId; HtmlInputHidden hiddenVdcName; private String vdcName; private Long cid; private String from; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getVdcName() { return vdcName; } public void setVdcName(String vdcName) { this.vdcName = vdcName; } /** * <p>Construct a new Page bean instance.</p> */ public DeleteDataversePage() { } /** * <p>Callback method that is called whenever a page is navigated to, * either directly via a URL, or indirectly via page navigation. * Customize this method to acquire resources that will be needed * for event handlers and lifecycle methods, whether or not this * page is performing post back processing.</p> * * <p>Note that, if the current request is a postback, the property * values of the components do <strong>not</strong> represent any * values submitted with this request. Instead, they represent the * property values that were saved for this view when it was rendered.</p> */ public void init() { super.init(); if ("manageDataverses".equals(from)) { - from = "/networkAdmin/NetworkOptionsPage.xhtml?faces-redirect=true"; + from = "/networkAdmin/NetworkOptionsPage?faces-redirect=true&tab=harvesting"; } else if ("manageHarvesting".equals(from)){ - from = "/site/HarvestSitesPage?faces-redirect=true"; + from = "/networkAdmin/NetworkOptionsPage?faces-redirect=true&tab=harvesting"; } else { from = "/HomePage?faces-redirect=true"; } System.out.print("From " + from); if (deleteId != null) { VDC vdc = vdcService.find(deleteId); vdcName = vdc.getName(); } } public String delete() { deleteId = (Long)hiddenVdcId.getValue(); VDC vdc = vdcService.find(deleteId); if (vdc.isHarvestingDv()) { remoteTimerService.removeHarvestTimer(vdc.getHarvestingDataverse()); } vdcService.delete(deleteId); getVDCRenderBean().getFlash().put("successMessage", "Successfully deleted dataverse."); return from; } public String cancel() { return from; } /** * Holds value of property deleteId. */ private Long deleteId; /** * Getter for property deleteId. * @return Value of property deleteId. */ public Long getDeleteId() { return this.deleteId; } /** * Setter for property deleteId. * @param deleteId New value of property deleteId. */ public void setDeleteId(Long deleteId) { this.deleteId = deleteId; } public HtmlInputHidden getHiddenVdcId() { return hiddenVdcId; } public void setHiddenVdcId(HtmlInputHidden hiddenVdcId) { this.hiddenVdcId = hiddenVdcId; } public HtmlInputHidden getHiddenVdcName() { return hiddenVdcName; } public void setHiddenVdcName(HtmlInputHidden hiddenVdcName) { this.hiddenVdcName = hiddenVdcName; } private String getFriendlyLinkName(String result) { if ("manageDataverses".equals(result)) return "Manage Dataverses"; else if ("manageHarvesting".equals(result)) return "Manage Harvesting"; else return ""; } }
false
true
public void init() { super.init(); if ("manageDataverses".equals(from)) { from = "/networkAdmin/NetworkOptionsPage.xhtml?faces-redirect=true"; } else if ("manageHarvesting".equals(from)){ from = "/site/HarvestSitesPage?faces-redirect=true"; } else { from = "/HomePage?faces-redirect=true"; } System.out.print("From " + from); if (deleteId != null) { VDC vdc = vdcService.find(deleteId); vdcName = vdc.getName(); } }
public void init() { super.init(); if ("manageDataverses".equals(from)) { from = "/networkAdmin/NetworkOptionsPage?faces-redirect=true&tab=harvesting"; } else if ("manageHarvesting".equals(from)){ from = "/networkAdmin/NetworkOptionsPage?faces-redirect=true&tab=harvesting"; } else { from = "/HomePage?faces-redirect=true"; } System.out.print("From " + from); if (deleteId != null) { VDC vdc = vdcService.find(deleteId); vdcName = vdc.getName(); } }
diff --git a/src/beans/CompleteProductListBean.java b/src/beans/CompleteProductListBean.java index dabfd7c..e042a2d 100644 --- a/src/beans/CompleteProductListBean.java +++ b/src/beans/CompleteProductListBean.java @@ -1,349 +1,348 @@ package beans; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class CompleteProductListBean { private Collection<CompleteProductBean> productList; private String url = null; private Connection conn = null; private Statement stmt = null; private ResultSet rs = null; public CompleteProductListBean() {} public CompleteProductListBean(String _url) throws Exception { this.url = _url; initList(url); } private void initList(String _url) throws Exception{ this.productList = new ArrayList<CompleteProductBean>(); try { Class.forName("com.mysql.jdbc.Driver"); this.conn = DriverManager.getConnection(this.url); this.stmt = this.conn.createStatement(); - String sql = "SELECT B.BOOK_ID, B.TITLE, B.DESCRIPTION, B.PRICE, "; - sql += "B.PROFIT, B.VISIBLE, A.AUTHOR_ID, A.NAME, A.SURNAME, "; - sql += "A.QTY, A.C_PRICE, C.QTY AS NEEDED "; - sql += "FROM BOOKS AS B LEFT JOIN (AUTHORS AS A CROSS JOIN COMPOSITION AS C) ON "; - sql += "B.BOOK_ID = C.EL_ID AND "; - sql += "A.AUTHOR_ID = C.COM_ID ORDER BY BOOK_ID"; + String sql = "SELECT B.BOOK_ID, B.TITLE, B.DESCRIPTION, AV.FINAL_PRICE AS PRICE, "; + sql += "B.PROFIT, B.VISIBLE, B.COM_ID AS AUTHOR_ID, B.NAME, B.SURNAME, "; + sql += "B.IN_STOCK as QTY, B.C_PRICE, B.QTY AS NEEDED "; + sql += "FROM NEEDED AS B LEFT JOIN AVAILABILITY AS AV ON "; + sql += "B.BOOK_ID = AV.BOOK_ID ORDER BY BOOK_ID"; this.rs = this.stmt.executeQuery(sql); int pid = -1; CompleteProductBean cpb = null; while(this.rs.next()) { if(pid != rs.getInt("BOOK_ID")) { cpb = new CompleteProductBean(); pid = rs.getInt("BOOK_ID"); cpb.setId(pid); cpb.setProduct(rs.getString("TITLE")); cpb.setDescription(rs.getString("DESCRIPTION")); cpb.setPrice(rs.getInt("PRICE")); cpb.setProfit(rs.getInt("PROFIT")); cpb.setVisbile(rs.getBoolean("VISIBLE")); ComponentBean cb = new ComponentBean(); cb.setId(rs.getInt("AUTHOR_ID")); cb.setManufacturer(rs.getString("NAME")); cb.setType(rs.getString("SURNAME")); cb.setQuantity(rs.getInt("QTY")); cb.setPrice(rs.getInt("C_PRICE")); cb.setNeeded(rs.getInt("NEEDED")); cpb.addComponent(cb); this.productList.add(cpb); } else { ComponentBean cb = new ComponentBean(); cb.setId(rs.getInt("AUTHOR_ID")); cb.setManufacturer(rs.getString("NAME")); cb.setType(rs.getString("SURNAME")); cb.setQuantity(rs.getInt("QTY")); cb.setPrice(rs.getInt("C_PRICE")); cb.setNeeded(rs.getInt("NEEDED")); cpb.addComponent(cb); } } } catch (SQLException sqle) { throw new Exception(sqle); } finally { try { this.rs.close(); } catch (Exception e) {} try { this.stmt.close(); } catch (Exception e) {} try { this.conn.close(); } catch (Exception e) {} } } public Collection<CompleteProductBean> getProductList() { return this.productList; } public String getXml() throws Exception{ initList(url); StringBuffer xmlOut = new StringBuffer(); Iterator<CompleteProductBean> iter = this.productList.iterator(); CompleteProductBean cpb = null; xmlOut.append("<productlist>"); while(iter.hasNext()) { cpb = iter.next(); xmlOut.append(cpb.getXml()); } xmlOut.append("</productlist>"); return xmlOut.toString(); } public CompleteProductBean getById(int id) { CompleteProductBean cpb = null; Iterator<CompleteProductBean> iter = this.productList.iterator(); while(iter.hasNext()) { cpb = iter.next(); if(cpb.getId() == id) return cpb; } return null; } private void deleteComponent(int productId, int componentId) throws Exception { try { Class.forName("com.mysql.jdbc.Driver"); this.conn = DriverManager.getConnection(this.url); this.stmt = this.conn.createStatement(); String sql = "DELETE FROM COMPOSITION WHERE "; sql += "EL_ID = " + productId + " AND "; sql += "COM_ID = " + componentId; this.stmt.executeUpdate(sql); } catch (SQLException sqle) { throw new Exception(sqle); } finally { try { this.stmt.close(); } catch (Exception e) {} try { this.conn.close(); } catch (Exception e) {} } } private void updateComponent(int productId, int componentId, int newQuantity) throws Exception { try { Class.forName("com.mysql.jdbc.Driver"); this.conn = DriverManager.getConnection(this.url); this.stmt = this.conn.createStatement(); String sql = "UPDATE COMPOSITION SET QTY = " + newQuantity; sql += " WHERE EL_ID = " + productId + " AND"; sql += " COM_ID = " + componentId; this.stmt.executeUpdate(sql); sql = "UPDATE"; } catch (SQLException sqle) { throw new Exception(sqle); } finally { try { this.stmt.close(); } catch (Exception e) {} try { this.conn.close(); } catch (Exception e) {} } } private ComponentBean insertComponent(int productId, int componentId, int quantity) throws Exception { try { Class.forName("com.mysql.jdbc.Driver"); this.conn = DriverManager.getConnection(this.url); this.stmt = this.conn.createStatement(); String sql = "SELECT * FROM AUTHORS WHERE AUTHOR_ID=" + componentId; this.rs = this.stmt.executeQuery(sql); ComponentBean cb = new ComponentBean(); rs.next(); cb.setId(rs.getInt("AUTHOR_ID")); cb.setManufacturer(rs.getString("NAME")); cb.setType(rs.getString("SURNAME")); cb.setQuantity(rs.getInt("QTY")); cb.setPrice(rs.getInt("C_PRICE")); cb.setNeeded(quantity); sql = "INSERT INTO COMPOSITION VALUES(" + productId; sql += ", " + componentId + ", " + quantity + ")"; this.stmt.executeUpdate(sql); return cb; } catch (SQLException sqle) { throw new Exception(sqle); } finally { try { this.rs.close(); } catch (Exception e) {} try { this.stmt.close(); } catch (Exception e) {} try { this.conn.close(); } catch (Exception e) {} } } public void removeComponent(int productId, int componentId, int quantity) throws Exception { Iterator<CompleteProductBean> iter = this.productList.iterator(); CompleteProductBean cpb = null; while(iter.hasNext()) { cpb = iter.next(); if(cpb.getId() == productId) { Iterator<ComponentBean> it = cpb.getComponents().iterator(); ComponentBean cb = null; while(it.hasNext()) { cb = it.next(); if(cb.getId() == componentId) { if(cb.getNeeded() == quantity) { deleteComponent(productId, componentId); cpb.setPrice(cpb.getPrice() - (quantity*cb.getPrice())); it.remove(); break; } else { updateComponent(productId, componentId, cb.getNeeded()-quantity); cb.setNeeded(cb.getNeeded()-quantity); cpb.setPrice(cpb.getPrice() - (quantity*cb.getPrice())); break; } } } break; } } } public void addComponent(int productId, int componentId, int quantity) throws Exception { Iterator<CompleteProductBean> iter = this.productList.iterator(); CompleteProductBean cpb = null; while(iter.hasNext()) { cpb = iter.next(); if(cpb.getId() == productId) { Iterator<ComponentBean> it = cpb.getComponents().iterator(); ComponentBean cb = null; boolean found = false; while(it.hasNext()) { cb = it.next(); if(cb.getId() == componentId) { updateComponent(productId, componentId, cb.getNeeded()+quantity); cb.setNeeded(cb.getNeeded()+quantity); cpb.setPrice(cpb.getPrice() + (quantity*cb.getPrice())); found = true; break; } } if(!found) { ComponentBean ncb = null; ncb = insertComponent(productId, componentId, quantity); cpb.addComponent(ncb); cpb.setPrice(cpb.getPrice() + (quantity*ncb.getPrice())); } break; } } } public void updateProduct(int productId, String _product, String _description, boolean _visible, int _profit) throws Exception { Iterator<CompleteProductBean> iter = this.productList.iterator(); CompleteProductBean cpb = null; boolean found = false; while(iter.hasNext() && !found) { cpb = iter.next(); if(cpb.getId() == productId) { found = true; } } if(!found) return; int profit_diff = _profit - cpb.getProfit(); try { Class.forName("com.mysql.jdbc.Driver"); this.conn = DriverManager.getConnection(this.url); this.stmt = this.conn.createStatement(); String sql = "UPDATE BOOKS SET TITLE = '" + _product + "', "; sql += "DESCRIPTION = '" + _description + "', "; sql += "PROFIT = " + _profit + ", "; sql += "PRICE = " + (cpb.getPrice() + profit_diff) + ", "; if(_visible) sql += "VISIBLE = 1 "; else sql += "VISIBLE = 0 "; sql += "WHERE BOOK_ID = " + productId; this.stmt.executeUpdate(sql); cpb.setProduct(_product); cpb.setDescription(_description); cpb.setProfit(_profit); cpb.setVisbile(_visible); cpb.setPrice(cpb.getPrice() + profit_diff); } catch (SQLException sqle) { throw new Exception(sqle); } finally { try { this.stmt.close(); } catch (Exception e) {} try { this.conn.close(); } catch (Exception e) {} } } }
true
true
private void initList(String _url) throws Exception{ this.productList = new ArrayList<CompleteProductBean>(); try { Class.forName("com.mysql.jdbc.Driver"); this.conn = DriverManager.getConnection(this.url); this.stmt = this.conn.createStatement(); String sql = "SELECT B.BOOK_ID, B.TITLE, B.DESCRIPTION, B.PRICE, "; sql += "B.PROFIT, B.VISIBLE, A.AUTHOR_ID, A.NAME, A.SURNAME, "; sql += "A.QTY, A.C_PRICE, C.QTY AS NEEDED "; sql += "FROM BOOKS AS B LEFT JOIN (AUTHORS AS A CROSS JOIN COMPOSITION AS C) ON "; sql += "B.BOOK_ID = C.EL_ID AND "; sql += "A.AUTHOR_ID = C.COM_ID ORDER BY BOOK_ID"; this.rs = this.stmt.executeQuery(sql); int pid = -1; CompleteProductBean cpb = null; while(this.rs.next()) { if(pid != rs.getInt("BOOK_ID")) { cpb = new CompleteProductBean(); pid = rs.getInt("BOOK_ID"); cpb.setId(pid); cpb.setProduct(rs.getString("TITLE")); cpb.setDescription(rs.getString("DESCRIPTION")); cpb.setPrice(rs.getInt("PRICE")); cpb.setProfit(rs.getInt("PROFIT")); cpb.setVisbile(rs.getBoolean("VISIBLE")); ComponentBean cb = new ComponentBean(); cb.setId(rs.getInt("AUTHOR_ID")); cb.setManufacturer(rs.getString("NAME")); cb.setType(rs.getString("SURNAME")); cb.setQuantity(rs.getInt("QTY")); cb.setPrice(rs.getInt("C_PRICE")); cb.setNeeded(rs.getInt("NEEDED")); cpb.addComponent(cb); this.productList.add(cpb); } else { ComponentBean cb = new ComponentBean(); cb.setId(rs.getInt("AUTHOR_ID")); cb.setManufacturer(rs.getString("NAME")); cb.setType(rs.getString("SURNAME")); cb.setQuantity(rs.getInt("QTY")); cb.setPrice(rs.getInt("C_PRICE")); cb.setNeeded(rs.getInt("NEEDED")); cpb.addComponent(cb); } } } catch (SQLException sqle) { throw new Exception(sqle); } finally { try { this.rs.close(); } catch (Exception e) {} try { this.stmt.close(); } catch (Exception e) {} try { this.conn.close(); } catch (Exception e) {} } }
private void initList(String _url) throws Exception{ this.productList = new ArrayList<CompleteProductBean>(); try { Class.forName("com.mysql.jdbc.Driver"); this.conn = DriverManager.getConnection(this.url); this.stmt = this.conn.createStatement(); String sql = "SELECT B.BOOK_ID, B.TITLE, B.DESCRIPTION, AV.FINAL_PRICE AS PRICE, "; sql += "B.PROFIT, B.VISIBLE, B.COM_ID AS AUTHOR_ID, B.NAME, B.SURNAME, "; sql += "B.IN_STOCK as QTY, B.C_PRICE, B.QTY AS NEEDED "; sql += "FROM NEEDED AS B LEFT JOIN AVAILABILITY AS AV ON "; sql += "B.BOOK_ID = AV.BOOK_ID ORDER BY BOOK_ID"; this.rs = this.stmt.executeQuery(sql); int pid = -1; CompleteProductBean cpb = null; while(this.rs.next()) { if(pid != rs.getInt("BOOK_ID")) { cpb = new CompleteProductBean(); pid = rs.getInt("BOOK_ID"); cpb.setId(pid); cpb.setProduct(rs.getString("TITLE")); cpb.setDescription(rs.getString("DESCRIPTION")); cpb.setPrice(rs.getInt("PRICE")); cpb.setProfit(rs.getInt("PROFIT")); cpb.setVisbile(rs.getBoolean("VISIBLE")); ComponentBean cb = new ComponentBean(); cb.setId(rs.getInt("AUTHOR_ID")); cb.setManufacturer(rs.getString("NAME")); cb.setType(rs.getString("SURNAME")); cb.setQuantity(rs.getInt("QTY")); cb.setPrice(rs.getInt("C_PRICE")); cb.setNeeded(rs.getInt("NEEDED")); cpb.addComponent(cb); this.productList.add(cpb); } else { ComponentBean cb = new ComponentBean(); cb.setId(rs.getInt("AUTHOR_ID")); cb.setManufacturer(rs.getString("NAME")); cb.setType(rs.getString("SURNAME")); cb.setQuantity(rs.getInt("QTY")); cb.setPrice(rs.getInt("C_PRICE")); cb.setNeeded(rs.getInt("NEEDED")); cpb.addComponent(cb); } } } catch (SQLException sqle) { throw new Exception(sqle); } finally { try { this.rs.close(); } catch (Exception e) {} try { this.stmt.close(); } catch (Exception e) {} try { this.conn.close(); } catch (Exception e) {} } }
diff --git a/redelm-column/src/main/java/redelm/column/primitive/SimplePrimitiveColumnReader.java b/redelm-column/src/main/java/redelm/column/primitive/SimplePrimitiveColumnReader.java index c43803c..500b50f 100644 --- a/redelm-column/src/main/java/redelm/column/primitive/SimplePrimitiveColumnReader.java +++ b/redelm-column/src/main/java/redelm/column/primitive/SimplePrimitiveColumnReader.java @@ -1,116 +1,120 @@ /** * Copyright 2012 Twitter, 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 redelm.column.primitive; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import static redelm.column.primitive.SimplePrimitiveColumnWriter.CHARSET; public class SimplePrimitiveColumnReader extends PrimitiveColumnReader { private DataInputStream in; public SimplePrimitiveColumnReader(byte[] data, int offset, int length) { this.in = new DataInputStream(new ByteArrayInputStream(data, offset, length)); } @Override public float readFloat() { try { return in.readFloat(); } catch (IOException e) { throw new RuntimeException("never happens", e); } } @Override public byte[] readBytes() { try { byte[] value = new byte[in.readInt()]; in.readFully(value); return value; } catch (IOException e) { throw new RuntimeException("never happens", e); } } @Override public boolean readBoolean() { try { return in.readBoolean(); } catch (IOException e) { throw new RuntimeException("never happens", e); } } @Override public String readString() { try { int size = in.readInt(); - byte[] bytes = new byte[size]; - int i = 0; - do { - int n = in.read(bytes, i, bytes.length - i); - if (n == -1) { - throw new RuntimeException("Reached end of stream"); - } - i = i + n; - } while (i < bytes.length); - return new String(bytes, CHARSET); + if (size == 0) { + return ""; + } else { + byte[] bytes = new byte[size]; + int i = 0; + do { + int n = in.read(bytes, i, bytes.length - i); + if (n == -1) { + throw new RuntimeException("Reached end of stream"); + } + i = i + n; + } while (i < bytes.length); + return new String(bytes, CHARSET); + } } catch (IOException e) { throw new RuntimeException("never happens", e); } } @Override public double readDouble() { try { return in.readDouble(); } catch (IOException e) { throw new RuntimeException("never happens", e); } } @Override public int readInt() { try { return in.readInt(); } catch (IOException e) { throw new RuntimeException("never happens", e); } } @Override public long readLong() { try { return in.readLong(); } catch (IOException e) { throw new RuntimeException("never happens", e); } } @Override public int readByte() { try { return in.read(); } catch (IOException e) { throw new RuntimeException("never happens", e); } } }
true
true
public String readString() { try { int size = in.readInt(); byte[] bytes = new byte[size]; int i = 0; do { int n = in.read(bytes, i, bytes.length - i); if (n == -1) { throw new RuntimeException("Reached end of stream"); } i = i + n; } while (i < bytes.length); return new String(bytes, CHARSET); } catch (IOException e) { throw new RuntimeException("never happens", e); } }
public String readString() { try { int size = in.readInt(); if (size == 0) { return ""; } else { byte[] bytes = new byte[size]; int i = 0; do { int n = in.read(bytes, i, bytes.length - i); if (n == -1) { throw new RuntimeException("Reached end of stream"); } i = i + n; } while (i < bytes.length); return new String(bytes, CHARSET); } } catch (IOException e) { throw new RuntimeException("never happens", e); } }
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryChart.java b/src/com/android/settings/fuelgauge/BatteryHistoryChart.java index 25d86098f..acd9ee447 100644 --- a/src/com/android/settings/fuelgauge/BatteryHistoryChart.java +++ b/src/com/android/settings/fuelgauge/BatteryHistoryChart.java @@ -1,672 +1,672 @@ /* * 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.fuelgauge; import com.android.settings.R; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Typeface; import android.os.BatteryStats; import android.os.SystemClock; import android.os.BatteryStats.HistoryItem; import android.telephony.ServiceState; import android.text.TextPaint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; public class BatteryHistoryChart extends View { static final int SANS = 1; static final int SERIF = 2; static final int MONOSPACE = 3; static final int BATTERY_WARN = 29; static final int BATTERY_CRITICAL = 14; // First value if for phone off; sirst value is "scanning"; following values // are battery stats signal strength buckets. static final int NUM_PHONE_SIGNALS = 7; final Paint mBatteryBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); final Paint mBatteryGoodPaint = new Paint(Paint.ANTI_ALIAS_FLAG); final Paint mBatteryWarnPaint = new Paint(Paint.ANTI_ALIAS_FLAG); final Paint mBatteryCriticalPaint = new Paint(Paint.ANTI_ALIAS_FLAG); final Paint mChargingPaint = new Paint(); final Paint mScreenOnPaint = new Paint(); final Paint mGpsOnPaint = new Paint(); final Paint mWifiRunningPaint = new Paint(); final Paint mWakeLockPaint = new Paint(); final Paint[] mPhoneSignalPaints = new Paint[NUM_PHONE_SIGNALS]; final int[] mPhoneSignalColors = new int[] { 0x00000000, 0xffa00000, 0xffa0a000, 0xff808020, 0xff808040, 0xff808060, 0xff008000 }; final TextPaint mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); final Path mBatLevelPath = new Path(); final Path mBatGoodPath = new Path(); final Path mBatWarnPath = new Path(); final Path mBatCriticalPath = new Path(); final Path mChargingPath = new Path(); final Path mScreenOnPath = new Path(); final Path mGpsOnPath = new Path(); final Path mWifiRunningPath = new Path(); final Path mWakeLockPath = new Path(); int mFontSize; BatteryStats mStats; long mStatsPeriod; String mDurationString; String mTotalDurationString; String mChargingLabel; String mScreenOnLabel; String mGpsOnLabel; String mWifiRunningLabel; String mWakeLockLabel; String mPhoneSignalLabel; int mTextAscent; int mTextDescent; int mDurationStringWidth; int mTotalDurationStringWidth; boolean mLargeMode; int mLineWidth; int mThinLineWidth; int mChargingOffset; int mScreenOnOffset; int mGpsOnOffset; int mWifiRunningOffset; int mWakeLockOffset; int mPhoneSignalOffset; int mLevelOffset; int mLevelTop; int mLevelBottom; static final int PHONE_SIGNAL_X_MASK = 0x0000ffff; static final int PHONE_SIGNAL_BIN_MASK = 0xffff0000; static final int PHONE_SIGNAL_BIN_SHIFT = 16; int mNumPhoneSignalTicks; int[] mPhoneSignalTicks; int mNumHist; BatteryStats.HistoryItem mHistFirst; long mHistStart; long mHistEnd; int mBatLow; int mBatHigh; boolean mHaveWifi; boolean mHaveGps; public BatteryHistoryChart(Context context, AttributeSet attrs) { super(context, attrs); mBatteryBackgroundPaint.setARGB(255, 128, 128, 128); mBatteryBackgroundPaint.setStyle(Paint.Style.FILL); mBatteryGoodPaint.setARGB(128, 0, 255, 0); mBatteryGoodPaint.setStyle(Paint.Style.STROKE); mBatteryWarnPaint.setARGB(128, 255, 255, 0); mBatteryWarnPaint.setStyle(Paint.Style.STROKE); mBatteryCriticalPaint.setARGB(192, 255, 0, 0); mBatteryCriticalPaint.setStyle(Paint.Style.STROKE); mChargingPaint.setARGB(255, 0, 128, 0); mChargingPaint.setStyle(Paint.Style.STROKE); mScreenOnPaint.setARGB(255, 0, 0, 255); mScreenOnPaint.setStyle(Paint.Style.STROKE); mGpsOnPaint.setARGB(255, 0, 0, 255); mGpsOnPaint.setStyle(Paint.Style.STROKE); mWifiRunningPaint.setARGB(255, 0, 0, 255); mWifiRunningPaint.setStyle(Paint.Style.STROKE); mWakeLockPaint.setARGB(255, 0, 0, 255); mWakeLockPaint.setStyle(Paint.Style.STROKE); for (int i=0; i<NUM_PHONE_SIGNALS; i++) { mPhoneSignalPaints[i] = new Paint(); mPhoneSignalPaints[i].setColor(mPhoneSignalColors[i]); mPhoneSignalPaints[i].setStyle(Paint.Style.FILL); } mTextPaint.density = getResources().getDisplayMetrics().density; mTextPaint.setCompatibilityScaling( getResources().getCompatibilityInfo().applicationScale); TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.BatteryHistoryChart, 0, 0); ColorStateList textColor = null; int textSize = 15; int typefaceIndex = -1; int styleIndex = -1; TypedArray appearance = null; int ap = a.getResourceId(R.styleable.BatteryHistoryChart_android_textAppearance, -1); if (ap != -1) { appearance = context.obtainStyledAttributes(ap, com.android.internal.R.styleable. TextAppearance); } if (appearance != null) { int n = appearance.getIndexCount(); for (int i = 0; i < n; i++) { int attr = appearance.getIndex(i); switch (attr) { case com.android.internal.R.styleable.TextAppearance_textColor: textColor = appearance.getColorStateList(attr); break; case com.android.internal.R.styleable.TextAppearance_textSize: textSize = appearance.getDimensionPixelSize(attr, textSize); break; case com.android.internal.R.styleable.TextAppearance_typeface: typefaceIndex = appearance.getInt(attr, -1); break; case com.android.internal.R.styleable.TextAppearance_textStyle: styleIndex = appearance.getInt(attr, -1); break; } } appearance.recycle(); } int shadowcolor = 0; float dx=0, dy=0, r=0; int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.BatteryHistoryChart_android_shadowColor: shadowcolor = a.getInt(attr, 0); break; case R.styleable.BatteryHistoryChart_android_shadowDx: dx = a.getFloat(attr, 0); break; case R.styleable.BatteryHistoryChart_android_shadowDy: dy = a.getFloat(attr, 0); break; case R.styleable.BatteryHistoryChart_android_shadowRadius: r = a.getFloat(attr, 0); break; case R.styleable.BatteryHistoryChart_android_textColor: textColor = a.getColorStateList(attr); break; case R.styleable.BatteryHistoryChart_android_textSize: textSize = a.getDimensionPixelSize(attr, textSize); break; case R.styleable.BatteryHistoryChart_android_typeface: typefaceIndex = a.getInt(attr, typefaceIndex); break; case R.styleable.BatteryHistoryChart_android_textStyle: styleIndex = a.getInt(attr, styleIndex); break; } } mTextPaint.setColor(textColor.getDefaultColor()); mTextPaint.setTextSize(textSize); Typeface tf = null; switch (typefaceIndex) { case SANS: tf = Typeface.SANS_SERIF; break; case SERIF: tf = Typeface.SERIF; break; case MONOSPACE: tf = Typeface.MONOSPACE; break; } setTypeface(tf, styleIndex); if (shadowcolor != 0) { mTextPaint.setShadowLayer(r, dx, dy, shadowcolor); } } public void setTypeface(Typeface tf, int style) { if (style > 0) { if (tf == null) { tf = Typeface.defaultFromStyle(style); } else { tf = Typeface.create(tf, style); } mTextPaint.setTypeface(tf); // now compute what (if any) algorithmic styling is needed int typefaceStyle = tf != null ? tf.getStyle() : 0; int need = style & ~typefaceStyle; mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); } else { mTextPaint.setFakeBoldText(false); mTextPaint.setTextSkewX(0); mTextPaint.setTypeface(tf); } } void setStats(BatteryStats stats) { mStats = stats; long uSecTime = mStats.computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, BatteryStats.STATS_SINCE_CHARGED); mStatsPeriod = uSecTime; String durationString = Utils.formatElapsedTime(getContext(), mStatsPeriod / 1000); mDurationString = getContext().getString(R.string.battery_stats_on_battery, durationString); mChargingLabel = getContext().getString(R.string.battery_stats_charging_label); mScreenOnLabel = getContext().getString(R.string.battery_stats_screen_on_label); mGpsOnLabel = getContext().getString(R.string.battery_stats_gps_on_label); mWifiRunningLabel = getContext().getString(R.string.battery_stats_wifi_running_label); mWakeLockLabel = getContext().getString(R.string.battery_stats_wake_lock_label); mPhoneSignalLabel = getContext().getString(R.string.battery_stats_phone_signal_label); BatteryStats.HistoryItem rec = stats.getHistory(); mHistFirst = null; int pos = 0; int lastInteresting = 0; byte lastLevel = -1; mBatLow = 0; mBatHigh = 100; int aggrStates = 0; while (rec != null) { pos++; if (rec.cmd == HistoryItem.CMD_UPDATE) { if (mHistFirst == null) { mHistFirst = rec; mHistStart = rec.time; } if (rec.batteryLevel != lastLevel || pos == 1) { lastLevel = rec.batteryLevel; lastInteresting = pos; mHistEnd = rec.time; } aggrStates |= rec.states; } rec = rec.next; } mNumHist = lastInteresting; mHaveGps = (aggrStates&HistoryItem.STATE_GPS_ON_FLAG) != 0; mHaveWifi = (aggrStates&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0; if (mHistEnd <= mHistStart) mHistEnd = mHistStart+1; mTotalDurationString = Utils.formatElapsedTime(getContext(), mHistEnd - mHistStart); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mDurationStringWidth = (int)mTextPaint.measureText(mDurationString); mTotalDurationStringWidth = (int)mTextPaint.measureText(mTotalDurationString); mTextAscent = (int)mTextPaint.ascent(); mTextDescent = (int)mTextPaint.descent(); } void addPhoneSignalTick(int x, int bin) { mPhoneSignalTicks[mNumPhoneSignalTicks] = x | bin << PHONE_SIGNAL_BIN_SHIFT; mNumPhoneSignalTicks++; } void finishPaths(int w, int h, int levelh, int startX, int y, Path curLevelPath, int lastX, boolean lastCharging, boolean lastScreenOn, boolean lastGpsOn, boolean lastWifiRunning, boolean lastWakeLock, int lastPhoneSignal, Path lastPath) { if (curLevelPath != null) { if (lastX >= 0 && lastX < w) { if (lastPath != null) { lastPath.lineTo(w, y); } curLevelPath.lineTo(w, y); } curLevelPath.lineTo(w, mLevelTop+levelh); curLevelPath.lineTo(startX, mLevelTop+levelh); curLevelPath.close(); } if (lastCharging) { mChargingPath.lineTo(w, h-mChargingOffset); } if (lastScreenOn) { mScreenOnPath.lineTo(w, h-mScreenOnOffset); } if (lastGpsOn) { mGpsOnPath.lineTo(w, h-mGpsOnOffset); } if (lastWifiRunning) { mWifiRunningPath.lineTo(w, h-mWifiRunningOffset); } if (lastWakeLock) { mWakeLockPath.lineTo(w, h-mWakeLockOffset); } if (lastPhoneSignal != 0) { addPhoneSignalTick(w, 0); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int textHeight = mTextDescent - mTextAscent; mThinLineWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()); if (h > (textHeight*6)) { mLargeMode = true; mLineWidth = textHeight/2; mLevelTop = textHeight + mLineWidth; } else { mLargeMode = false; mLineWidth = mThinLineWidth; mLevelTop = 0; } if (mLineWidth <= 0) mLineWidth = 1; mTextPaint.setStrokeWidth(mThinLineWidth); mBatteryGoodPaint.setStrokeWidth(mThinLineWidth); mBatteryWarnPaint.setStrokeWidth(mThinLineWidth); mBatteryCriticalPaint.setStrokeWidth(mThinLineWidth); mChargingPaint.setStrokeWidth(mLineWidth); mScreenOnPaint.setStrokeWidth(mLineWidth); mGpsOnPaint.setStrokeWidth(mLineWidth); mWifiRunningPaint.setStrokeWidth(mLineWidth); mWakeLockPaint.setStrokeWidth(mLineWidth); if (mLargeMode) { int barOffset = textHeight + mLineWidth; mChargingOffset = mLineWidth; mScreenOnOffset = mChargingOffset + barOffset; mWakeLockOffset = mScreenOnOffset + barOffset; mWifiRunningOffset = mWakeLockOffset + barOffset; - mGpsOnOffset = mHaveWifi ? (mWifiRunningOffset + barOffset) : mWakeLockOffset; - mPhoneSignalOffset = mHaveGps ? (mGpsOnOffset + barOffset) : mWifiRunningOffset; + mGpsOnOffset = mWifiRunningOffset + (mHaveWifi ? barOffset : 0); + mPhoneSignalOffset = mGpsOnOffset + (mHaveGps ? barOffset : 0); mLevelOffset = mPhoneSignalOffset + barOffset + mLineWidth; mPhoneSignalTicks = new int[w+2]; } else { mScreenOnOffset = mGpsOnOffset = mWifiRunningOffset = mWakeLockOffset = mLineWidth; mChargingOffset = mLineWidth*2; mPhoneSignalOffset = 0; mLevelOffset = mLineWidth*3; mPhoneSignalTicks = null; } mBatLevelPath.reset(); mBatGoodPath.reset(); mBatWarnPath.reset(); mBatCriticalPath.reset(); mScreenOnPath.reset(); mGpsOnPath.reset(); mWifiRunningPath.reset(); mWakeLockPath.reset(); mChargingPath.reset(); final long timeStart = mHistStart; final long timeChange = mHistEnd-mHistStart; final int batLow = mBatLow; final int batChange = mBatHigh-mBatLow; final int levelh = h - mLevelOffset - mLevelTop; mLevelBottom = mLevelTop + levelh; BatteryStats.HistoryItem rec = mHistFirst; int x = 0, y = 0, startX = 0, lastX = -1, lastY = -1; int i = 0; Path curLevelPath = null; Path lastLinePath = null; boolean lastCharging = false, lastScreenOn = false, lastGpsOn = false; boolean lastWifiRunning = false, lastWakeLock = false; int lastPhoneSignalBin = 0; final int N = mNumHist; while (rec != null && i < N) { if (rec.cmd == BatteryStats.HistoryItem.CMD_UPDATE) { x = (int)(((rec.time-timeStart)*w)/timeChange); y = mLevelTop + levelh - ((rec.batteryLevel-batLow)*(levelh-1))/batChange; if (lastX != x) { // We have moved by at least a pixel. if (lastY != y) { // Don't plot changes within a pixel. Path path; byte value = rec.batteryLevel; if (value <= BATTERY_CRITICAL) path = mBatCriticalPath; else if (value <= BATTERY_WARN) path = mBatWarnPath; else path = mBatGoodPath; if (path != lastLinePath) { if (lastLinePath != null) { lastLinePath.lineTo(x, y); } path.moveTo(x, y); lastLinePath = path; } else { path.lineTo(x, y); } if (curLevelPath == null) { curLevelPath = mBatLevelPath; curLevelPath.moveTo(x, y); startX = x; } else { curLevelPath.lineTo(x, y); } lastX = x; lastY = y; } final boolean charging = (rec.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) != 0; if (charging != lastCharging) { if (charging) { mChargingPath.moveTo(x, h-mChargingOffset); } else { mChargingPath.lineTo(x, h-mChargingOffset); } lastCharging = charging; } final boolean screenOn = (rec.states&HistoryItem.STATE_SCREEN_ON_FLAG) != 0; if (screenOn != lastScreenOn) { if (screenOn) { mScreenOnPath.moveTo(x, h-mScreenOnOffset); } else { mScreenOnPath.lineTo(x, h-mScreenOnOffset); } lastScreenOn = screenOn; } final boolean gpsOn = (rec.states&HistoryItem.STATE_GPS_ON_FLAG) != 0; if (gpsOn != lastGpsOn) { if (gpsOn) { mGpsOnPath.moveTo(x, h-mGpsOnOffset); } else { mGpsOnPath.lineTo(x, h-mGpsOnOffset); } lastGpsOn = gpsOn; } final boolean wifiRunning = (rec.states&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0; if (wifiRunning != lastWifiRunning) { if (wifiRunning) { mWifiRunningPath.moveTo(x, h-mWifiRunningOffset); } else { mWifiRunningPath.lineTo(x, h-mWifiRunningOffset); } lastWifiRunning = wifiRunning; } final boolean wakeLock = (rec.states&HistoryItem.STATE_WAKE_LOCK_FLAG) != 0; if (wakeLock != lastWakeLock) { if (wakeLock) { mWakeLockPath.moveTo(x, h-mWakeLockOffset); } else { mWakeLockPath.lineTo(x, h-mWakeLockOffset); } lastWakeLock = wakeLock; } if (mLargeMode) { int bin; if (((rec.states&HistoryItem.STATE_PHONE_STATE_MASK) >> HistoryItem.STATE_PHONE_STATE_SHIFT) == ServiceState.STATE_POWER_OFF) { bin = 0; } else if ((rec.states&HistoryItem.STATE_PHONE_SCANNING_FLAG) != 0) { bin = 1; } else { bin = (rec.states&HistoryItem.STATE_SIGNAL_STRENGTH_MASK) >> HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT; bin += 2; } if (bin != lastPhoneSignalBin) { addPhoneSignalTick(x, bin); lastPhoneSignalBin = bin; } } } } else if (curLevelPath != null) { finishPaths(x+1, h, levelh, startX, lastY, curLevelPath, lastX, lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning, lastWakeLock, lastPhoneSignalBin, lastLinePath); lastX = lastY = -1; curLevelPath = null; lastLinePath = null; lastCharging = lastScreenOn = lastGpsOn = lastWakeLock = false; lastPhoneSignalBin = 0; } rec = rec.next; i++; } finishPaths(w, h, levelh, startX, lastY, curLevelPath, lastX, lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning, lastWakeLock, lastPhoneSignalBin, lastLinePath); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); final int width = getWidth(); final int height = getHeight(); canvas.drawPath(mBatLevelPath, mBatteryBackgroundPaint); if (mLargeMode) { canvas.drawText(mDurationString, 0, -mTextAscent + (mLineWidth/2), mTextPaint); canvas.drawText(mTotalDurationString, (width/2) - (mTotalDurationStringWidth/2), mLevelBottom - mTextAscent + mThinLineWidth, mTextPaint); } else { canvas.drawText(mDurationString, (width/2) - (mDurationStringWidth/2), (height/2) - ((mTextDescent-mTextAscent)/2) - mTextAscent, mTextPaint); } if (!mBatGoodPath.isEmpty()) { canvas.drawPath(mBatGoodPath, mBatteryGoodPaint); } if (!mBatWarnPath.isEmpty()) { canvas.drawPath(mBatWarnPath, mBatteryWarnPaint); } if (!mBatCriticalPath.isEmpty()) { canvas.drawPath(mBatCriticalPath, mBatteryCriticalPaint); } int lastBin=0, lastX=0; int top = height-mPhoneSignalOffset - (mLineWidth/2); int bottom = top + mLineWidth; for (int i=0; i<mNumPhoneSignalTicks; i++) { int tick = mPhoneSignalTicks[i]; int x = tick&PHONE_SIGNAL_X_MASK; int bin = (tick&PHONE_SIGNAL_BIN_MASK) >> PHONE_SIGNAL_BIN_SHIFT; if (lastBin != 0) { canvas.drawRect(lastX, top, x, bottom, mPhoneSignalPaints[lastBin]); } lastBin = bin; lastX = x; } if (!mScreenOnPath.isEmpty()) { canvas.drawPath(mScreenOnPath, mScreenOnPaint); } if (!mChargingPath.isEmpty()) { canvas.drawPath(mChargingPath, mChargingPaint); } if (mHaveGps) { if (!mGpsOnPath.isEmpty()) { canvas.drawPath(mGpsOnPath, mGpsOnPaint); } } if (mHaveWifi) { if (!mWifiRunningPath.isEmpty()) { canvas.drawPath(mWifiRunningPath, mWifiRunningPaint); } } if (!mWakeLockPath.isEmpty()) { canvas.drawPath(mWakeLockPath, mWakeLockPaint); } if (mLargeMode) { canvas.drawText(mPhoneSignalLabel, 0, height - mPhoneSignalOffset - mTextDescent, mTextPaint); if (mHaveGps) { canvas.drawText(mGpsOnLabel, 0, height - mGpsOnOffset - mTextDescent, mTextPaint); } if (mHaveWifi) { canvas.drawText(mWifiRunningLabel, 0, height - mWifiRunningOffset - mTextDescent, mTextPaint); } canvas.drawText(mWakeLockLabel, 0, height - mWakeLockOffset - mTextDescent, mTextPaint); canvas.drawText(mChargingLabel, 0, height - mChargingOffset - mTextDescent, mTextPaint); canvas.drawText(mScreenOnLabel, 0, height - mScreenOnOffset - mTextDescent, mTextPaint); canvas.drawLine(0, mLevelBottom+(mThinLineWidth/2), width, mLevelBottom+(mThinLineWidth/2), mTextPaint); canvas.drawLine(0, mLevelTop, 0, mLevelBottom+(mThinLineWidth/2), mTextPaint); for (int i=0; i<10; i++) { int y = mLevelTop + ((mLevelBottom-mLevelTop)*i)/10; canvas.drawLine(0, y, mThinLineWidth*2, y, mTextPaint); } } } }
true
true
protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int textHeight = mTextDescent - mTextAscent; mThinLineWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()); if (h > (textHeight*6)) { mLargeMode = true; mLineWidth = textHeight/2; mLevelTop = textHeight + mLineWidth; } else { mLargeMode = false; mLineWidth = mThinLineWidth; mLevelTop = 0; } if (mLineWidth <= 0) mLineWidth = 1; mTextPaint.setStrokeWidth(mThinLineWidth); mBatteryGoodPaint.setStrokeWidth(mThinLineWidth); mBatteryWarnPaint.setStrokeWidth(mThinLineWidth); mBatteryCriticalPaint.setStrokeWidth(mThinLineWidth); mChargingPaint.setStrokeWidth(mLineWidth); mScreenOnPaint.setStrokeWidth(mLineWidth); mGpsOnPaint.setStrokeWidth(mLineWidth); mWifiRunningPaint.setStrokeWidth(mLineWidth); mWakeLockPaint.setStrokeWidth(mLineWidth); if (mLargeMode) { int barOffset = textHeight + mLineWidth; mChargingOffset = mLineWidth; mScreenOnOffset = mChargingOffset + barOffset; mWakeLockOffset = mScreenOnOffset + barOffset; mWifiRunningOffset = mWakeLockOffset + barOffset; mGpsOnOffset = mHaveWifi ? (mWifiRunningOffset + barOffset) : mWakeLockOffset; mPhoneSignalOffset = mHaveGps ? (mGpsOnOffset + barOffset) : mWifiRunningOffset; mLevelOffset = mPhoneSignalOffset + barOffset + mLineWidth; mPhoneSignalTicks = new int[w+2]; } else { mScreenOnOffset = mGpsOnOffset = mWifiRunningOffset = mWakeLockOffset = mLineWidth; mChargingOffset = mLineWidth*2; mPhoneSignalOffset = 0; mLevelOffset = mLineWidth*3; mPhoneSignalTicks = null; } mBatLevelPath.reset(); mBatGoodPath.reset(); mBatWarnPath.reset(); mBatCriticalPath.reset(); mScreenOnPath.reset(); mGpsOnPath.reset(); mWifiRunningPath.reset(); mWakeLockPath.reset(); mChargingPath.reset(); final long timeStart = mHistStart; final long timeChange = mHistEnd-mHistStart; final int batLow = mBatLow; final int batChange = mBatHigh-mBatLow; final int levelh = h - mLevelOffset - mLevelTop; mLevelBottom = mLevelTop + levelh; BatteryStats.HistoryItem rec = mHistFirst; int x = 0, y = 0, startX = 0, lastX = -1, lastY = -1; int i = 0; Path curLevelPath = null; Path lastLinePath = null; boolean lastCharging = false, lastScreenOn = false, lastGpsOn = false; boolean lastWifiRunning = false, lastWakeLock = false; int lastPhoneSignalBin = 0; final int N = mNumHist; while (rec != null && i < N) { if (rec.cmd == BatteryStats.HistoryItem.CMD_UPDATE) { x = (int)(((rec.time-timeStart)*w)/timeChange); y = mLevelTop + levelh - ((rec.batteryLevel-batLow)*(levelh-1))/batChange; if (lastX != x) { // We have moved by at least a pixel. if (lastY != y) { // Don't plot changes within a pixel. Path path; byte value = rec.batteryLevel; if (value <= BATTERY_CRITICAL) path = mBatCriticalPath; else if (value <= BATTERY_WARN) path = mBatWarnPath; else path = mBatGoodPath; if (path != lastLinePath) { if (lastLinePath != null) { lastLinePath.lineTo(x, y); } path.moveTo(x, y); lastLinePath = path; } else { path.lineTo(x, y); } if (curLevelPath == null) { curLevelPath = mBatLevelPath; curLevelPath.moveTo(x, y); startX = x; } else { curLevelPath.lineTo(x, y); } lastX = x; lastY = y; } final boolean charging = (rec.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) != 0; if (charging != lastCharging) { if (charging) { mChargingPath.moveTo(x, h-mChargingOffset); } else { mChargingPath.lineTo(x, h-mChargingOffset); } lastCharging = charging; } final boolean screenOn = (rec.states&HistoryItem.STATE_SCREEN_ON_FLAG) != 0; if (screenOn != lastScreenOn) { if (screenOn) { mScreenOnPath.moveTo(x, h-mScreenOnOffset); } else { mScreenOnPath.lineTo(x, h-mScreenOnOffset); } lastScreenOn = screenOn; } final boolean gpsOn = (rec.states&HistoryItem.STATE_GPS_ON_FLAG) != 0; if (gpsOn != lastGpsOn) { if (gpsOn) { mGpsOnPath.moveTo(x, h-mGpsOnOffset); } else { mGpsOnPath.lineTo(x, h-mGpsOnOffset); } lastGpsOn = gpsOn; } final boolean wifiRunning = (rec.states&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0; if (wifiRunning != lastWifiRunning) { if (wifiRunning) { mWifiRunningPath.moveTo(x, h-mWifiRunningOffset); } else { mWifiRunningPath.lineTo(x, h-mWifiRunningOffset); } lastWifiRunning = wifiRunning; } final boolean wakeLock = (rec.states&HistoryItem.STATE_WAKE_LOCK_FLAG) != 0; if (wakeLock != lastWakeLock) { if (wakeLock) { mWakeLockPath.moveTo(x, h-mWakeLockOffset); } else { mWakeLockPath.lineTo(x, h-mWakeLockOffset); } lastWakeLock = wakeLock; } if (mLargeMode) { int bin; if (((rec.states&HistoryItem.STATE_PHONE_STATE_MASK) >> HistoryItem.STATE_PHONE_STATE_SHIFT) == ServiceState.STATE_POWER_OFF) { bin = 0; } else if ((rec.states&HistoryItem.STATE_PHONE_SCANNING_FLAG) != 0) { bin = 1; } else { bin = (rec.states&HistoryItem.STATE_SIGNAL_STRENGTH_MASK) >> HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT; bin += 2; } if (bin != lastPhoneSignalBin) { addPhoneSignalTick(x, bin); lastPhoneSignalBin = bin; } } } } else if (curLevelPath != null) { finishPaths(x+1, h, levelh, startX, lastY, curLevelPath, lastX, lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning, lastWakeLock, lastPhoneSignalBin, lastLinePath); lastX = lastY = -1; curLevelPath = null; lastLinePath = null; lastCharging = lastScreenOn = lastGpsOn = lastWakeLock = false; lastPhoneSignalBin = 0; } rec = rec.next; i++; } finishPaths(w, h, levelh, startX, lastY, curLevelPath, lastX, lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning, lastWakeLock, lastPhoneSignalBin, lastLinePath); }
protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int textHeight = mTextDescent - mTextAscent; mThinLineWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()); if (h > (textHeight*6)) { mLargeMode = true; mLineWidth = textHeight/2; mLevelTop = textHeight + mLineWidth; } else { mLargeMode = false; mLineWidth = mThinLineWidth; mLevelTop = 0; } if (mLineWidth <= 0) mLineWidth = 1; mTextPaint.setStrokeWidth(mThinLineWidth); mBatteryGoodPaint.setStrokeWidth(mThinLineWidth); mBatteryWarnPaint.setStrokeWidth(mThinLineWidth); mBatteryCriticalPaint.setStrokeWidth(mThinLineWidth); mChargingPaint.setStrokeWidth(mLineWidth); mScreenOnPaint.setStrokeWidth(mLineWidth); mGpsOnPaint.setStrokeWidth(mLineWidth); mWifiRunningPaint.setStrokeWidth(mLineWidth); mWakeLockPaint.setStrokeWidth(mLineWidth); if (mLargeMode) { int barOffset = textHeight + mLineWidth; mChargingOffset = mLineWidth; mScreenOnOffset = mChargingOffset + barOffset; mWakeLockOffset = mScreenOnOffset + barOffset; mWifiRunningOffset = mWakeLockOffset + barOffset; mGpsOnOffset = mWifiRunningOffset + (mHaveWifi ? barOffset : 0); mPhoneSignalOffset = mGpsOnOffset + (mHaveGps ? barOffset : 0); mLevelOffset = mPhoneSignalOffset + barOffset + mLineWidth; mPhoneSignalTicks = new int[w+2]; } else { mScreenOnOffset = mGpsOnOffset = mWifiRunningOffset = mWakeLockOffset = mLineWidth; mChargingOffset = mLineWidth*2; mPhoneSignalOffset = 0; mLevelOffset = mLineWidth*3; mPhoneSignalTicks = null; } mBatLevelPath.reset(); mBatGoodPath.reset(); mBatWarnPath.reset(); mBatCriticalPath.reset(); mScreenOnPath.reset(); mGpsOnPath.reset(); mWifiRunningPath.reset(); mWakeLockPath.reset(); mChargingPath.reset(); final long timeStart = mHistStart; final long timeChange = mHistEnd-mHistStart; final int batLow = mBatLow; final int batChange = mBatHigh-mBatLow; final int levelh = h - mLevelOffset - mLevelTop; mLevelBottom = mLevelTop + levelh; BatteryStats.HistoryItem rec = mHistFirst; int x = 0, y = 0, startX = 0, lastX = -1, lastY = -1; int i = 0; Path curLevelPath = null; Path lastLinePath = null; boolean lastCharging = false, lastScreenOn = false, lastGpsOn = false; boolean lastWifiRunning = false, lastWakeLock = false; int lastPhoneSignalBin = 0; final int N = mNumHist; while (rec != null && i < N) { if (rec.cmd == BatteryStats.HistoryItem.CMD_UPDATE) { x = (int)(((rec.time-timeStart)*w)/timeChange); y = mLevelTop + levelh - ((rec.batteryLevel-batLow)*(levelh-1))/batChange; if (lastX != x) { // We have moved by at least a pixel. if (lastY != y) { // Don't plot changes within a pixel. Path path; byte value = rec.batteryLevel; if (value <= BATTERY_CRITICAL) path = mBatCriticalPath; else if (value <= BATTERY_WARN) path = mBatWarnPath; else path = mBatGoodPath; if (path != lastLinePath) { if (lastLinePath != null) { lastLinePath.lineTo(x, y); } path.moveTo(x, y); lastLinePath = path; } else { path.lineTo(x, y); } if (curLevelPath == null) { curLevelPath = mBatLevelPath; curLevelPath.moveTo(x, y); startX = x; } else { curLevelPath.lineTo(x, y); } lastX = x; lastY = y; } final boolean charging = (rec.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) != 0; if (charging != lastCharging) { if (charging) { mChargingPath.moveTo(x, h-mChargingOffset); } else { mChargingPath.lineTo(x, h-mChargingOffset); } lastCharging = charging; } final boolean screenOn = (rec.states&HistoryItem.STATE_SCREEN_ON_FLAG) != 0; if (screenOn != lastScreenOn) { if (screenOn) { mScreenOnPath.moveTo(x, h-mScreenOnOffset); } else { mScreenOnPath.lineTo(x, h-mScreenOnOffset); } lastScreenOn = screenOn; } final boolean gpsOn = (rec.states&HistoryItem.STATE_GPS_ON_FLAG) != 0; if (gpsOn != lastGpsOn) { if (gpsOn) { mGpsOnPath.moveTo(x, h-mGpsOnOffset); } else { mGpsOnPath.lineTo(x, h-mGpsOnOffset); } lastGpsOn = gpsOn; } final boolean wifiRunning = (rec.states&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0; if (wifiRunning != lastWifiRunning) { if (wifiRunning) { mWifiRunningPath.moveTo(x, h-mWifiRunningOffset); } else { mWifiRunningPath.lineTo(x, h-mWifiRunningOffset); } lastWifiRunning = wifiRunning; } final boolean wakeLock = (rec.states&HistoryItem.STATE_WAKE_LOCK_FLAG) != 0; if (wakeLock != lastWakeLock) { if (wakeLock) { mWakeLockPath.moveTo(x, h-mWakeLockOffset); } else { mWakeLockPath.lineTo(x, h-mWakeLockOffset); } lastWakeLock = wakeLock; } if (mLargeMode) { int bin; if (((rec.states&HistoryItem.STATE_PHONE_STATE_MASK) >> HistoryItem.STATE_PHONE_STATE_SHIFT) == ServiceState.STATE_POWER_OFF) { bin = 0; } else if ((rec.states&HistoryItem.STATE_PHONE_SCANNING_FLAG) != 0) { bin = 1; } else { bin = (rec.states&HistoryItem.STATE_SIGNAL_STRENGTH_MASK) >> HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT; bin += 2; } if (bin != lastPhoneSignalBin) { addPhoneSignalTick(x, bin); lastPhoneSignalBin = bin; } } } } else if (curLevelPath != null) { finishPaths(x+1, h, levelh, startX, lastY, curLevelPath, lastX, lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning, lastWakeLock, lastPhoneSignalBin, lastLinePath); lastX = lastY = -1; curLevelPath = null; lastLinePath = null; lastCharging = lastScreenOn = lastGpsOn = lastWakeLock = false; lastPhoneSignalBin = 0; } rec = rec.next; i++; } finishPaths(w, h, levelh, startX, lastY, curLevelPath, lastX, lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning, lastWakeLock, lastPhoneSignalBin, lastLinePath); }
diff --git a/src/com/android/Oasis/diary/OldDiary.java b/src/com/android/Oasis/diary/OldDiary.java index ee99b84..fec8a5e 100644 --- a/src/com/android/Oasis/diary/OldDiary.java +++ b/src/com/android/Oasis/diary/OldDiary.java @@ -1,579 +1,580 @@ package com.android.Oasis.diary; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ScrollView; import android.widget.TextView; import com.android.Oasis.Main; import com.android.Oasis.MySQLite; import com.android.Oasis.R; import com.android.Oasis.life.Life; import com.android.Oasis.recent.Recent; import com.android.Oasis.story.Story; public class OldDiary extends Activity { ArrayList<HashMap<String, Object>> array = new ArrayList<HashMap<String, Object>>(); int PLANT = 0; final int TAKE_PICTURE = 12345; final int SELECT_PICTURE = 54321; private Uri imageUri = null; private File tmpPhoto; private Uri pictureUri = null; boolean isFromAlbum = false; private ViewPager viewPager; private Context cxt; private pagerAdapter pageradapter; Intent intent = new Intent(); Bundle bundle = new Bundle(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.olddiary); cxt = this; bundle = this.getIntent().getExtras(); PLANT = bundle.getInt("plant"); loadFromDb(); pageradapter = new pagerAdapter(); viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setAdapter(pageradapter); ImageButton btn_new = (ImageButton) findViewById(R.id.diary_btn_new); btn_new.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { registerForContextMenu(arg0); openContextMenu(arg0); } }); ImageButton btn_story = (ImageButton) findViewById(R.id.main_btn_story); btn_story.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { intent.putExtras(bundle); intent.setClass(OldDiary.this, Story.class); startActivity(intent); System.gc(); OldDiary.this.finish(); } }); ImageButton btn_recent = (ImageButton) findViewById(R.id.main_btn_recent); btn_recent.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { intent.putExtras(bundle); intent.setClass(OldDiary.this, Recent.class); startActivity(intent); System.gc(); OldDiary.this.finish(); } }); ImageButton btn_life = (ImageButton) findViewById(R.id.main_btn_life); btn_life.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse(OldDiary.this.getResources().getString(R.string.fb_url)); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { View view = LayoutInflater.from(v.getContext()).inflate( R.layout.ui_contextmenu_header, null); TextView txt_header = (TextView) view .findViewById(R.id.ui_contextmenu_headertextview); txt_header.setText("新增日記相片"); menu.setHeaderView(view); menu.add(0, 0, 0, "從相簿"); menu.add(0, 1, 1, "從相機"); super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { imageUri = null; if (item.getItemId() == 0) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, SELECT_PICTURE); } else if (item.getItemId() == 1) { Intent intent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); tmpPhoto = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".png"); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(tmpPhoto)); imageUri = Uri.fromFile(tmpPhoto); startActivityForResult(intent, TAKE_PICTURE); } return super.onContextItemSelected(item); } protected void makeDuplicatePicture(Uri originalUri) throws IOException, URISyntaxException { File cacheDir = getCacheDir(); // get cache dir File picture = new File(cacheDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".png"); // new file InputStream is = this.getContentResolver().openInputStream(originalUri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeStream(is, null, options); int mySize = 800; if (options.outWidth <= mySize) options.inSampleSize = 1; else if (options.outWidth <= 2 * mySize) options.inSampleSize = 2; else if (options.outWidth <= 4 * mySize) options.inSampleSize = 4; else options.inSampleSize = 8; is = this.getContentResolver().openInputStream(originalUri); options.inJustDecodeBounds = false; bmp = BitmapFactory.decodeStream(is, null, options); // if (picture.exists()) { // delete old file in cache // picture.delete(); // } FileOutputStream fos = new FileOutputStream(picture); bmp.compress(Bitmap.CompressFormat.JPEG, 85, fos); bmp.recycle(); is.close(); fos.close(); pictureUri = Uri.fromFile(picture); /* * if (isFromAlbum == false) { * android.provider.MediaStore.Images.Media.insertImage( * getContentResolver(), bmp, "", ""); * * sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, * Uri.parse("file://" + Environment.getExternalStorageDirectory()))); } */ } void check() { if (pictureUri != null) { // Bundle bundle = new Bundle(); String tmp = pictureUri.toString(); bundle.putString("uri", tmp); bundle.putInt("plant", PLANT); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(OldDiary.this, NewDiary.class); startActivity(intent); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PICTURE: if (resultCode == Activity.RESULT_OK) { Uri selectedImage = imageUri; getContentResolver().notifyChange(selectedImage, null); isFromAlbum = false; System.gc(); // run gc for sure that there's enough memory try { if (tmpPhoto.length() > 0l) { pictureUri = imageUri; makeDuplicatePicture(imageUri); tmpPhoto.delete(); System.gc(); } else { makeDuplicatePicture(data.getData()); System.gc(); } } catch (Exception e) { // Toast.makeText(this, R.string.toast_failedtoload, // Toast.LENGTH_SHORT).show(); } } check(); break; case SELECT_PICTURE: if (resultCode == Activity.RESULT_OK) { isFromAlbum = true; System.gc(); // run gc for sure that there's enough memory try { makeDuplicatePicture(data.getData()); System.gc(); } catch (IOException e) { break; } catch (URISyntaxException e) { break; } } check(); break; case 1: // startActivity(intent); break; default: super.onActivityResult(requestCode, resultCode, data); } } private class pagerAdapter extends PagerAdapter { @Override public int getCount() { // return NUM_VIEWS; return (int) Math.ceil((double) array.size() / 8.0); } /** * Create the page for the given position. The adapter is responsible * for adding the view to the container given here, although it only * must ensure this is done by the time it returns from * {@link #finishUpdate()}. * * @param container * The containing View in which the page will be shown. * @param position * The page position to be instantiated. * @return Returns an Object representing the new page. This does not * need to be a View, but can be some other container of the * page. */ @Override public Object instantiateItem(View collection, int position) { DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); // int height = displaymetrics.heightPixels; int width = displaymetrics.widthPixels; ScrollView sv = new ScrollView(cxt); LinearLayout ll = new LinearLayout(cxt); ll.setOrientation(LinearLayout.VERTICAL); + ll.removeAllViews(); ImageView iv1 = new ImageView(cxt); ImageView iv2 = new ImageView(cxt); iv1.setImageDrawable(OldDiary.this.getResources().getDrawable( R.drawable.diary_rope_top)); iv2.setImageDrawable(OldDiary.this.getResources().getDrawable( R.drawable.diary_rope_bottom)); ll.addView(iv1); int i; LinearLayout photoropeup = new LinearLayout(cxt); LinearLayout photodateup = new LinearLayout(cxt); // photoropeup.setGravity(Gravity.CENTER_HORIZONTAL); LinearLayout photoropebottom = new LinearLayout(cxt); LinearLayout photodatebottom = new LinearLayout(cxt); // photoropebottom.setGravity(Gravity.CENTER_HORIZONTAL); int padding = 8; if (width > 490) { padding = (width - 480) / 5; } for (i = 0; i < 4; i++) { Log.wtf("jizz", "i have big belly!"); if (position * 8 + i >= array.size()) break; HashMap<String, Object> map = new HashMap<String, Object>(); map = array.get(position * 8 + i); final Uri uri = Uri.parse(map.get("path").toString()); Uri uri_t = Uri.parse(map.get("thumb").toString()); Bitmap img = null; ContentResolver vContentResolver = getContentResolver(); try { img = BitmapFactory.decodeStream(vContentResolver .openInputStream(uri_t)); } catch (FileNotFoundException e) { e.printStackTrace(); } ImageView myImageView = new ImageView(cxt); myImageView.setImageBitmap(img); // img.recycle(); myImageView.setAdjustViewBounds(true); myImageView.setScaleType(ScaleType.CENTER_INSIDE); myImageView.setMaxWidth(width / 4 - 10); myImageView.setPadding(padding / 2, 0, padding / 2, 0); TextView myTextView = new TextView(cxt); myTextView.setText(map.get("date").toString()); myTextView.setTextColor(Color.BLACK); myTextView.setTextSize(13); myTextView.setGravity(Gravity.CENTER_HORIZONTAL); myTextView.setWidth(width / 4 - 10); myTextView.setPadding(padding / 2, 0, padding / 2, 0); final int id = Integer.parseInt(map.get("db_id").toString()); myImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Bundle bundle = new Bundle(); bundle.putBoolean("ismine", true); bundle.putString("path", uri.toString()); bundle.putInt("db_id", id); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(OldDiary.this, BrowseDiary.class); System.gc(); startActivity(intent); } }); photoropeup.addView(myImageView); photodateup.addView(myTextView); } if (i == 4) { photoropeup.setGravity(Gravity.CENTER_HORIZONTAL); photodateup.setGravity(Gravity.CENTER_HORIZONTAL); } else { photoropeup.setPadding(padding, 0, padding, 0); photodateup.setPadding(padding, 0, padding, 0); } for (i = 4; i < 8; i++) { if (position * 8 + i >= array.size()) break; HashMap<String, Object> map = new HashMap<String, Object>(); map = array.get(position * 8 + i); final Uri uri = Uri.parse(map.get("path").toString()); Uri uri_t = Uri.parse(map.get("thumb").toString()); Bitmap img = null; ContentResolver vContentResolver = getContentResolver(); try { img = BitmapFactory.decodeStream(vContentResolver .openInputStream(uri_t)); } catch (FileNotFoundException e) { e.printStackTrace(); } ImageView myImageView = new ImageView(cxt); myImageView.setImageBitmap(img); // img.recycle(); myImageView.setAdjustViewBounds(true); myImageView.setScaleType(ScaleType.CENTER_INSIDE); myImageView.setMaxWidth(width / 4 - 10); myImageView.setPadding(padding / 2, 0, padding / 2, 0); TextView myTextView = new TextView(cxt); myTextView.setText(map.get("date").toString()); myTextView.setTextColor(Color.BLACK); myTextView.setTextSize(13); myTextView.setGravity(Gravity.CENTER_HORIZONTAL); myTextView.setWidth(width / 4 - 10); myTextView.setPadding(padding / 2, 0, padding / 2, 0); final int id = Integer.parseInt(map.get("db_id").toString()); myImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Bundle bundle = new Bundle(); bundle.putBoolean("ismine", true); bundle.putString("path", uri.toString()); bundle.putInt("db_id", id); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(OldDiary.this, BrowseDiary.class); System.gc(); startActivity(intent); } }); photoropebottom.addView(myImageView); photodatebottom.addView(myTextView); } if (i == 8) { photoropebottom.setGravity(Gravity.CENTER_HORIZONTAL); photodatebottom.setGravity(Gravity.CENTER_HORIZONTAL); } else { photoropebottom.setPadding(padding, 0, padding, 0); photodatebottom.setPadding(padding, 0, padding, 0); } // if(photoropeup.getChildCount()<4) // ll.setGravity(Gravity.LEFT); // if(photoropebottom.getChildCount()<4) // ll.setGravity(Gravity.LEFT); ll.addView(photoropeup); ll.addView(photodateup); ll.addView(iv2); ll.addView(photoropebottom); ll.addView(photodatebottom); sv.addView(ll); ((ViewPager) collection).addView(sv, 0); // ((ViewPager) collection).addView(ll, 0); return sv; } /** * Remove a page for the given position. The adapter is responsible for * removing the view from its container, although it only must ensure * this is done by the time it returns from {@link #finishUpdate()}. * * @param container * The containing View from which the page will be removed. * @param position * The page position to be removed. * @param object * The same object that was returned by * {@link #instantiateItem(View, int)}. */ @Override public void destroyItem(View collection, int position, Object view) { ((ViewPager) collection).removeView((ScrollView) view); } @Override public boolean isViewFromObject(View view, Object object) { return view == ((ScrollView) object); } /** * Called when the a change in the shown pages has been completed. At * this point you must ensure that all of the pages have actually been * added or removed from the container as appropriate. * * @param container * The containing View which is displaying this adapter's * page views. */ @Override public void finishUpdate(View arg0) { } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } @Override public void startUpdate(View arg0) { } } private void loadFromDb() { array.clear(); int db_id = 0; int plant = 0; String path = ""; String date = ""; String thumb = ""; String content =""; MySQLite db = new MySQLite(OldDiary.this); Cursor cursor = db.getPlant(PLANT); int rows_num = cursor.getCount(); // cursor.moveToFirst(); cursor.moveToLast(); for (int i = 0; i < rows_num; i++) { db_id = cursor.getInt(0); plant = cursor.getInt(1); path = cursor.getString(2); date = cursor.getString(3); thumb = cursor.getString(4); content = cursor.getString(5); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("db_id", db_id); map.put("plant", plant); map.put("path", path); map.put("date", date); map.put("thumb", thumb); array.add(map); cursor.moveToPrevious(); } cursor.close(); db.close(); } @Override protected void onResume() { super.onResume(); loadFromDb(); pageradapter = new pagerAdapter(); viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setAdapter(pageradapter); } }
true
true
public Object instantiateItem(View collection, int position) { DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); // int height = displaymetrics.heightPixels; int width = displaymetrics.widthPixels; ScrollView sv = new ScrollView(cxt); LinearLayout ll = new LinearLayout(cxt); ll.setOrientation(LinearLayout.VERTICAL); ImageView iv1 = new ImageView(cxt); ImageView iv2 = new ImageView(cxt); iv1.setImageDrawable(OldDiary.this.getResources().getDrawable( R.drawable.diary_rope_top)); iv2.setImageDrawable(OldDiary.this.getResources().getDrawable( R.drawable.diary_rope_bottom)); ll.addView(iv1); int i; LinearLayout photoropeup = new LinearLayout(cxt); LinearLayout photodateup = new LinearLayout(cxt); // photoropeup.setGravity(Gravity.CENTER_HORIZONTAL); LinearLayout photoropebottom = new LinearLayout(cxt); LinearLayout photodatebottom = new LinearLayout(cxt); // photoropebottom.setGravity(Gravity.CENTER_HORIZONTAL); int padding = 8; if (width > 490) { padding = (width - 480) / 5; } for (i = 0; i < 4; i++) { Log.wtf("jizz", "i have big belly!"); if (position * 8 + i >= array.size()) break; HashMap<String, Object> map = new HashMap<String, Object>(); map = array.get(position * 8 + i); final Uri uri = Uri.parse(map.get("path").toString()); Uri uri_t = Uri.parse(map.get("thumb").toString()); Bitmap img = null; ContentResolver vContentResolver = getContentResolver(); try { img = BitmapFactory.decodeStream(vContentResolver .openInputStream(uri_t)); } catch (FileNotFoundException e) { e.printStackTrace(); } ImageView myImageView = new ImageView(cxt); myImageView.setImageBitmap(img); // img.recycle(); myImageView.setAdjustViewBounds(true); myImageView.setScaleType(ScaleType.CENTER_INSIDE); myImageView.setMaxWidth(width / 4 - 10); myImageView.setPadding(padding / 2, 0, padding / 2, 0); TextView myTextView = new TextView(cxt); myTextView.setText(map.get("date").toString()); myTextView.setTextColor(Color.BLACK); myTextView.setTextSize(13); myTextView.setGravity(Gravity.CENTER_HORIZONTAL); myTextView.setWidth(width / 4 - 10); myTextView.setPadding(padding / 2, 0, padding / 2, 0); final int id = Integer.parseInt(map.get("db_id").toString()); myImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Bundle bundle = new Bundle(); bundle.putBoolean("ismine", true); bundle.putString("path", uri.toString()); bundle.putInt("db_id", id); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(OldDiary.this, BrowseDiary.class); System.gc(); startActivity(intent); } }); photoropeup.addView(myImageView); photodateup.addView(myTextView); } if (i == 4) { photoropeup.setGravity(Gravity.CENTER_HORIZONTAL); photodateup.setGravity(Gravity.CENTER_HORIZONTAL); } else { photoropeup.setPadding(padding, 0, padding, 0); photodateup.setPadding(padding, 0, padding, 0); } for (i = 4; i < 8; i++) { if (position * 8 + i >= array.size()) break; HashMap<String, Object> map = new HashMap<String, Object>(); map = array.get(position * 8 + i); final Uri uri = Uri.parse(map.get("path").toString()); Uri uri_t = Uri.parse(map.get("thumb").toString()); Bitmap img = null; ContentResolver vContentResolver = getContentResolver(); try { img = BitmapFactory.decodeStream(vContentResolver .openInputStream(uri_t)); } catch (FileNotFoundException e) { e.printStackTrace(); } ImageView myImageView = new ImageView(cxt); myImageView.setImageBitmap(img); // img.recycle(); myImageView.setAdjustViewBounds(true); myImageView.setScaleType(ScaleType.CENTER_INSIDE); myImageView.setMaxWidth(width / 4 - 10); myImageView.setPadding(padding / 2, 0, padding / 2, 0); TextView myTextView = new TextView(cxt); myTextView.setText(map.get("date").toString()); myTextView.setTextColor(Color.BLACK); myTextView.setTextSize(13); myTextView.setGravity(Gravity.CENTER_HORIZONTAL); myTextView.setWidth(width / 4 - 10); myTextView.setPadding(padding / 2, 0, padding / 2, 0); final int id = Integer.parseInt(map.get("db_id").toString()); myImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Bundle bundle = new Bundle(); bundle.putBoolean("ismine", true); bundle.putString("path", uri.toString()); bundle.putInt("db_id", id); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(OldDiary.this, BrowseDiary.class); System.gc(); startActivity(intent); } }); photoropebottom.addView(myImageView); photodatebottom.addView(myTextView); } if (i == 8) { photoropebottom.setGravity(Gravity.CENTER_HORIZONTAL); photodatebottom.setGravity(Gravity.CENTER_HORIZONTAL); } else { photoropebottom.setPadding(padding, 0, padding, 0); photodatebottom.setPadding(padding, 0, padding, 0); } // if(photoropeup.getChildCount()<4) // ll.setGravity(Gravity.LEFT); // if(photoropebottom.getChildCount()<4) // ll.setGravity(Gravity.LEFT); ll.addView(photoropeup); ll.addView(photodateup); ll.addView(iv2); ll.addView(photoropebottom); ll.addView(photodatebottom); sv.addView(ll); ((ViewPager) collection).addView(sv, 0); // ((ViewPager) collection).addView(ll, 0); return sv; }
public Object instantiateItem(View collection, int position) { DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); // int height = displaymetrics.heightPixels; int width = displaymetrics.widthPixels; ScrollView sv = new ScrollView(cxt); LinearLayout ll = new LinearLayout(cxt); ll.setOrientation(LinearLayout.VERTICAL); ll.removeAllViews(); ImageView iv1 = new ImageView(cxt); ImageView iv2 = new ImageView(cxt); iv1.setImageDrawable(OldDiary.this.getResources().getDrawable( R.drawable.diary_rope_top)); iv2.setImageDrawable(OldDiary.this.getResources().getDrawable( R.drawable.diary_rope_bottom)); ll.addView(iv1); int i; LinearLayout photoropeup = new LinearLayout(cxt); LinearLayout photodateup = new LinearLayout(cxt); // photoropeup.setGravity(Gravity.CENTER_HORIZONTAL); LinearLayout photoropebottom = new LinearLayout(cxt); LinearLayout photodatebottom = new LinearLayout(cxt); // photoropebottom.setGravity(Gravity.CENTER_HORIZONTAL); int padding = 8; if (width > 490) { padding = (width - 480) / 5; } for (i = 0; i < 4; i++) { Log.wtf("jizz", "i have big belly!"); if (position * 8 + i >= array.size()) break; HashMap<String, Object> map = new HashMap<String, Object>(); map = array.get(position * 8 + i); final Uri uri = Uri.parse(map.get("path").toString()); Uri uri_t = Uri.parse(map.get("thumb").toString()); Bitmap img = null; ContentResolver vContentResolver = getContentResolver(); try { img = BitmapFactory.decodeStream(vContentResolver .openInputStream(uri_t)); } catch (FileNotFoundException e) { e.printStackTrace(); } ImageView myImageView = new ImageView(cxt); myImageView.setImageBitmap(img); // img.recycle(); myImageView.setAdjustViewBounds(true); myImageView.setScaleType(ScaleType.CENTER_INSIDE); myImageView.setMaxWidth(width / 4 - 10); myImageView.setPadding(padding / 2, 0, padding / 2, 0); TextView myTextView = new TextView(cxt); myTextView.setText(map.get("date").toString()); myTextView.setTextColor(Color.BLACK); myTextView.setTextSize(13); myTextView.setGravity(Gravity.CENTER_HORIZONTAL); myTextView.setWidth(width / 4 - 10); myTextView.setPadding(padding / 2, 0, padding / 2, 0); final int id = Integer.parseInt(map.get("db_id").toString()); myImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Bundle bundle = new Bundle(); bundle.putBoolean("ismine", true); bundle.putString("path", uri.toString()); bundle.putInt("db_id", id); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(OldDiary.this, BrowseDiary.class); System.gc(); startActivity(intent); } }); photoropeup.addView(myImageView); photodateup.addView(myTextView); } if (i == 4) { photoropeup.setGravity(Gravity.CENTER_HORIZONTAL); photodateup.setGravity(Gravity.CENTER_HORIZONTAL); } else { photoropeup.setPadding(padding, 0, padding, 0); photodateup.setPadding(padding, 0, padding, 0); } for (i = 4; i < 8; i++) { if (position * 8 + i >= array.size()) break; HashMap<String, Object> map = new HashMap<String, Object>(); map = array.get(position * 8 + i); final Uri uri = Uri.parse(map.get("path").toString()); Uri uri_t = Uri.parse(map.get("thumb").toString()); Bitmap img = null; ContentResolver vContentResolver = getContentResolver(); try { img = BitmapFactory.decodeStream(vContentResolver .openInputStream(uri_t)); } catch (FileNotFoundException e) { e.printStackTrace(); } ImageView myImageView = new ImageView(cxt); myImageView.setImageBitmap(img); // img.recycle(); myImageView.setAdjustViewBounds(true); myImageView.setScaleType(ScaleType.CENTER_INSIDE); myImageView.setMaxWidth(width / 4 - 10); myImageView.setPadding(padding / 2, 0, padding / 2, 0); TextView myTextView = new TextView(cxt); myTextView.setText(map.get("date").toString()); myTextView.setTextColor(Color.BLACK); myTextView.setTextSize(13); myTextView.setGravity(Gravity.CENTER_HORIZONTAL); myTextView.setWidth(width / 4 - 10); myTextView.setPadding(padding / 2, 0, padding / 2, 0); final int id = Integer.parseInt(map.get("db_id").toString()); myImageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Bundle bundle = new Bundle(); bundle.putBoolean("ismine", true); bundle.putString("path", uri.toString()); bundle.putInt("db_id", id); Intent intent = new Intent(); intent.putExtras(bundle); intent.setClass(OldDiary.this, BrowseDiary.class); System.gc(); startActivity(intent); } }); photoropebottom.addView(myImageView); photodatebottom.addView(myTextView); } if (i == 8) { photoropebottom.setGravity(Gravity.CENTER_HORIZONTAL); photodatebottom.setGravity(Gravity.CENTER_HORIZONTAL); } else { photoropebottom.setPadding(padding, 0, padding, 0); photodatebottom.setPadding(padding, 0, padding, 0); } // if(photoropeup.getChildCount()<4) // ll.setGravity(Gravity.LEFT); // if(photoropebottom.getChildCount()<4) // ll.setGravity(Gravity.LEFT); ll.addView(photoropeup); ll.addView(photodateup); ll.addView(iv2); ll.addView(photoropebottom); ll.addView(photodatebottom); sv.addView(ll); ((ViewPager) collection).addView(sv, 0); // ((ViewPager) collection).addView(ll, 0); return sv; }
diff --git a/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlayerConnection.java b/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlayerConnection.java index c6dac18..c7e9581 100644 --- a/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlayerConnection.java +++ b/src/main/java/com/bergerkiller/bukkit/common/internal/CommonPlayerConnection.java @@ -1,526 +1,526 @@ package com.bergerkiller.bukkit.common.internal; import java.util.List; import java.util.ListIterator; import java.util.logging.Level; import org.bukkit.entity.Player; import com.bergerkiller.bukkit.common.Task; import com.bergerkiller.bukkit.common.reflection.SafeField; import com.bergerkiller.bukkit.common.reflection.classes.PlayerConnectionRef; import com.bergerkiller.bukkit.common.utils.CommonUtil; import net.minecraft.server.v1_5_R2.*; /** * Used (when ProtocolLib is not enabled) to intercept and keep track of packets */ class CommonPlayerConnection extends PlayerConnection { private static final List<PlayerConnection> serverPlayerConnections = SafeField.get(CommonUtil.getMCServer().ae(), "c"); private final PlayerConnection previous; private final CommonPacketHandler handler; private CommonPlayerConnection(MinecraftServer minecraftserver, EntityPlayer entityplayer) { super(minecraftserver, entityplayer.playerConnection.networkManager, entityplayer); previous = entityplayer.playerConnection; handler = (CommonPacketHandler) CommonPlugin.getInstance().getPacketHandler(); PlayerConnectionRef.TEMPLATE.transfer(previous, this); } public static void bindAll() { for (Player player : CommonUtil.getOnlinePlayers()) { bind(player); } } public static void unbindAll() { for (Player player : CommonUtil.getOnlinePlayers()) { unbind(player); } } private static boolean isReplaceable(Object playerConnection) { return playerConnection instanceof CommonPlayerConnection || playerConnection.getClass() == PlayerConnection.class; } private static void setPlayerConnection(final EntityPlayer ep, final PlayerConnection connection) { - final boolean hasCommon = CommonPlugin.getInstance() != null; + final boolean hasCommon = CommonPlugin.hasInstance(); if (isReplaceable(ep.playerConnection)) { // Set it ep.playerConnection = connection; // Perform a little check-up in 10 ticks - if (CommonPlugin.getInstance() != null) { + if (CommonPlugin.hasInstance()) { new Task(CommonPlugin.getInstance()) { @Override public void run() { if (hasCommon && ep.playerConnection != connection) { // Player connection has changed! CommonPlugin.getInstance().failPacketListener(ep.playerConnection.getClass()); } } }.start(10); } } else if (hasCommon) { // Plugin conflict! CommonPlugin.getInstance().failPacketListener(ep.playerConnection.getClass()); return; } registerPlayerConnection(ep, connection, true); } private static void registerPlayerConnection(final EntityPlayer ep, final PlayerConnection connection, boolean retry) { synchronized (serverPlayerConnections) { // Replace existing ListIterator<PlayerConnection> iter = serverPlayerConnections.listIterator(); while (iter.hasNext()) { if (iter.next().player == ep) { iter.set(connection); return; } } if (!retry) { CommonPlugin.LOGGER.log(Level.SEVERE, "Failed to (un)register PlayerConnection proxy...bad things may happen!"); return; } // We failed to remove it in one go... // Remove the old one the next tick but then fail CommonUtil.nextTick(new Runnable() { public void run() { registerPlayerConnection(ep, connection, false); } }); } } public static void bind(Player player) { final EntityPlayer ep = CommonNMS.getNative(player); if (ep.playerConnection instanceof CommonPlayerConnection) { return; } setPlayerConnection(ep, new CommonPlayerConnection(CommonUtil.getMCServer(), ep)); } public static void unbind(Player player) { final EntityPlayer ep = CommonNMS.getNative(player); final PlayerConnection previous = ep.playerConnection; if (previous instanceof CommonPlayerConnection) { PlayerConnection replacement = ((CommonPlayerConnection) previous).previous; PlayerConnectionRef.TEMPLATE.transfer(previous, replacement); setPlayerConnection(ep, replacement); } } @Override public void a(Packet0KeepAlive packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet100OpenWindow packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet102WindowClick packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet103SetSlot packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet104WindowItems packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet105CraftProgressBar packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet106Transaction packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet107SetCreativeSlot packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet108ButtonClick packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet10Flying packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet130UpdateSign packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet131ItemData packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet132TileEntityData packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet14BlockDig packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet15Place packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet16BlockItemSwitch packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet17EntityLocationAction packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet18ArmAnimation packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet19EntityAction packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet1Login packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet200Statistic packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet201PlayerInfo packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet202Abilities packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet203TabComplete packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet204LocaleAndViewDistance packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet205ClientCommand packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet20NamedEntitySpawn packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet22Collect packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet23VehicleSpawn packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet24MobSpawn packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet250CustomPayload packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet252KeyResponse packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet253KeyRequest packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet254GetInfo packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet255KickDisconnect packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet25EntityPainting packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet26AddExpOrb packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet28EntityVelocity packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet29DestroyEntity packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet2Handshake packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet30Entity packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet34EntityTeleport packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet35EntityHeadRotation packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet38EntityStatus packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet39AttachEntity packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet3Chat packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet40EntityMetadata packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet41MobEffect packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet42RemoveMobEffect packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet43SetExperience packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet4UpdateTime packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet51MapChunk packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet52MultiBlockChange packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet53BlockChange packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet54PlayNoteBlock packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet55BlockBreakAnimation packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet56MapChunkBulk packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet5EntityEquipment packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet60Explosion packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet61WorldEvent packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet62NamedSoundEffect packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet6SpawnPosition packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet70Bed packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet71Weather packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet7UseEntity packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet8UpdateHealth packet) { if(this.canConfirm(packet)) super.a(packet); } @Override public void a(Packet9Respawn packet) { if(this.canConfirm(packet)) super.a(packet); } private boolean canConfirm(Packet packet) { return handler.onPacketReceive(CommonNMS.getPlayer(this.player), packet, false); } @Override public void sendPacket(Packet packet) { if (handler.onPacketSend(CommonNMS.getPlayer(this.player), packet, false)) { super.sendPacket(packet); } } }
false
true
private static void setPlayerConnection(final EntityPlayer ep, final PlayerConnection connection) { final boolean hasCommon = CommonPlugin.getInstance() != null; if (isReplaceable(ep.playerConnection)) { // Set it ep.playerConnection = connection; // Perform a little check-up in 10 ticks if (CommonPlugin.getInstance() != null) { new Task(CommonPlugin.getInstance()) { @Override public void run() { if (hasCommon && ep.playerConnection != connection) { // Player connection has changed! CommonPlugin.getInstance().failPacketListener(ep.playerConnection.getClass()); } } }.start(10); } } else if (hasCommon) { // Plugin conflict! CommonPlugin.getInstance().failPacketListener(ep.playerConnection.getClass()); return; } registerPlayerConnection(ep, connection, true); }
private static void setPlayerConnection(final EntityPlayer ep, final PlayerConnection connection) { final boolean hasCommon = CommonPlugin.hasInstance(); if (isReplaceable(ep.playerConnection)) { // Set it ep.playerConnection = connection; // Perform a little check-up in 10 ticks if (CommonPlugin.hasInstance()) { new Task(CommonPlugin.getInstance()) { @Override public void run() { if (hasCommon && ep.playerConnection != connection) { // Player connection has changed! CommonPlugin.getInstance().failPacketListener(ep.playerConnection.getClass()); } } }.start(10); } } else if (hasCommon) { // Plugin conflict! CommonPlugin.getInstance().failPacketListener(ep.playerConnection.getClass()); return; } registerPlayerConnection(ep, connection, true); }
diff --git a/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/runtime/server/polling/TwiddlePoller.java b/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/runtime/server/polling/TwiddlePoller.java index 50d8c5d45..88533bcce 100755 --- a/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/runtime/server/polling/TwiddlePoller.java +++ b/as/plugins/org.jboss.ide.eclipse.as.core/jbosscore/org/jboss/ide/eclipse/as/core/runtime/server/polling/TwiddlePoller.java @@ -1,243 +1,244 @@ /** * JBoss, a Division of Red Hat * Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.ide.eclipse.as.core.runtime.server.polling; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.security.Principal; import java.util.Date; import java.util.Properties; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.naming.InitialContext; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.wst.server.core.IRuntime; import org.eclipse.wst.server.core.IServer; import org.jboss.ide.eclipse.as.core.model.DescriptorModel; import org.jboss.ide.eclipse.as.core.model.EventLogModel; import org.jboss.ide.eclipse.as.core.model.DescriptorModel.ServerDescriptorModel; import org.jboss.ide.eclipse.as.core.model.EventLogModel.EventLogTreeItem; import org.jboss.ide.eclipse.as.core.runtime.server.IServerStatePoller; import org.jboss.ide.eclipse.as.core.server.JBossServerLaunchConfiguration; import org.jboss.ide.eclipse.as.core.server.TwiddleLauncher; import org.jboss.ide.eclipse.as.core.util.ArgsUtil; import org.jboss.ide.eclipse.as.core.util.ServerConverter; import org.jboss.ide.eclipse.as.core.util.SimpleTreeItem; public class TwiddlePoller implements IServerStatePoller { public static final String STATUS = "org.jboss.ide.eclipse.as.core.runtime.server.internal.TwiddlePoller.status"; public static final String TYPE_TERMINATED = "org.jboss.ide.eclipse.as.core.runtime.server.internal.TwiddlePoller.TYPE_TERMINATED"; public static final String TYPE_RESULT = "org.jboss.ide.eclipse.as.core.runtime.server.internal.TwiddlePoller.TYPE_RESULT"; public static final int STATE_STARTED = 1; public static final int STATE_STOPPED = 0; public static final int STATE_TRANSITION = -1; private boolean expectedState; private int started; private boolean canceled; private boolean done; private IServer server; private PollingException pollingException = null; private EventLogTreeItem event; public void beginPolling(IServer server, boolean expectedState, PollThread pt) { this.expectedState = expectedState; this.canceled = false; this.done = false; this.server = server; event = pt.getActiveEvent(); launchTwiddlePoller(); } private class PollerRunnable implements Runnable { private TwiddleLauncher launcher; public void run() { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); ClassLoader twiddleLoader = getClassLoader(); if( twiddleLoader != null ) { String serverConfDir = ServerConverter.getJBossServer(server).getConfigDirectory(false); ServerDescriptorModel descriptorModel = DescriptorModel.getDefault().getServerModel(new Path(serverConfDir)); int port = descriptorModel.getJNDIPort(); Thread.currentThread().setContextClassLoader(twiddleLoader); Properties props = new Properties(); props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces"); props.put("java.naming.provider.url","jnp://" + server.getHost() + ":" + port); setCredentials(); while( !done && !canceled ) { InitialContext ic; try { ic = new InitialContext(props); Object obj = ic.lookup("jmx/invoker/RMIAdaptor"); ic.close(); if( obj instanceof MBeanServerConnection ) { MBeanServerConnection connection = (MBeanServerConnection)obj; Object attInfo = connection.getAttribute(new ObjectName("jboss.system:type=Server"), "Started"); boolean b = ((Boolean)attInfo).booleanValue(); started = b ? STATE_STARTED : STATE_TRANSITION; if( b && expectedState ) done = true; } } catch( SecurityException se ) { pollingException = new PollingSecurityException("Security Exception: " + se.getMessage()); + done = true; } catch( Exception e ) { started = STATE_STOPPED; if( !expectedState ) done = true; } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // end while } Thread.currentThread().setContextClassLoader(currentLoader); } protected void setCredentials() { try { ILaunchConfiguration lc = server.getLaunchConfiguration(true, new NullProgressMonitor()); String twiddleArgs = lc.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS + JBossServerLaunchConfiguration.PRGM_ARGS_TWIDDLE_SUFFIX, (String)null); String user = ArgsUtil.getValue(twiddleArgs, "-u", "--user"); String password = ArgsUtil.getValue(twiddleArgs, "-p", "--password"); // get our methods Class simplePrincipal = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.security.SimplePrincipal"); Class securityAssoc = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.security.SecurityAssociation"); securityAssoc.getMethods(); // force-init the methods since the class hasn't been initialized yet. Constructor newSimplePrincipal = simplePrincipal.getConstructor(new Class[] { String.class }); Object newPrincipalInstance = newSimplePrincipal.newInstance(new Object[] {user}); // set the principal Method setPrincipalMethod = securityAssoc.getMethod("setPrincipal", new Class[] {Principal.class}); setPrincipalMethod.invoke(null, new Object[] {newPrincipalInstance}); // set the credential Method setCredentialMethod = securityAssoc.getMethod("setCredential", new Class[] {Object.class}); setCredentialMethod.invoke(null, new Object[] {password}); } catch( Exception e ) { e.printStackTrace(); } } protected ClassLoader getClassLoader() { try { IRuntime rt = server.getRuntime(); IPath loc = rt.getLocation(); URL url = loc.append("client").append("jbossall-client.jar").toFile().toURI().toURL(); URL url2 = loc.append("bin").append("twiddle.jar").toFile().toURI().toURL(); URLClassLoader loader = new URLClassLoader(new URL[] {url, url2}, Thread.currentThread().getContextClassLoader()); return loader; } catch( MalformedURLException murle) { murle.printStackTrace(); } return null; } public void setCanceled() { if( launcher != null ) { launcher.setCanceled(); } } } public void eventTwiddleExecuted() { TwiddlePollerEvent tpe = new TwiddlePollerEvent(event, TYPE_RESULT, started, expectedState); EventLogModel.markChanged(event); } public void eventAllProcessesTerminated() { TwiddlePollerEvent tpe = new TwiddlePollerEvent(event, TYPE_TERMINATED, started, expectedState); EventLogModel.markChanged(event); } private void launchTwiddlePoller() { PollerRunnable run = new PollerRunnable(); Thread t = new Thread(run, "Twiddle Poller"); t.start(); } public void cancel(int type) { canceled = true; } public void cleanup() { } public class PollingSecurityException extends PollingException { public PollingSecurityException(String msg) {super(msg);} } public class PollingNamingException extends PollingException { public PollingNamingException(String msg) {super(msg);} } public boolean getState() throws PollingException { if( pollingException != null ) throw pollingException; if( started == 0 ) return SERVER_DOWN; if( started == 1 ) return SERVER_UP; if( !done && !canceled ) return !expectedState; // Not there yet. return expectedState; // done or canceled, doesnt matter } public boolean isComplete() throws PollingException { if( pollingException != null ) throw pollingException; return done; } public class TwiddlePollerEvent extends EventLogTreeItem { public TwiddlePollerEvent(SimpleTreeItem parent, String type, int status, boolean expectedState) { super(parent, PollThread.SERVER_STATE_MAJOR_TYPE, type); setProperty(PollThread.EXPECTED_STATE, new Boolean(expectedState)); setProperty(STATUS, new Integer(status)); setProperty(DATE, new Long(new Date().getTime())); } } }
true
true
public void run() { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); ClassLoader twiddleLoader = getClassLoader(); if( twiddleLoader != null ) { String serverConfDir = ServerConverter.getJBossServer(server).getConfigDirectory(false); ServerDescriptorModel descriptorModel = DescriptorModel.getDefault().getServerModel(new Path(serverConfDir)); int port = descriptorModel.getJNDIPort(); Thread.currentThread().setContextClassLoader(twiddleLoader); Properties props = new Properties(); props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces"); props.put("java.naming.provider.url","jnp://" + server.getHost() + ":" + port); setCredentials(); while( !done && !canceled ) { InitialContext ic; try { ic = new InitialContext(props); Object obj = ic.lookup("jmx/invoker/RMIAdaptor"); ic.close(); if( obj instanceof MBeanServerConnection ) { MBeanServerConnection connection = (MBeanServerConnection)obj; Object attInfo = connection.getAttribute(new ObjectName("jboss.system:type=Server"), "Started"); boolean b = ((Boolean)attInfo).booleanValue(); started = b ? STATE_STARTED : STATE_TRANSITION; if( b && expectedState ) done = true; } } catch( SecurityException se ) { pollingException = new PollingSecurityException("Security Exception: " + se.getMessage()); } catch( Exception e ) { started = STATE_STOPPED; if( !expectedState ) done = true; } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // end while } Thread.currentThread().setContextClassLoader(currentLoader); }
public void run() { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); ClassLoader twiddleLoader = getClassLoader(); if( twiddleLoader != null ) { String serverConfDir = ServerConverter.getJBossServer(server).getConfigDirectory(false); ServerDescriptorModel descriptorModel = DescriptorModel.getDefault().getServerModel(new Path(serverConfDir)); int port = descriptorModel.getJNDIPort(); Thread.currentThread().setContextClassLoader(twiddleLoader); Properties props = new Properties(); props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces"); props.put("java.naming.provider.url","jnp://" + server.getHost() + ":" + port); setCredentials(); while( !done && !canceled ) { InitialContext ic; try { ic = new InitialContext(props); Object obj = ic.lookup("jmx/invoker/RMIAdaptor"); ic.close(); if( obj instanceof MBeanServerConnection ) { MBeanServerConnection connection = (MBeanServerConnection)obj; Object attInfo = connection.getAttribute(new ObjectName("jboss.system:type=Server"), "Started"); boolean b = ((Boolean)attInfo).booleanValue(); started = b ? STATE_STARTED : STATE_TRANSITION; if( b && expectedState ) done = true; } } catch( SecurityException se ) { pollingException = new PollingSecurityException("Security Exception: " + se.getMessage()); done = true; } catch( Exception e ) { started = STATE_STOPPED; if( !expectedState ) done = true; } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // end while } Thread.currentThread().setContextClassLoader(currentLoader); }
diff --git a/framework/src/net/sf/tapestry/engine/ExternalService.java b/framework/src/net/sf/tapestry/engine/ExternalService.java index e3bd4499f..3392f2093 100644 --- a/framework/src/net/sf/tapestry/engine/ExternalService.java +++ b/framework/src/net/sf/tapestry/engine/ExternalService.java @@ -1,175 +1,175 @@ // // Tapestry Web Application Framework // Copyright (c) 2000-2002 by Howard Lewis Ship // // Howard Lewis Ship // http://sf.net/projects/tapestry // mailto:[email protected] // // This library is free software. // // You may redistribute it and/or modify it under the terms of the GNU // Lesser General Public License as published by the Free Software Foundation. // // Version 2.1 of the license should be included with this distribution in // the file LICENSE, as well as License.html. If the license is not // included with this distribution, you may find a copy at the FSF web // site at 'www.gnu.org' or 'www.fsf.org', or you may write to the // Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied waranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // package net.sf.tapestry.engine; import java.io.IOException; import javax.servlet.ServletException; import net.sf.tapestry.ApplicationRuntimeException; import net.sf.tapestry.Gesture; import net.sf.tapestry.IComponent; import net.sf.tapestry.IEngineServiceView; import net.sf.tapestry.IExternalPage; import net.sf.tapestry.IRequestCycle; import net.sf.tapestry.RequestCycleException; import net.sf.tapestry.ResponseOutputStream; import net.sf.tapestry.Tapestry; import net.sf.tapestry.util.io.DataSqueezer; /** * The external service enables external applications * to reference Tapestry pages via a URL. Pages which can be referenced * by the external service must implement the {@link IExternalPage} * interface. The external service enables the bookmarking of pages. * <p> * The URL format for the external service is: * <blockquote> * <tt>http://localhost/app?service=external&amp;context=[Page Name]&amp;sp=[Param 0]&amp;sp=[Param 1]...</tt> * </blockquote> * For example to view the "ViewCustomer" page the service parameters 5056 (customer ID) and * 309 (company ID) the external service URL would be: * <blockquote> * <tt>http://localhost/myapp?service=external&amp;context=<b>ViewCustomer</b>&amp;sp=<b>5056</b>&amp;sp=<b>302</b></tt> * </blockquote> * In this example external service will get a "ViewCustomer" page and invoke the * {@link IExternalPage#activateExternalPage(Object[], IRequestCycle)} method with the parameters: * Object[] { new Integer(5056), new Integer(302) }. * <p> * Note service parameters (sp) need to be prefixed by valid * {@link DataSqueezer} adaptor char. These adaptor chars are automatically provided in * URL's created by the <tt>buildGesture()</tt> method. However if you hand coded an external * service URL you will need to ensure valid prefix chars are present. * <p> * <table border="1" cellpadding="2"> * <tr> * <th>Prefix char(s)</th><th>Mapped Java Type</th> * </tr> * <tr> * <td>&nbsp;TF</td><td>&nbsp;boolean</td> * </tr> * <tr> * <td>&nbsp;b</td><td>&nbsp;byte</td> * </tr> * <tr> * <td>&nbsp;c</td><td>&nbsp;char</td> * </tr> * <tr> * <td>&nbsp;d</td><td>&nbsp;double</td> * </tr> * <tr> * <td>&nbsp;-0123456789</td><td>&nbsp;integer</td> * </tr> * <tr> * <td>&nbsp;l</td><td>&nbsp;long</td> * </tr> * <tr> * <td>&nbsp;S</td><td>&nbsp;String</td> * </tr> * <tr> * <td>&nbsp;s</td><td>&nbsp;short</td> * </tr> * <tr> * <td>&nbsp;other chars</td> * <td>&nbsp;<tt>String</tt> without truncation of first char</td> * </tr> * <table> * <p> * <p> * A good rule of thumb is to keep the information encoded in the URL short and simple, and restrict it * to just Strings and Integers. Integers can be encoded as-is. Prefixing all Strings with the letter 'S' * will ensure that they are decoded properly. Again, this is only relevant if an * {@link net.sf.tapestry.IExternalPage} is being referenced from static HTML or JSP and the * URL must be assembled in user code ... when the URL is generated by Tapestry, it is automatically * created with the correct prefixes and encodings (as with any other service). * * @see net.sf.tapestry.IExternalPage * * @author Howard Lewis Ship * @author Malcolm Edgar * @since 2.2 * **/ public class ExternalService extends AbstractService { public Gesture buildGesture(IRequestCycle cycle, IComponent component, Object[] parameters) { if (parameters == null || parameters.length == 0) throw new ApplicationRuntimeException(Tapestry.getString("service-requires-parameters", EXTERNAL_SERVICE)); String pageName = (String)parameters[0]; String[] context = new String[] { pageName }; Object[] pageParameters = new Object[parameters.length - 1]; System.arraycopy(parameters, 1, pageParameters, 0, parameters.length - 1); return assembleGesture(cycle, EXTERNAL_SERVICE, context, pageParameters, true); } public boolean service(IEngineServiceView engine, IRequestCycle cycle, ResponseOutputStream output) throws RequestCycleException, ServletException, IOException { IExternalPage page = null; String[] context = getServiceContext(cycle.getRequestContext()); if (context == null || context.length != 1) throw new ApplicationRuntimeException( - Tapestry.getString("service-single-parameter", EXTERNAL_SERVICE)); + Tapestry.getString("service-single-context-parameter", EXTERNAL_SERVICE)); String pageName = context[0]; try { page = (IExternalPage) cycle.getPage(pageName); } catch (ClassCastException ex) { throw new ApplicationRuntimeException( Tapestry.getString("ExternalService.page-not-compatible", pageName), ex); } page.validate(cycle); cycle.setPage(page); Object[] parameters = getParameters(cycle); page.activateExternalPage(parameters, cycle); // Render the response. engine.renderResponse(cycle, output); return true; } public String getName() { return EXTERNAL_SERVICE; } }
true
true
public boolean service(IEngineServiceView engine, IRequestCycle cycle, ResponseOutputStream output) throws RequestCycleException, ServletException, IOException { IExternalPage page = null; String[] context = getServiceContext(cycle.getRequestContext()); if (context == null || context.length != 1) throw new ApplicationRuntimeException( Tapestry.getString("service-single-parameter", EXTERNAL_SERVICE)); String pageName = context[0]; try { page = (IExternalPage) cycle.getPage(pageName); } catch (ClassCastException ex) { throw new ApplicationRuntimeException( Tapestry.getString("ExternalService.page-not-compatible", pageName), ex); } page.validate(cycle); cycle.setPage(page); Object[] parameters = getParameters(cycle); page.activateExternalPage(parameters, cycle); // Render the response. engine.renderResponse(cycle, output); return true; }
public boolean service(IEngineServiceView engine, IRequestCycle cycle, ResponseOutputStream output) throws RequestCycleException, ServletException, IOException { IExternalPage page = null; String[] context = getServiceContext(cycle.getRequestContext()); if (context == null || context.length != 1) throw new ApplicationRuntimeException( Tapestry.getString("service-single-context-parameter", EXTERNAL_SERVICE)); String pageName = context[0]; try { page = (IExternalPage) cycle.getPage(pageName); } catch (ClassCastException ex) { throw new ApplicationRuntimeException( Tapestry.getString("ExternalService.page-not-compatible", pageName), ex); } page.validate(cycle); cycle.setPage(page); Object[] parameters = getParameters(cycle); page.activateExternalPage(parameters, cycle); // Render the response. engine.renderResponse(cycle, output); return true; }
diff --git a/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java b/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java index e7df4d1..db1fac7 100644 --- a/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java +++ b/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java @@ -1,100 +1,95 @@ package org.disco.easyb.core.delegates; import groovy.lang.Closure; import org.disco.easyb.core.exception.VerificationException; /** * * @author aglover * */ public class EnsuringDelegate { /** * * @param clzz * the class of the exception type expected * @param closure * closure containing code to be run that should throw an * exception * @throws Exception */ public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { - boolean expectedExceptionCaught = false; try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } - expectedExceptionCaught = true; - } - if (!expectedExceptionCaught) { - // Can't throw this immediately after the invokation of the closure because this exception - // would get inadvertantly caught by the catch which contains it. Thus the flag approach. - throw new VerificationException("expected exception of type " + clzz + " was not thrown"); + return; } + throw new VerificationException("expected exception of type " + clzz + " was not thrown"); } /** * * @param expression * to be evaluated and should resolve to a boolean result * @throws Exception */ public void ensure(final boolean expression) throws Exception { if (!expression) { throw new VerificationException("the expression evaluated to false"); } } /** * * @param value * @param closure * @throws Exception */ public void ensure(final Object value, final Closure closure) throws Exception { RichlyEnsurable delegate = this.getDelegate(value); closure.setDelegate(delegate); closure.call(); } /** * * @param value * @return FlexibleDelegate instance * @throws Exception */ private RichlyEnsurable getDelegate(final Object value) throws Exception { RichlyEnsurable delegate = EnsurableFactory.manufacture(); delegate.setVerified(value); return delegate; } /** * * @param message */ public void fail(String message) { throw new VerificationException(message); } /** * * @param message * @param e */ public void fail(String message, Exception e) { throw new VerificationException(message, e); } /** * * @param message * @param expected * @param actual */ public void fail(String message, Object expected, Object actual) { throw new VerificationException(message, expected, actual); } }
false
true
public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { boolean expectedExceptionCaught = false; try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } expectedExceptionCaught = true; } if (!expectedExceptionCaught) { // Can't throw this immediately after the invokation of the closure because this exception // would get inadvertantly caught by the catch which contains it. Thus the flag approach. throw new VerificationException("expected exception of type " + clzz + " was not thrown"); } }
public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } return; } throw new VerificationException("expected exception of type " + clzz + " was not thrown"); }
diff --git a/src/main/java/net/dtl/citizens/trader/parts/TraderStockPart.java b/src/main/java/net/dtl/citizens/trader/parts/TraderStockPart.java index ab725cb..b7fde16 100644 --- a/src/main/java/net/dtl/citizens/trader/parts/TraderStockPart.java +++ b/src/main/java/net/dtl/citizens/trader/parts/TraderStockPart.java @@ -1,523 +1,523 @@ package net.dtl.citizens.trader.parts; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.citizensnpcs.api.util.DataKey; import net.dtl.citizens.trader.CitizensTrader; import net.dtl.citizens.trader.ItemsConfig; import net.dtl.citizens.trader.managers.PatternsManager; import net.dtl.citizens.trader.objects.NBTTagEditor; import net.dtl.citizens.trader.objects.StockItem; import net.dtl.citizens.trader.objects.TransactionPattern; import net.dtl.citizens.trader.types.Trader.TraderStatus; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; public class TraderStockPart implements InventoryHolder { private static PatternsManager patternsManager = CitizensTrader.getPatternsManager(); private static ItemsConfig itemsConfig = CitizensTrader.getInstance().getItemConfig(); public TraderStockPart(String name) { this(54, name); pattern = null; } private TraderStockPart(int size, String name) { this.name = name; stockSize = size; if( size <= 0 || size > 54 ){ throw new IllegalArgumentException("Size must be between 1 and 54");} stock = new HashMap<String, List<StockItem>>(); stock.put("sell", new ArrayList<StockItem>()); stock.put("buy", new ArrayList<StockItem>()); } private int stockSize; private String name; private TransactionPattern pattern; private Map<String,List<StockItem>> stock; //set/get the pattern public TransactionPattern getPattern() { return pattern; } public boolean setPattern(String pattern) { if ( patternsManager.getPattern(pattern) == null ) return false; this.pattern = patternsManager.getPattern(pattern); this.reloadStock(); return true; } public void removePattern() { pattern = null; reloadStock(); } public List<StockItem> getStock(String stock) { return this.stock.get(stock); } public void reloadStock() { List<StockItem> oldSellStock = new ArrayList<StockItem>(); for ( StockItem item : stock.get("sell") ) if ( !item.isPatternItem() ) oldSellStock.add(item); List<StockItem> oldBuyStock = new ArrayList<StockItem>(); for ( StockItem item : stock.get("buy") ) if ( !item.isPatternItem() ) oldBuyStock.add(item); stock.get("sell").clear(); stock.get("buy").clear(); if ( pattern != null ) { stock.get("sell").addAll( pattern.getStockItems("sell") ); stock.get("buy").addAll( pattern.getStockItems("buy") ); } for ( StockItem item : oldSellStock ) { stock.get("sell").remove(item); stock.get("sell").add(item); } for ( StockItem item : oldBuyStock ) { stock.get("buy").remove(item); stock.get("buy").add(item); } } public void clearStock(String stock) { this.stock.get(stock).clear(); } public void clearStock() { clearStock("sell"); clearStock("buy"); } public Inventory getInventory(String startingStock, Player player) { Inventory inventory = Bukkit.createInventory(this, stockSize, name); for( StockItem item : stock.get(startingStock) ) { ItemStack chk = setLore(item.getItemStack(), getPriceLore(item, 0, startingStock, pattern, player)); // chk.addEnchantments(item.getItemStack().getEnchantments()); if ( item.getSlot() < 0 ) item.setSlot(inventory.firstEmpty()); inventory.setItem(item.getSlot(),chk); } if ( !stock.get( opositeStock(startingStock) ).isEmpty() ) inventory.setItem(stockSize - 1, itemsConfig.getItemManagement( opositeStock(startingStock) ) ); return inventory; } public Inventory inventoryView(Inventory inventory, TraderStatus s, Player player, String type) { if ( !s.isManaging() ) { for( StockItem item : stock.get(s.toString()) ) { ItemStack chk = setLore(item.getItemStack(), getPriceLore(item, 0, s.toString(), pattern, player)); // chk.addEnchantments(item.getItemStack().getEnchantments()); if ( item.getSlot() < 0 ) item.setSlot(inventory.firstEmpty()); inventory.setItem( item.getSlot() ,chk); } if ( !stock.get( opositeStock(s.toString()) ).isEmpty() ) inventory.setItem(stockSize - 1, itemsConfig.getItemManagement( opositeStock(s.toString()) ) ); } else { for( StockItem item : stock.get(s.toString()) ) { ItemStack chk = setLore(item.getItemStack(), getLore(type, item, s.toString(), pattern, player)); //ItemStack chk = new ItemStack(item.getItemStack().getType(),item.getItemStack().getAmount(),item.getItemStack().getDurability()); // chk.addEnchantments(item.getItemStack().getEnchantments()); if ( item.getSlot() < 0 ) item.setSlot(inventory.firstEmpty()); inventory.setItem( item.getSlot() ,chk); } inventory.setItem(stockSize - 3, itemsConfig.getItemManagement(4) ); inventory.setItem(stockSize - 2, itemsConfig.getItemManagement(2) ); inventory.setItem(stockSize - 1, itemsConfig.getItemManagement(opositeStock(s.toString())) ); } return inventory; } public void addItem(String stock ,String data) { this.stock.get(stock).add(new StockItem(data)); } public void addItem(String stock, StockItem stockItem) { this.stock.get(stock).add(stockItem); } public void removeItem(String stock, int slot) { for ( StockItem item : this.stock.get(stock) ) if ( item.getSlot() == slot ) { this.stock.get(stock).remove(item); return; } } public StockItem getItem(int slot, TraderStatus status) { for ( StockItem item : stock.get(status.toString()) ) if ( item.getSlot() == slot ) return item; return null; } public StockItem getItem(ItemStack itemStack, TraderStatus status, boolean dura, boolean amount) { boolean equal = false; for ( StockItem item : stock.get(status.toString()) ) { equal = false; if ( itemStack.getType().equals(item.getItemStack().getType()) ) { equal = true; if ( dura ) equal = itemStack.getDurability() <= item.getItemStack().getDurability(); else equal = itemStack.getData().equals(item.getItemStack().getData()); if ( amount && equal ) equal = itemStack.getAmount() >= item.getItemStack().getAmount(); if ( equal ) { // StockItem has 2 boolean properties that are set to true if its entry in an Items Pattern has the "ce" or "cel" flags boolean checkEnchant = item.isCheckingEnchantments(); boolean checkLevel = item.isCheckingEnchantmentLevels(); if ( checkEnchant || checkLevel ) { Map<Enchantment,Integer> itemStackEnchantments = null; Map<Enchantment,Integer> stockItemEnchantments = null; // special handling for Enchanted Books and stored enchantments if ( itemStack.getType().equals(Material.ENCHANTED_BOOK) ) { EnchantmentStorageMeta itemStackStorageMeta = (EnchantmentStorageMeta)itemStack.getItemMeta(); if (itemStackStorageMeta != null) { itemStackEnchantments = itemStackStorageMeta.getStoredEnchants(); } EnchantmentStorageMeta stockItemStorageMeta = (EnchantmentStorageMeta)item.getItemStack().getItemMeta(); if (stockItemStorageMeta != null) { - itemStackEnchantments = stockItemStorageMeta.getStoredEnchants(); + stockItemEnchantments = stockItemStorageMeta.getStoredEnchants(); } } else { // regular enchantments (not stored enchantments) itemStackEnchantments = itemStack.getEnchantments(); stockItemEnchantments = item.getItemStack().getEnchantments(); } if (itemStackEnchantments == null || itemStackEnchantments.isEmpty()) { equal = (stockItemEnchantments == null || stockItemEnchantments.isEmpty()); } else { equal = ( stockItemEnchantments != null && !stockItemEnchantments.isEmpty() && itemStackEnchantments.keySet().equals(stockItemEnchantments.keySet()) ); } // equal is still true if both itemStacks had the same enchanments if ( equal && checkLevel ) { for ( Map.Entry<Enchantment,Integer> ench : itemStackEnchantments.entrySet() ) { if ( ench.getValue() != stockItemEnchantments.get(ench.getKey()) ) { equal = false; break; } } } } } if ( equal ) return item; } } return null; } public void setInventoryWith(Inventory inventory, StockItem item, Player player) { int i = 0; for ( Integer amount : item.getAmounts() ) { ItemStack chk = setLore(item.getItemStack(), getPriceLore(item, i, "sell", pattern, player)); // chk.addEnchantments(item.getItemStack().getEnchantments()); chk.setAmount(amount); if ( item.getLimitSystem().checkLimit("", i) ) inventory.setItem(i++,chk); } inventory.setItem(stockSize - 1, itemsConfig.getItemManagement(7)); } public static void setManagerInventoryWith(Inventory inventory, StockItem item) { int i = 0; for ( Integer amount : item.getAmounts() ) { ItemStack itemStack = item.getItemStack().clone(); itemStack.setAmount(amount); inventory.setItem(i++, itemStack); } inventory.setItem(inventory.getSize() - 1, itemsConfig.getItemManagement(7)); } public void linkItems() { for ( StockItem item : stock.get("sell") ) { for ( int i = 0 ; i < stock.get("buy").size() ; ++i ) { if ( item.equals(stock.get("buy").get(i)) ) { item.getLimitSystem().linkWith(stock.get("buy").get(i)); stock.get("buy").get(i).getLimitSystem().setGlobalAmount(item.getLimitSystem().getGlobalLimit()); stock.get("buy").get(i).getLimitSystem().linkWith(item); } } } } //Returning the displayInventory @Override public Inventory getInventory() { Inventory inventory = Bukkit.createInventory(this, stockSize, name); for( StockItem item : stock.get("sell") ) { ItemStack chk = setLore(item.getItemStack(), getPriceLore(item, 0, "sell", pattern, null)); // chk.addEnchantments(item.getItemStack().getEnchantments()); if ( item.getSlot() < 0 ) item.setSlot(inventory.firstEmpty()); inventory.setItem(item.getSlot(),chk); } if ( !stock.get( "buy" ).isEmpty() ) inventory.setItem(stockSize - 1, itemsConfig.getItemManagement( "buy" ) ); return inventory; } @SuppressWarnings("unchecked") public void load(DataKey data) { if ( data.keyExists("sell") ) { for ( String item : (List<String>) data.getRaw("sell") ) { StockItem stockItem = new StockItem(item); if ( stockItem.getSlot() < 0 ) stock.get("sell").add(stockItem); else stock.get("sell").add(0, stockItem); } } if ( data.keyExists("buy") ) { for ( String item : (List<String>) data.getRaw("buy") ) { StockItem stockItem = new StockItem(item); if ( stockItem.getSlot() < 0 ) stock.get("buy").add(stockItem); else stock.get("buy").add(0, stockItem); } } setPattern( data.getString("pattern", "") ); } public void save(DataKey data) { if ( pattern != null ) if ( !pattern.getName().isEmpty() ) data.setString("pattern", pattern.getName()); List<String> sellList = new ArrayList<String>(); for ( StockItem item : stock.get("sell") ) if ( !item.isPatternItem() ) sellList.add(item.toString()); List<String> buyList = new ArrayList<String>(); for ( StockItem item : stock.get("buy") ) { if ( !item.isPatternItem() ) buyList.add(item.toString()); } data.setRaw("sell", sellList); data.setRaw("buy", buyList); } //Static methods public static ItemStack setLore(ItemStack cis, List<String> lore) { ItemMeta meta = Bukkit.getItemFactory().getItemMeta(cis.getType()); List<String> list = cis.getItemMeta().getLore(); if ( list == null ) list = new ArrayList<String>(); for ( String s : lore ) list.add(s.replace('^', '§')); meta.setLore(list); meta.setDisplayName(NBTTagEditor.getName(cis)); for ( Map.Entry<Enchantment, Integer> e : cis.getEnchantments().entrySet() ) meta.addEnchant(e.getKey(), e.getValue(), true); if ( cis.getType().equals(Material.ENCHANTED_BOOK) ) { for ( Map.Entry<Enchantment, Integer> e : ((EnchantmentStorageMeta)cis.getItemMeta()).getStoredEnchants().entrySet() ) ((EnchantmentStorageMeta)meta).addStoredEnchant(e.getKey(), e.getValue(), true); } Map<String, Object> map = cis.serialize(); map.put("meta", meta); // cis.setItemMeta(ItemStack.deserialize(map).getItemMeta()); return ItemStack.deserialize(map); } public static List<String> getLore(String type, StockItem item, String stock, TransactionPattern pattern, Player player) { if ( type.equals("glimit") ) return getLimitLore(item, stock, pattern, player); if ( type.equals("plimit") ) return getPlayerLimitLore(item, stock, pattern, player); if ( type.equals("manage") ) return getManageLore(item, stock, pattern, player); return getPriceLore(item, 0, stock, pattern, player); } public static List<String> getPriceLore(StockItem item, int i, String stock, TransactionPattern pattern, Player player) { String price = ""; DecimalFormat format = new DecimalFormat("#.##"); if ( pattern != null ) price = format.format(pattern.getItemPrice(player, item, stock, i, 0.0)); else price = format.format(item.getPrice(i)); List<String> lore = new ArrayList<String>(); for ( String line : itemsConfig.getPriceLore(stock) ) lore.add(line.replace("{price}", price).replace("{amount}", item.getLimitSystem().getStackAmount())); return lore; } public static List<String> getManageLore(StockItem item, String stock, TransactionPattern pattern, Player player) { List<String> lore = new ArrayList<String>(); if ( item.hasStackPrice() ) lore.add("^7Stack price"); if ( item.isPatternListening() ) lore.add("^7Pattern price"); if ( item.isPatternItem() ) lore.add("^7Pattern item"); return lore; } public static List<String> getPlayerLimitLore(StockItem item, String stock, TransactionPattern pattern, Player player) { List<String> lore = new ArrayList<String>(); if ( item.getLimitSystem().hasLimit() ) { lore.add("^7Limit: ^6" +item.getLimitSystem().getPlayerLimit()); lore.add("^7Timeout: ^6" + item.getLimitSystem().getPlayerTimeout()); } return lore; } public static List<String> getLimitLore(StockItem item, String stock, TransactionPattern pattern, Player player) { List<String> lore = new ArrayList<String>(); if ( item.getLimitSystem().hasLimit() ) { lore.add("^7Limit: ^e" + item.getLimitSystem().getGlobalAmount() + "^6/" + item.getLimitSystem().getGlobalLimit()); lore.add("^7Timeout: ^6" + item.getLimitSystem().getGlobalTimeout()); } return lore; } public static String opositeStock(String stock) { return ( stock.equals("sell") ? "buy" : "sell" ); } public static void saveNewAmounts(Inventory inventory, StockItem si) { si.getAmounts().clear(); for ( ItemStack is : inventory.getContents() ) if ( is != null ) si.addAmount(is.getAmount()); if ( si.getAmounts().size() > 1 ) si.getAmounts().remove(si.getAmounts().size()-1); } public void resetPrices() { for ( StockItem item : stock.get("sell") ) { item.setRawPrice(0.0); item.setPatternListening(true); } for ( StockItem item : stock.get("buy") ) { item.setRawPrice(0.0); item.setPatternListening(true); } } }
true
true
public StockItem getItem(ItemStack itemStack, TraderStatus status, boolean dura, boolean amount) { boolean equal = false; for ( StockItem item : stock.get(status.toString()) ) { equal = false; if ( itemStack.getType().equals(item.getItemStack().getType()) ) { equal = true; if ( dura ) equal = itemStack.getDurability() <= item.getItemStack().getDurability(); else equal = itemStack.getData().equals(item.getItemStack().getData()); if ( amount && equal ) equal = itemStack.getAmount() >= item.getItemStack().getAmount(); if ( equal ) { // StockItem has 2 boolean properties that are set to true if its entry in an Items Pattern has the "ce" or "cel" flags boolean checkEnchant = item.isCheckingEnchantments(); boolean checkLevel = item.isCheckingEnchantmentLevels(); if ( checkEnchant || checkLevel ) { Map<Enchantment,Integer> itemStackEnchantments = null; Map<Enchantment,Integer> stockItemEnchantments = null; // special handling for Enchanted Books and stored enchantments if ( itemStack.getType().equals(Material.ENCHANTED_BOOK) ) { EnchantmentStorageMeta itemStackStorageMeta = (EnchantmentStorageMeta)itemStack.getItemMeta(); if (itemStackStorageMeta != null) { itemStackEnchantments = itemStackStorageMeta.getStoredEnchants(); } EnchantmentStorageMeta stockItemStorageMeta = (EnchantmentStorageMeta)item.getItemStack().getItemMeta(); if (stockItemStorageMeta != null) { itemStackEnchantments = stockItemStorageMeta.getStoredEnchants(); } } else { // regular enchantments (not stored enchantments) itemStackEnchantments = itemStack.getEnchantments(); stockItemEnchantments = item.getItemStack().getEnchantments(); } if (itemStackEnchantments == null || itemStackEnchantments.isEmpty()) { equal = (stockItemEnchantments == null || stockItemEnchantments.isEmpty()); } else { equal = ( stockItemEnchantments != null && !stockItemEnchantments.isEmpty() && itemStackEnchantments.keySet().equals(stockItemEnchantments.keySet()) ); } // equal is still true if both itemStacks had the same enchanments if ( equal && checkLevel ) { for ( Map.Entry<Enchantment,Integer> ench : itemStackEnchantments.entrySet() ) { if ( ench.getValue() != stockItemEnchantments.get(ench.getKey()) ) { equal = false; break; } } } } } if ( equal ) return item; } } return null; }
public StockItem getItem(ItemStack itemStack, TraderStatus status, boolean dura, boolean amount) { boolean equal = false; for ( StockItem item : stock.get(status.toString()) ) { equal = false; if ( itemStack.getType().equals(item.getItemStack().getType()) ) { equal = true; if ( dura ) equal = itemStack.getDurability() <= item.getItemStack().getDurability(); else equal = itemStack.getData().equals(item.getItemStack().getData()); if ( amount && equal ) equal = itemStack.getAmount() >= item.getItemStack().getAmount(); if ( equal ) { // StockItem has 2 boolean properties that are set to true if its entry in an Items Pattern has the "ce" or "cel" flags boolean checkEnchant = item.isCheckingEnchantments(); boolean checkLevel = item.isCheckingEnchantmentLevels(); if ( checkEnchant || checkLevel ) { Map<Enchantment,Integer> itemStackEnchantments = null; Map<Enchantment,Integer> stockItemEnchantments = null; // special handling for Enchanted Books and stored enchantments if ( itemStack.getType().equals(Material.ENCHANTED_BOOK) ) { EnchantmentStorageMeta itemStackStorageMeta = (EnchantmentStorageMeta)itemStack.getItemMeta(); if (itemStackStorageMeta != null) { itemStackEnchantments = itemStackStorageMeta.getStoredEnchants(); } EnchantmentStorageMeta stockItemStorageMeta = (EnchantmentStorageMeta)item.getItemStack().getItemMeta(); if (stockItemStorageMeta != null) { stockItemEnchantments = stockItemStorageMeta.getStoredEnchants(); } } else { // regular enchantments (not stored enchantments) itemStackEnchantments = itemStack.getEnchantments(); stockItemEnchantments = item.getItemStack().getEnchantments(); } if (itemStackEnchantments == null || itemStackEnchantments.isEmpty()) { equal = (stockItemEnchantments == null || stockItemEnchantments.isEmpty()); } else { equal = ( stockItemEnchantments != null && !stockItemEnchantments.isEmpty() && itemStackEnchantments.keySet().equals(stockItemEnchantments.keySet()) ); } // equal is still true if both itemStacks had the same enchanments if ( equal && checkLevel ) { for ( Map.Entry<Enchantment,Integer> ench : itemStackEnchantments.entrySet() ) { if ( ench.getValue() != stockItemEnchantments.get(ench.getKey()) ) { equal = false; break; } } } } } if ( equal ) return item; } } return null; }
diff --git a/HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/ParserHelper.java b/HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/ParserHelper.java index 8b92352..56c2781 100644 --- a/HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/ParserHelper.java +++ b/HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/helper/ParserHelper.java @@ -1,710 +1,714 @@ package com.magicmicky.habitrpglibrary.onlineapi.helper; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.magicmicky.habitrpglibrary.habits.*; public class ParserHelper { private final static String TAG_ERR="err"; private final static String TAG_AUTH_API_TOKEN="token"; private final static String TAG_AUTH_USER_TOKEN="id"; private final static String TAG_REG_API_TOKEN="apiToken"; private final static String TAG_REG_USER_TOKEN="id"; private static final String TAG_habitData = "habitRPGData"; private static final String TAG_DAILIESID = "dailyIds"; private static final String TAG_HABITSID = "habitIds"; private static final String TAG_TODOIDS = "todoIds"; private static final String TAG_REWARDIDS = "rewardIds"; private static final String TAG_TAGS = "tags"; private static final String TAG_TAGS_ID = "id"; private static final String TAG_TAGS_NAME = "name"; private static final String TAG_STATS = "stats"; private static final String TAG_STATS_CLASS = "class"; private static final String TAG_XP = "exp"; private static final String TAG_GP = "gp"; private static final String TAG_HP = "hp"; private static final String TAG_LVL="lvl"; private static final String TAG_XP_MAX="toNextLevel"; private static final String TAG_HP_MAX = "maxHealth"; private static final String TAG_TASKS = "tasks"; private static final String TAG_TASK_TYPE = "type"; private static final String TAG_TASK_ID = "id"; private static final String TAG_TASK_DATE = "date"; private static final String TAG_TASK_NOTES = "notes"; private static final String TAG_TASK_PRIORITY = "priority"; private static final String TAG_TASK_TEXT = "text"; private static final String TAG_TASK_VALUE = "value"; private static final String TAG_TASK_ATTRIBUTE="attribute"; private static final String TAG_TASK_COMPLETED = "completed"; private static final String TAG_TASK_UP = "up"; private static final String TAG_TASK_DOWN = "down"; private static final String TAG_TASK_REPEAT = "repeat"; private static final String TAG_TASK_STREAK="streak"; private static final String TAG_TASK_TAGS = "tags"; private static final String TAG_TASK_HISTORY="history"; private static final String TAG_TASK_HISTORY_DATE = "date"; private static final String TAG_PROFILE = "profile"; private static final String TAG_PROFILE_NAME="name"; private static final String TAG_PREFS = "preferences"; private static final String TAG_PREFS_COSTUME="costume"; private static final String TAG_PREFS_SKIN = "skin"; private static final String TAG_PREFS_SHIRT="shirt"; private static final String TAG_PREFS_HAIR = "hair"; private static final String TAG_PREFS_HAIR_MUSTACHE="mustache"; private static final String TAG_PREFS_HAIR_BEARD="beard"; private static final String TAG_PREFS_HAIR_BANGS="bangs"; private static final String TAG_PREFS_HAIR_BASE="base"; private static final String TAG_PREFS_HAIR_COLOR="color"; private static final String TAG_PREFS_SIZE="size"; private static final String TAG_PREFS_DAYSTART = "dayStart"; private static final String TAG_PREFS_TIMEZONEOFFSET ="timezoneOffset"; private static final String TAG_ITEMS = "items"; private static final String TAG_ITEMS_PETS = "pets"; private static final String TAG_ITEMS_MOUNTS="mounts"; private static final String TAG_ITEMS_EGGS="eggs"; private static final String TAG_ITEMS_HATCHING_POTIONS="hatchingPotions"; private static final String TAG_ITEMS_FOOD="food"; private static final String TAG_ITEMS_GEAR="gear"; private static final String TAG_ITEMS_GEAR_EQUIPPED="equipped"; private static final String TAG_ITEMS_GEAR_COSTUME = "costume"; private static final String TAG_ITEMS_ARMOR = "armor"; private static final String TAG_ITEMS_HEAD = "head"; private static final String TAG_ITEMS_SHIELD = "shield"; private static final String TAG_ITEMS_WEAPON = "weapon"; //TODO:private static final String TAG_ITEMS_PETS = "pets"; private static final String TAG_NOWXP = "exp"; private static final String TAG_NOWGP = "gp"; private static final String TAG_NOWHP = "hp"; private static final String TAG_DELTA = "delta"; private static final String TAG_TASK_DELETED = "task_deleted"; //Hotfix private static final String TAG_DAILIES="dailys"; private static final String TAG_HABITS="habits"; private static final String TAG_TODOS="todos"; private static final String TAG_REWARDS="rewards"; public static User parseUser(JSONObject obj) throws ParseErrorException{ parseError(obj); if(obj.has(TAG_habitData)) { try { obj = obj.getJSONObject(TAG_habitData); } catch (JSONException e1) { // Can't happen e1.printStackTrace(); } } User user = new User(); /* * Parse tasks */ user.setItems(parseTasks(obj)); /* * Parse User infos */ try { parseUserInfos(obj, user); } catch (JSONException e) { e.printStackTrace(); //exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_INFO_NOT_FOUND)); } /* * Parse user look */ try { user.setLook(parseUserLook(obj)); } catch (ParseErrorException e) { e.printStackTrace(); //TODO: //exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_LOOK_NOT_FOUND)); } /* * Parse user tags. */ try { user.setTags(parseUserTags(obj.getJSONArray(TAG_TAGS))); } catch (JSONException e) { e.printStackTrace(); //exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_TAGS_NOT_FOUND)); } try { parseUserInventory(obj.getJSONObject(TAG_ITEMS), user); } catch (JSONException e) { e.printStackTrace(); //exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_TAGS_NOT_FOUND)); } return user; } private static void parseUserInventory(JSONObject obj, User user) { List<String> pets, mounts, eggs, hatchingPotions, food; //Pets: try { JSONObject pets_json = obj.getJSONObject(TAG_ITEMS_PETS); JSONArray pets_array = pets_json.names(); pets = new ArrayList<String>(); - for(int i = 0;i<pets_array.length()-1;i++) { - if(pets_json.getInt(pets_array.getString(i))>=1) { - pets.add(pets_array.getString(i)); + if(pets_array != null && pets_array.length()>0) { + for(int i = 0;i<pets_array.length()-1;i++) { + if(pets_json.getInt(pets_array.getString(i))>=1) + pets.add(pets_array.getString(i)); } } user.setPets(pets); } catch (JSONException e) { e.printStackTrace(); } /*Mounts JSONArray mounts_array = obj.getJSONArray(TAG_ITEMS_MOUNTS);*/ try { //Eggs JSONObject eggs_json = obj.getJSONObject(TAG_ITEMS_EGGS); JSONArray eggs_array = eggs_json.names(); eggs = new ArrayList<String>(); - for(int i = 0;i<eggs_array.length()-1;i++) { - if(eggs_json.getInt(eggs_array.getString(i))>=1) { - eggs.add(eggs_array.getString(i)); + if(eggs_array != null && eggs_array.length()>0) { + for(int i = 0;i<eggs_array.length()-1;i++) { + if(eggs_json.getInt(eggs_array.getString(i))>=1) + eggs.add(eggs_array.getString(i)); } } user.setEggs(eggs); } catch (JSONException e) { e.printStackTrace(); } try { //hatching potions JSONObject pot_json = obj.getJSONObject(TAG_ITEMS_HATCHING_POTIONS); JSONArray pot_array = pot_json.names(); hatchingPotions = new ArrayList<String>(); - for(int i = 0;i<pot_array.length()-1;i++) { - if(pot_json.getInt(pot_array.getString(i))>=1) { - hatchingPotions.add(pot_array.getString(i)); + if(pot_array!=null && pot_array.length() > 0) { + for(int i = 0;i<pot_array.length()-1;i++) { + if(pot_json.getInt(pot_array.getString(i))>=1) + hatchingPotions.add(pot_array.getString(i)); } } user.setHatchingPotions(hatchingPotions); } catch (JSONException e) { e.printStackTrace(); } try { //food JSONObject food_json = obj.getJSONObject(TAG_ITEMS_FOOD); JSONArray food_array = food_json.names(); food = new ArrayList<String>(); - for(int i = 0;i<food_array.length()-1;i++) { - if(food_json.getInt(food_array.getString(i))>=1) { - food.add(food_array.getString(i)); + if(food_array!=null && food_array.length()>0) { + for(int i = 0;i<food_array.length()-1;i++) { + if(food_json.getInt(food_array.getString(i))>=1) + food.add(food_array.getString(i)); } } user.setFood(food); } catch (JSONException e) { e.printStackTrace(); } } /** * Parses the tags from the user * @param obj the JSONArray containing the tags * @return a map of {@code <TagId, TagName>} */ private static Map<String, String> parseUserTags(JSONArray obj) { Map<String,String> tags = new HashMap<String,String>(); try { for(int i=0;i<obj.length();i++) { JSONObject tag_obj = obj.getJSONObject(i); tags.put(tag_obj.getString(TAG_TAGS_ID), tag_obj.getString(TAG_TAGS_NAME)); } } catch(JSONException e) { e.printStackTrace(); } return tags; } public static UserLook parseUserLook(JSONObject obj) throws ParseErrorException { UserLook look = new UserLook(); if(obj.has(TAG_PREFS)) { try { JSONObject prefs; prefs = obj.getJSONObject(TAG_PREFS); if(prefs.has(TAG_PREFS_COSTUME)) { look.setCostume(prefs.getBoolean(TAG_PREFS_COSTUME)); } if(prefs.has(TAG_PREFS_SIZE)) look.setSize(prefs.getString(TAG_PREFS_SIZE)); if(prefs.has(TAG_PREFS_SHIRT)) look.setShirtColor(prefs.getString(TAG_PREFS_SHIRT)); if(prefs.has(TAG_PREFS_SKIN)) look.setSkin(prefs.getString(TAG_PREFS_SKIN)); if(prefs.has(TAG_PREFS_HAIR)) { JSONObject hair = prefs.getJSONObject(TAG_PREFS_HAIR); int mustache = hair.getInt(TAG_PREFS_HAIR_MUSTACHE); int beard = hair.getInt(TAG_PREFS_HAIR_BEARD); int bangs = hair.getInt(TAG_PREFS_HAIR_BANGS); int base = hair.getInt(TAG_PREFS_HAIR_BASE); String color = hair.getString(TAG_PREFS_HAIR_COLOR); //UserHair user_hair = new UserHair(mustache, beard, bangs, base, color); UserHair user_hair = new UserHair(mustache, beard,bangs,base, color); look.setHair(user_hair); } }catch(JSONException e) { throw new ParseErrorException(ParseErrorException.JSON_USER_PREFS_ERROR); } } try { look.setItems(parseUserItems(obj.getJSONObject(TAG_ITEMS).getJSONObject(TAG_ITEMS_GEAR).getJSONObject(TAG_ITEMS_GEAR_EQUIPPED))); } catch(JSONException e) { throw new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_ITEMS); } try { look.setCostumeItems(parseUserItems(obj.getJSONObject(TAG_ITEMS).getJSONObject(TAG_ITEMS_GEAR).getJSONObject(TAG_ITEMS_GEAR_COSTUME))); } catch(JSONException e) { throw new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_ITEMS); } return look; } public static UserLook.UserItems parseUserItems(JSONObject obj) throws ParseErrorException { parseError(obj); String armor = null, head = null, shield = null, weapon = null; try { if(obj.has(TAG_ITEMS_ARMOR)) armor = (obj.getString(TAG_ITEMS_ARMOR)); if(obj.has(TAG_ITEMS_HEAD)) head = (obj.getString(TAG_ITEMS_HEAD)); if(obj.has(TAG_ITEMS_SHIELD)) shield = (obj.getString(TAG_ITEMS_SHIELD)); if(obj.has(TAG_ITEMS_WEAPON)) weapon = (obj.getString(TAG_ITEMS_WEAPON)); } catch (JSONException e){ e.printStackTrace(); //Should never happen } return new UserLook.UserItems(armor, head, shield, weapon); } private static void parseUserInfos(JSONObject obj, User user) throws JSONException { if(obj.has(TAG_STATS)) { JSONObject stats = obj.getJSONObject(TAG_STATS); if(stats.has(TAG_LVL)) user.setLvl(stats.getInt(TAG_LVL)); if(stats.has(TAG_XP)) user.setXp(stats.getDouble(TAG_XP)); if(stats.has(TAG_XP_MAX)) user.setMaxXp(stats.getDouble(TAG_XP_MAX)); if(stats.has(TAG_HP)) user.setHp(stats.getDouble(TAG_HP)); if(stats.has(TAG_HP_MAX)) user.setMaxHp(stats.getDouble(TAG_HP_MAX)); if(stats.has(TAG_GP)) user.setGp(stats.getDouble(TAG_GP)); if(stats.has(TAG_STATS_CLASS)) user.setUserClass(stats.getString(TAG_STATS_CLASS)); } if(obj.has(TAG_PREFS)) { JSONObject prefs = obj.getJSONObject(TAG_PREFS); if(prefs.has(TAG_PREFS_DAYSTART)) user.setDayStart(prefs.getInt(TAG_PREFS_DAYSTART)); else user.setDayStart(0); if(prefs.has(TAG_PREFS_TIMEZONEOFFSET)) user.setTimeZoneOffset(prefs.getInt(TAG_PREFS_TIMEZONEOFFSET)); } if(obj.has(TAG_PROFILE)) { JSONObject profile = obj.getJSONObject(TAG_PROFILE); user.setName(profile.getString(TAG_PROFILE_NAME)); } } /** * Parse all the tasks of the user * @param obj the json object of the user * @return the list of all the tasks of the user * @throws ParseErrorException when something isn't found. */ public static List<HabitItem> parseTasks(JSONObject obj) throws ParseErrorException { parseError(obj); List<HabitItem> items = new ArrayList<HabitItem>(); //First, parse the TASKS tag to find all tasks. JSONObject tasks; //try { try { JSONArray h = obj.getJSONArray(TAG_HABITS); for(int i=0;i<h.length();i++) { items.add(parseHabit(h.getJSONObject(i))); } JSONArray d = obj.getJSONArray(TAG_DAILIES); for(int i=0;i<d.length();i++) { items.add(parseDaily(d.getJSONObject(i))); } JSONArray r = obj.getJSONArray(TAG_REWARDS); for(int i=0;i<r.length();i++) { items.add(parseReward(r.getJSONObject(i))); } JSONArray t = obj.getJSONArray(TAG_TODOS); for(int i=0;i<t.length();i++) { items.add(parseTodo(t.getJSONObject(i))); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //tasks = obj.getJSONObject(TAG_TASKS); /* * Then parse DAILISES tag to find dailies id * and loop through them to find it in the TASKS tags */ /*try { JSONArray dailies = obj.getJSONArray(TAG_DAILIESID); for(int i=0;i<dailies.length();i++) { if(tasks.has(dailies.getString(i))) { items.add(parseDaily(tasks.getJSONObject(dailies.getString(i)))); //TODO: it Throws exception when stuff not found, but we still want to continue if this happens. } } } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_DAILIES_TAGS); throw(ex); } try { JSONArray todos = obj.getJSONArray(TAG_TODOIDS); for(int i=0;i<todos.length();i++) { if(tasks.has(todos.getString(i))) { items.add(parseTodo(tasks.getJSONObject(todos.getString(i)))); } } } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_TODOS_TAGS); throw(ex); } try { JSONArray habits = obj.getJSONArray(TAG_HABITSID); for(int i=0;i<habits.length();i++) { if(tasks.has(habits.getString(i))) { items.add(parseHabit(tasks.getJSONObject(habits.getString(i)))); } } } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_HABITS_TAGS); throw(ex); } try { JSONArray rewards = obj.getJSONArray(TAG_REWARDIDS); for(int i=0;i<rewards.length();i++) { if(tasks.has(rewards.getString(i))) { items.add(parseReward(tasks.getJSONObject(rewards.getString(i)))); } } } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_REWARDS_TAGS); throw(ex); } } catch (JSONException e) { e.printStackTrace(); //tasks = obj.getJSONObject(key) try { JSONArray h = obj.getJSONArray(TAG_HABITS); for(int i=0;i<h.length();i++) { items.add(parseHabit(h.getJSONObject(i))); } JSONArray d = obj.getJSONArray(TAG_DAILIES); for(int i=0;i<d.length();i++) { items.add(parseDaily(d.getJSONObject(i))); } JSONArray r = obj.getJSONArray(TAG_TODOS); for(int i=0;i<r.length();i++) { items.add(parseReward(r.getJSONObject(i))); } JSONArray t = obj.getJSONArray(TAG_TODOS); for(int i=0;i<t.length();i++) { items.add(parseTodo(t.getJSONObject(i))); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } */ //private static final String TAG_HABITS="habits"; //private static final String TAG_TODOS="todos"; //private static final String TAG_REWARDS="rewards"; //ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_TASKS_TAGS); //throw(ex); //} return items; } public static HabitItem parseHabitItem(JSONObject obj) throws ParseErrorException { parseError(obj); try { if(obj.getString(TAG_TASK_TYPE).equals("reward")) { return parseReward(obj); } else if(obj.getString(TAG_TASK_TYPE).equals("habit")) { return parseHabit(obj); } else if(obj.getString(TAG_TASK_TYPE).equals("daily")) { return parseDaily(obj); } else if(obj.getString(TAG_TASK_TYPE).equals("todo")) { return parseTodo(obj); } } catch (JSONException e) { e.printStackTrace(); } return null; } public static double[] parseDirectionAnswer(JSONObject obj) throws ParseErrorException { try { double xp = 0,hp = 0,gold = 0,lvl = 0,delta = 0; if(obj.has(TAG_NOWXP)) xp = obj.getDouble(TAG_NOWXP); if(obj.has(TAG_NOWHP)) hp = obj.getDouble(TAG_NOWHP); if(obj.has(TAG_NOWGP)) gold = obj.getDouble(TAG_NOWGP); if(obj.has(TAG_LVL)) lvl = obj.getDouble(TAG_LVL); if(obj.has(TAG_DELTA)) delta = obj.getDouble(TAG_DELTA); double[] res = {xp,hp,gold,lvl,delta}; return res; } catch (JSONException e) { e.printStackTrace(); throw(new ParseErrorException(ParseErrorException.HABITRPG_DIRECTION_ANSWER_UNPARSABLE)); } } private static Habit parseHabit(JSONObject obj) throws ParseErrorException { try { Habit it = new Habit(); parseBase(it, obj); it.setUp(obj.has(TAG_TASK_UP) ? obj.getBoolean(TAG_TASK_UP) : false); it.setDown(obj.has(TAG_TASK_DOWN) ? obj.getBoolean(TAG_TASK_DOWN) : false); return it; } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_HABIT_UNPARSABLE); throw(ex); } } private static Daily parseDaily(JSONObject obj) throws ParseErrorException { try { Daily it; String lastday=""; if(obj.has(TAG_TASK_HISTORY)) { JSONArray history = obj.getJSONArray(TAG_TASK_HISTORY); if(history.length()>=1) { try { lastday = history.getJSONObject(history.length()-1).getString(TAG_TASK_HISTORY_DATE); } catch(JSONException e) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); lastday=format.format(new Date(history.getJSONObject(history.length()-1).getLong(TAG_TASK_HISTORY_DATE))); } } } boolean[] repeats = {false,false,false,false,false,false,false}; if(obj.has(TAG_TASK_REPEAT)) { JSONObject repeatTag = obj.getJSONObject(TAG_TASK_REPEAT); for(int j=0;j<7;j++) { if(repeatTag.has(whatDay(j))) { try { repeats[j] = repeatTag.getBoolean(whatDay(j)); } catch(JSONException e) { repeats[j] = repeatTag.getInt(whatDay(j)) >= 1; } } } } it = new Daily(); parseBase(it, obj); it.setCompleted(obj.has(TAG_TASK_COMPLETED) ? obj.getBoolean(TAG_TASK_COMPLETED) : false); it.setRepeat(repeats); it.setStreak(obj.has(TAG_TASK_STREAK) ? obj.getInt(TAG_TASK_STREAK) : 0); it.setLastCompleted(lastday); return it; } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_DAILY_UNPARSABLE); throw(ex); } } private static ToDo parseTodo(JSONObject obj) throws ParseErrorException { try { ToDo it= new ToDo(); parseBase(it, obj); it.setCompleted(obj.has(TAG_TASK_COMPLETED) ? obj.getBoolean(TAG_TASK_COMPLETED) : false); it.setDate(obj.has(TAG_TASK_DATE) ? obj.getString(TAG_TASK_DATE) : null); return it; } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_TODO_UNPARSABLE); throw(ex); } } private static Reward parseReward(JSONObject obj) throws ParseErrorException { try { Reward it = new Reward(); parseBase(it, obj); return it; } catch (JSONException e) { e.printStackTrace(); ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_REWARD_UNPARSABLE); throw(ex); } } private static <T extends HabitItem> void parseBase(T it, JSONObject habit) throws JSONException { if(habit.has(TAG_TASK_ID)) it.setId(habit.getString(TAG_TASK_ID)); if(habit.has(TAG_TASK_NOTES)) it.setNotes(habit.getString(TAG_TASK_NOTES)); if(habit.has(TAG_TASK_PRIORITY)) it.setPriority(habit.getInt(TAG_TASK_PRIORITY)); if(habit.has(TAG_TASK_TEXT)) it.setText(habit.getString(TAG_TASK_TEXT)); if(habit.has(TAG_TASK_VALUE)) it.setValue(habit.getDouble(TAG_TASK_VALUE)); if(habit.has(TAG_TASK_ATTRIBUTE)) it.setAttribute(habit.getString(TAG_TASK_ATTRIBUTE)); if(habit.has(TAG_TASK_TAGS) && !habit.isNull(TAG_TASK_TAGS)) { try { JSONObject tagsJSON = habit.getJSONObject(TAG_TASK_TAGS); List<String> tags = parseTaskTags(tagsJSON); it.setTagsId(tags); } catch(JSONException error) { error.printStackTrace(); } } } private static List<String> parseTaskTags(JSONObject tagsJSON) throws JSONException { List<String> tagsIds = new ArrayList<String>(); @SuppressWarnings("unchecked") Iterator<String> it = tagsJSON.keys(); while(it.hasNext()) { String tag = it.next(); if(tagsJSON.getBoolean(tag)) tagsIds.add(tag); } return tagsIds; } public static void parseError(JSONObject obj) throws ParseErrorException{ if(obj.has(TAG_ERR)) { try { throw(new ParseErrorException(ParseErrorException.HABITRPG_REGISTRATION_ERROR, obj.getString(TAG_ERR))); } catch (JSONException e1) { e1.printStackTrace(); } } } public static String[] parseAuthenticationAnswer(JSONObject obj) throws ParseErrorException { parseError(obj); String api_t = null; String user_t = null; try { api_t = obj.getString(TAG_AUTH_API_TOKEN); user_t = obj.getString(TAG_AUTH_USER_TOKEN); //callback.onUserConnected(api_t, user_t); } catch (JSONException e) { throw(new ParseErrorException(ParseErrorException.HABITRPG_PARSING_ERROR_AUTH)); } String[] res = {api_t, user_t}; return res; } public static String[] parseRegistrationAnswer(JSONObject obj) throws ParseErrorException { parseError(obj); String api_t = null; String user_t = null; try { api_t = obj.getString(TAG_REG_API_TOKEN); user_t = obj.getString(TAG_REG_USER_TOKEN); String[] res = {api_t, user_t}; return res; } catch (JSONException e) { throw(new ParseErrorException(ParseErrorException.HABITRPG_PARSING_ERROR_REGISTRATION)); } } /** * returns the day string depending on the number * @param j the number * @return the first/two first letter of the day */ public static String whatDay(int j) { if(j==0) return "m"; else if(j==1) return "t"; else if(j==2) return "w"; else if(j==3) return "th"; else if(j==4) return "f"; else if(j==5) return "s"; else if(j==6) return "su"; return "su"; } public static boolean parseDeletedTask(JSONObject obj) throws ParseErrorException { parseError(obj); if(obj.has(TAG_TASK_DELETED)) { return true; } else { throw new ParseErrorException(ParseErrorException.TASK_NOT_DELETED); } } }
false
true
private static void parseUserInventory(JSONObject obj, User user) { List<String> pets, mounts, eggs, hatchingPotions, food; //Pets: try { JSONObject pets_json = obj.getJSONObject(TAG_ITEMS_PETS); JSONArray pets_array = pets_json.names(); pets = new ArrayList<String>(); for(int i = 0;i<pets_array.length()-1;i++) { if(pets_json.getInt(pets_array.getString(i))>=1) { pets.add(pets_array.getString(i)); } } user.setPets(pets); } catch (JSONException e) { e.printStackTrace(); } /*Mounts JSONArray mounts_array = obj.getJSONArray(TAG_ITEMS_MOUNTS);*/ try { //Eggs JSONObject eggs_json = obj.getJSONObject(TAG_ITEMS_EGGS); JSONArray eggs_array = eggs_json.names(); eggs = new ArrayList<String>(); for(int i = 0;i<eggs_array.length()-1;i++) { if(eggs_json.getInt(eggs_array.getString(i))>=1) { eggs.add(eggs_array.getString(i)); } } user.setEggs(eggs); } catch (JSONException e) { e.printStackTrace(); } try { //hatching potions JSONObject pot_json = obj.getJSONObject(TAG_ITEMS_HATCHING_POTIONS); JSONArray pot_array = pot_json.names(); hatchingPotions = new ArrayList<String>(); for(int i = 0;i<pot_array.length()-1;i++) { if(pot_json.getInt(pot_array.getString(i))>=1) { hatchingPotions.add(pot_array.getString(i)); } } user.setHatchingPotions(hatchingPotions); } catch (JSONException e) { e.printStackTrace(); } try { //food JSONObject food_json = obj.getJSONObject(TAG_ITEMS_FOOD); JSONArray food_array = food_json.names(); food = new ArrayList<String>(); for(int i = 0;i<food_array.length()-1;i++) { if(food_json.getInt(food_array.getString(i))>=1) { food.add(food_array.getString(i)); } } user.setFood(food); } catch (JSONException e) { e.printStackTrace(); } }
private static void parseUserInventory(JSONObject obj, User user) { List<String> pets, mounts, eggs, hatchingPotions, food; //Pets: try { JSONObject pets_json = obj.getJSONObject(TAG_ITEMS_PETS); JSONArray pets_array = pets_json.names(); pets = new ArrayList<String>(); if(pets_array != null && pets_array.length()>0) { for(int i = 0;i<pets_array.length()-1;i++) { if(pets_json.getInt(pets_array.getString(i))>=1) pets.add(pets_array.getString(i)); } } user.setPets(pets); } catch (JSONException e) { e.printStackTrace(); } /*Mounts JSONArray mounts_array = obj.getJSONArray(TAG_ITEMS_MOUNTS);*/ try { //Eggs JSONObject eggs_json = obj.getJSONObject(TAG_ITEMS_EGGS); JSONArray eggs_array = eggs_json.names(); eggs = new ArrayList<String>(); if(eggs_array != null && eggs_array.length()>0) { for(int i = 0;i<eggs_array.length()-1;i++) { if(eggs_json.getInt(eggs_array.getString(i))>=1) eggs.add(eggs_array.getString(i)); } } user.setEggs(eggs); } catch (JSONException e) { e.printStackTrace(); } try { //hatching potions JSONObject pot_json = obj.getJSONObject(TAG_ITEMS_HATCHING_POTIONS); JSONArray pot_array = pot_json.names(); hatchingPotions = new ArrayList<String>(); if(pot_array!=null && pot_array.length() > 0) { for(int i = 0;i<pot_array.length()-1;i++) { if(pot_json.getInt(pot_array.getString(i))>=1) hatchingPotions.add(pot_array.getString(i)); } } user.setHatchingPotions(hatchingPotions); } catch (JSONException e) { e.printStackTrace(); } try { //food JSONObject food_json = obj.getJSONObject(TAG_ITEMS_FOOD); JSONArray food_array = food_json.names(); food = new ArrayList<String>(); if(food_array!=null && food_array.length()>0) { for(int i = 0;i<food_array.length()-1;i++) { if(food_json.getInt(food_array.getString(i))>=1) food.add(food_array.getString(i)); } } user.setFood(food); } catch (JSONException e) { e.printStackTrace(); } }
diff --git a/src/main/javassist/bytecode/analysis/Executor.java b/src/main/javassist/bytecode/analysis/Executor.java index 7cf9a67..4ee5584 100644 --- a/src/main/javassist/bytecode/analysis/Executor.java +++ b/src/main/javassist/bytecode/analysis/Executor.java @@ -1,1012 +1,1012 @@ /* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999-2007 Shigeru Chiba, and others. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later. * * 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. */ package javassist.bytecode.analysis; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import javassist.bytecode.BadBytecode; import javassist.bytecode.CodeIterator; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import javassist.bytecode.MethodInfo; import javassist.bytecode.Opcode; /** * Executor is responsible for modeling the effects of a JVM instruction on a frame. * * @author Jason T. Greene */ public class Executor implements Opcode { private final ConstPool constPool; private final ClassPool classPool; private final Type STRING_TYPE; private final Type CLASS_TYPE; private final Type THROWABLE_TYPE; private int lastPos; public Executor(ClassPool classPool, ConstPool constPool) { this.constPool = constPool; this.classPool = classPool; try { STRING_TYPE = getType("java.lang.String"); CLASS_TYPE = getType("java.lang.Class"); THROWABLE_TYPE = getType("java.lang.Throwable"); } catch (Exception e) { throw new RuntimeException(e); } } /** * Execute the instruction, modeling the effects on the specified frame and subroutine. * If a subroutine is passed, the access flags will be modified if this instruction accesses * the local variable table. * * @param method the method containing the instruction * @param pos the position of the instruction in the method * @param iter the code iterator used to find the instruction * @param frame the frame to modify to represent the result of the instruction * @param subroutine the optional subroutine this instruction belongs to. * @throws BadBytecode if the bytecode violates the jvm spec */ public void execute(MethodInfo method, int pos, CodeIterator iter, Frame frame, Subroutine subroutine) throws BadBytecode { this.lastPos = pos; int opcode = iter.byteAt(pos); // Declared opcode in order switch (opcode) { case NOP: break; case ACONST_NULL: frame.push(Type.UNINIT); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: frame.push(Type.INTEGER); break; case LCONST_0: case LCONST_1: frame.push(Type.LONG); frame.push(Type.TOP); break; case FCONST_0: case FCONST_1: case FCONST_2: frame.push(Type.FLOAT); break; case DCONST_0: case DCONST_1: frame.push(Type.DOUBLE); frame.push(Type.TOP); break; case BIPUSH: case SIPUSH: frame.push(Type.INTEGER); break; case LDC: evalLDC(iter.byteAt(pos + 1), frame); break; case LDC_W : case LDC2_W : evalLDC(iter.u16bitAt(pos + 1), frame); break; case ILOAD: evalLoad(Type.INTEGER, iter.byteAt(pos + 1), frame, subroutine); break; case LLOAD: evalLoad(Type.LONG, iter.byteAt(pos + 1), frame, subroutine); break; case FLOAD: evalLoad(Type.FLOAT, iter.byteAt(pos + 1), frame, subroutine); break; case DLOAD: evalLoad(Type.DOUBLE, iter.byteAt(pos + 1), frame, subroutine); break; case ALOAD: evalLoad(Type.OBJECT, iter.byteAt(pos + 1), frame, subroutine); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: evalLoad(Type.INTEGER, opcode - ILOAD_0, frame, subroutine); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: evalLoad(Type.LONG, opcode - LLOAD_0, frame, subroutine); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: evalLoad(Type.FLOAT, opcode - FLOAD_0, frame, subroutine); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: evalLoad(Type.DOUBLE, opcode - DLOAD_0, frame, subroutine); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: evalLoad(Type.OBJECT, opcode - ALOAD_0, frame, subroutine); break; case IALOAD: evalArrayLoad(Type.INTEGER, frame); break; case LALOAD: evalArrayLoad(Type.LONG, frame); break; case FALOAD: evalArrayLoad(Type.FLOAT, frame); break; case DALOAD: evalArrayLoad(Type.DOUBLE, frame); break; case AALOAD: evalArrayLoad(Type.OBJECT, frame); break; case BALOAD: case CALOAD: case SALOAD: evalArrayLoad(Type.INTEGER, frame); break; case ISTORE: evalStore(Type.INTEGER, iter.byteAt(pos + 1), frame, subroutine); break; case LSTORE: evalStore(Type.LONG, iter.byteAt(pos + 1), frame, subroutine); break; case FSTORE: evalStore(Type.FLOAT, iter.byteAt(pos + 1), frame, subroutine); break; case DSTORE: evalStore(Type.DOUBLE, iter.byteAt(pos + 1), frame, subroutine); break; case ASTORE: evalStore(Type.OBJECT, iter.byteAt(pos + 1), frame, subroutine); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: evalStore(Type.INTEGER, opcode - ISTORE_0, frame, subroutine); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: evalStore(Type.LONG, opcode - LSTORE_0, frame, subroutine); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: evalStore(Type.FLOAT, opcode - FSTORE_0, frame, subroutine); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: evalStore(Type.DOUBLE, opcode - DSTORE_0, frame, subroutine); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: evalStore(Type.OBJECT, opcode - ASTORE_0, frame, subroutine); break; case IASTORE: evalArrayStore(Type.INTEGER, frame); break; case LASTORE: evalArrayStore(Type.LONG, frame); break; case FASTORE: evalArrayStore(Type.FLOAT, frame); break; case DASTORE: evalArrayStore(Type.DOUBLE, frame); break; case AASTORE: evalArrayStore(Type.OBJECT, frame); break; case BASTORE: case CASTORE: case SASTORE: evalArrayStore(Type.INTEGER, frame); break; case POP: if (frame.pop() == Type.TOP) throw new BadBytecode("POP can not be used with a category 2 value, pos = " + pos); break; case POP2: frame.pop(); frame.pop(); break; case DUP: { Type type = frame.peek(); if (type == Type.TOP) throw new BadBytecode("DUP can not be used with a category 2 value, pos = " + pos); frame.push(frame.peek()); break; } case DUP_X1: case DUP_X2: { Type type = frame.peek(); if (type == Type.TOP) throw new BadBytecode("DUP can not be used with a category 2 value, pos = " + pos); int end = frame.getTopIndex(); int insert = end - (opcode - DUP_X1) - 1; frame.push(type); while (end > insert) { frame.setStack(end, frame.getStack(end - 1)); end--; } frame.setStack(insert, type); break; } case DUP2: frame.push(frame.getStack(frame.getTopIndex() - 1)); frame.push(frame.getStack(frame.getTopIndex() - 1)); break; case DUP2_X1: case DUP2_X2: { int end = frame.getTopIndex(); int insert = end - (opcode - DUP2_X1) - 1; Type type1 = frame.getStack(frame.getTopIndex() - 1); Type type2 = frame.peek(); - frame.push(type1); - frame.push(type2); + frame.push(type1); + frame.push(type2); while (end > insert) { frame.setStack(end, frame.getStack(end - 2)); end--; } frame.setStack(insert, type2); frame.setStack(insert - 1, type1); break; } case SWAP: { Type type1 = frame.pop(); Type type2 = frame.pop(); if (type1.getSize() == 2 || type2.getSize() == 2) throw new BadBytecode("Swap can not be used with category 2 values, pos = " + pos); frame.push(type1); frame.push(type2); break; } // Math case IADD: evalBinaryMath(Type.INTEGER, frame); break; case LADD: evalBinaryMath(Type.LONG, frame); break; case FADD: evalBinaryMath(Type.FLOAT, frame); break; case DADD: evalBinaryMath(Type.DOUBLE, frame); break; case ISUB: evalBinaryMath(Type.INTEGER, frame); break; case LSUB: evalBinaryMath(Type.LONG, frame); break; case FSUB: evalBinaryMath(Type.FLOAT, frame); break; case DSUB: evalBinaryMath(Type.DOUBLE, frame); break; case IMUL: evalBinaryMath(Type.INTEGER, frame); break; case LMUL: evalBinaryMath(Type.LONG, frame); break; case FMUL: evalBinaryMath(Type.FLOAT, frame); break; case DMUL: evalBinaryMath(Type.DOUBLE, frame); break; case IDIV: evalBinaryMath(Type.INTEGER, frame); break; case LDIV: evalBinaryMath(Type.LONG, frame); break; case FDIV: evalBinaryMath(Type.FLOAT, frame); break; case DDIV: evalBinaryMath(Type.DOUBLE, frame); break; case IREM: evalBinaryMath(Type.INTEGER, frame); break; case LREM: evalBinaryMath(Type.LONG, frame); break; case FREM: evalBinaryMath(Type.FLOAT, frame); break; case DREM: evalBinaryMath(Type.DOUBLE, frame); break; // Unary case INEG: verifyAssignable(Type.INTEGER, simplePeek(frame)); break; case LNEG: verifyAssignable(Type.LONG, simplePeek(frame)); break; case FNEG: verifyAssignable(Type.FLOAT, simplePeek(frame)); break; case DNEG: verifyAssignable(Type.DOUBLE, simplePeek(frame)); break; // Shifts case ISHL: evalShift(Type.INTEGER, frame); break; case LSHL: evalShift(Type.LONG, frame); break; case ISHR: evalShift(Type.INTEGER, frame); break; case LSHR: evalShift(Type.LONG, frame); break; case IUSHR: evalShift(Type.INTEGER,frame); break; case LUSHR: evalShift(Type.LONG, frame); break; // Bitwise Math case IAND: evalBinaryMath(Type.INTEGER, frame); break; case LAND: evalBinaryMath(Type.LONG, frame); break; case IOR: evalBinaryMath(Type.INTEGER, frame); break; case LOR: evalBinaryMath(Type.LONG, frame); break; case IXOR: evalBinaryMath(Type.INTEGER, frame); break; case LXOR: evalBinaryMath(Type.LONG, frame); break; case IINC: { int index = iter.byteAt(pos + 1); verifyAssignable(Type.INTEGER, frame.getLocal(index)); access(index, Type.INTEGER, subroutine); break; } // Conversion case I2L: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.LONG, frame); break; case I2F: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case I2D: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case L2I: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case L2F: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case L2D: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case F2I: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case F2L: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.LONG, frame); break; case F2D: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case D2I: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case D2L: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.LONG, frame); break; case D2F: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case I2B: case I2C: case I2S: verifyAssignable(Type.INTEGER, frame.peek()); break; case LCMP: verifyAssignable(Type.LONG, simplePop(frame)); verifyAssignable(Type.LONG, simplePop(frame)); frame.push(Type.INTEGER); break; case FCMPL: case FCMPG: verifyAssignable(Type.FLOAT, simplePop(frame)); verifyAssignable(Type.FLOAT, simplePop(frame)); frame.push(Type.INTEGER); break; case DCMPL: case DCMPG: verifyAssignable(Type.DOUBLE, simplePop(frame)); verifyAssignable(Type.DOUBLE, simplePop(frame)); frame.push(Type.INTEGER); break; // Control flow case IFEQ: case IFNE: case IFLT: case IFGE: case IFGT: case IFLE: verifyAssignable(Type.INTEGER, simplePop(frame)); break; case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPGE: case IF_ICMPGT: case IF_ICMPLE: verifyAssignable(Type.INTEGER, simplePop(frame)); verifyAssignable(Type.INTEGER, simplePop(frame)); break; case IF_ACMPEQ: case IF_ACMPNE: verifyAssignable(Type.OBJECT, simplePop(frame)); verifyAssignable(Type.OBJECT, simplePop(frame)); break; case GOTO: break; case JSR: frame.push(Type.RETURN_ADDRESS); break; case RET: verifyAssignable(Type.RETURN_ADDRESS, frame.getLocal(iter.byteAt(pos + 1))); break; case TABLESWITCH: case LOOKUPSWITCH: case IRETURN: verifyAssignable(Type.INTEGER, simplePop(frame)); break; case LRETURN: verifyAssignable(Type.LONG, simplePop(frame)); break; case FRETURN: verifyAssignable(Type.FLOAT, simplePop(frame)); break; case DRETURN: verifyAssignable(Type.DOUBLE, simplePop(frame)); break; case ARETURN: try { CtClass returnType = Descriptor.getReturnType(method.getDescriptor(), classPool); verifyAssignable(Type.get(returnType), simplePop(frame)); } catch (NotFoundException e) { throw new RuntimeException(e); } break; case RETURN: break; case GETSTATIC: evalGetField(opcode, iter.u16bitAt(pos + 1), frame); break; case PUTSTATIC: evalPutField(opcode, iter.u16bitAt(pos + 1), frame); break; case GETFIELD: evalGetField(opcode, iter.u16bitAt(pos + 1), frame); break; case PUTFIELD: evalPutField(opcode, iter.u16bitAt(pos + 1), frame); break; case INVOKEVIRTUAL: case INVOKESPECIAL: case INVOKESTATIC: evalInvokeMethod(opcode, iter.u16bitAt(pos + 1), frame); break; case INVOKEINTERFACE: evalInvokeIntfMethod(opcode, iter.u16bitAt(pos + 1), frame); break; case 186: throw new RuntimeException("Bad opcode 186"); case NEW: frame.push(typeFromDesc(constPool.getClassInfo(iter.u16bitAt(pos + 1)))); break; case NEWARRAY: evalNewArray(pos, iter, frame); break; case ANEWARRAY: evalNewObjectArray(pos, iter, frame); break; case ARRAYLENGTH: { Type array = simplePop(frame); if (! array.isArray() && array != Type.UNINIT) throw new BadBytecode("Array length passed a non-array [pos = " + pos + "]: " + array); frame.push(Type.INTEGER); break; } case ATHROW: verifyAssignable(THROWABLE_TYPE, simplePop(frame)); break; case CHECKCAST: verifyAssignable(Type.OBJECT, simplePop(frame)); frame.push(typeFromDesc(constPool.getClassInfo(iter.u16bitAt(pos + 1)))); break; case INSTANCEOF: verifyAssignable(Type.OBJECT, simplePop(frame)); frame.push(Type.INTEGER); break; case MONITORENTER: case MONITOREXIT: verifyAssignable(Type.OBJECT, simplePop(frame)); break; case WIDE: evalWide(pos, iter, frame, subroutine); break; case MULTIANEWARRAY: evalNewObjectArray(pos, iter, frame); break; case IFNULL: case IFNONNULL: verifyAssignable(Type.OBJECT, simplePop(frame)); break; case GOTO_W: break; case JSR_W: frame.push(Type.RETURN_ADDRESS); break; } } private Type zeroExtend(Type type) { if (type == Type.SHORT || type == Type.BYTE || type == Type.CHAR || type == Type.BOOLEAN) return Type.INTEGER; return type; } private void evalArrayLoad(Type expectedComponent, Frame frame) throws BadBytecode { Type index = frame.pop(); Type array = frame.pop(); // Special case, an array defined by aconst_null // TODO - we might need to be more inteligent about this if (array == Type.UNINIT) { verifyAssignable(Type.INTEGER, index); if (expectedComponent == Type.OBJECT) { simplePush(Type.UNINIT, frame); } else { simplePush(expectedComponent, frame); } return; } Type component = array.getComponent(); if (component == null) throw new BadBytecode("Not an array! [pos = " + lastPos + "]: " + component); component = zeroExtend(component); verifyAssignable(expectedComponent, component); verifyAssignable(Type.INTEGER, index); simplePush(component, frame); } private void evalArrayStore(Type expectedComponent, Frame frame) throws BadBytecode { Type value = simplePop(frame); Type index = frame.pop(); Type array = frame.pop(); if (array == Type.UNINIT) { verifyAssignable(Type.INTEGER, index); return; } Type component = array.getComponent(); if (component == null) throw new BadBytecode("Not an array! [pos = " + lastPos + "]: " + component); component = zeroExtend(component); verifyAssignable(expectedComponent, component); verifyAssignable(Type.INTEGER, index); // This intentionally only checks for Object on aastore // downconverting of an array (no casts) // e.g. Object[] blah = new String[]; // blah[2] = (Object) "test"; // blah[3] = new Integer(); // compiler doesnt catch it (has legal bytecode), // // but will throw arraystoreexception if (expectedComponent == Type.OBJECT) { verifyAssignable(expectedComponent, value); } else { verifyAssignable(component, value); } } private void evalBinaryMath(Type expected, Frame frame) throws BadBytecode { Type value2 = simplePop(frame); Type value1 = simplePop(frame); verifyAssignable(expected, value2); verifyAssignable(expected, value1); simplePush(value1, frame); } private void evalGetField(int opcode, int index, Frame frame) throws BadBytecode { String desc = constPool.getFieldrefType(index); Type type = zeroExtend(typeFromDesc(desc)); if (opcode == GETFIELD) { Type objectType = typeFromDesc(constPool.getFieldrefClassName(index)); verifyAssignable(objectType, simplePop(frame)); } simplePush(type, frame); } private void evalInvokeIntfMethod(int opcode, int index, Frame frame) throws BadBytecode { String desc = constPool.getInterfaceMethodrefType(index); Type[] types = paramTypesFromDesc(desc); int i = types.length; while (i > 0) verifyAssignable(zeroExtend(types[--i]), simplePop(frame)); String classDesc = constPool.getInterfaceMethodrefClassName(index); Type objectType = typeFromDesc(classDesc); verifyAssignable(objectType, simplePop(frame)); Type returnType = returnTypeFromDesc(desc); if (returnType != Type.VOID) simplePush(zeroExtend(returnType), frame); } private void evalInvokeMethod(int opcode, int index, Frame frame) throws BadBytecode { String desc = constPool.getMethodrefType(index); Type[] types = paramTypesFromDesc(desc); int i = types.length; while (i > 0) verifyAssignable(zeroExtend(types[--i]), simplePop(frame)); if (opcode != INVOKESTATIC) { Type objectType = typeFromDesc(constPool.getMethodrefClassName(index)); verifyAssignable(objectType, simplePop(frame)); } Type returnType = returnTypeFromDesc(desc); if (returnType != Type.VOID) simplePush(zeroExtend(returnType), frame); } private void evalLDC(int index, Frame frame) throws BadBytecode { int tag = constPool.getTag(index); Type type; switch (tag) { case ConstPool.CONST_String: type = STRING_TYPE; break; case ConstPool.CONST_Integer: type = Type.INTEGER; break; case ConstPool.CONST_Float: type = Type.FLOAT; break; case ConstPool.CONST_Long: type = Type.LONG; break; case ConstPool.CONST_Double: type = Type.DOUBLE; break; case ConstPool.CONST_Class: type = CLASS_TYPE; break; default: throw new BadBytecode("bad LDC [pos = " + lastPos + "]: " + tag); } simplePush(type, frame); } private void evalLoad(Type expected, int index, Frame frame, Subroutine subroutine) throws BadBytecode { Type type = frame.getLocal(index); verifyAssignable(expected, type); simplePush(type, frame); access(index, type, subroutine); } private void evalNewArray(int pos, CodeIterator iter, Frame frame) throws BadBytecode { verifyAssignable(Type.INTEGER, simplePop(frame)); Type type = null; int typeInfo = iter.byteAt(pos + 1); switch (typeInfo) { case T_BOOLEAN: type = getType("boolean[]"); break; case T_CHAR: type = getType("char[]"); break; case T_BYTE: type = getType("byte[]"); break; case T_SHORT: type = getType("short[]"); break; case T_INT: type = getType("int[]"); break; case T_LONG: type = getType("long[]"); break; case T_FLOAT: type = getType("float[]"); break; case T_DOUBLE: type = getType("double[]"); break; default: throw new BadBytecode("Invalid array type [pos = " + pos + "]: " + typeInfo); } frame.push(type); } private void evalNewObjectArray(int pos, CodeIterator iter, Frame frame) throws BadBytecode { // Convert to x[] format Type type = typeFromDesc(constPool.getClassInfo(iter.u16bitAt(pos + 1))); String name = type.getCtClass().getName(); int opcode = iter.byteAt(pos); int dimensions; if (opcode == MULTIANEWARRAY) { dimensions = iter.byteAt(pos + 3); } else { name = name + "[]"; dimensions = 1; } while (dimensions-- > 0) { verifyAssignable(Type.INTEGER, simplePop(frame)); } simplePush(getType(name), frame); } private void evalPutField(int opcode, int index, Frame frame) throws BadBytecode { String desc = constPool.getFieldrefType(index); Type type = zeroExtend(typeFromDesc(desc)); verifyAssignable(type, simplePop(frame)); if (opcode == PUTFIELD) { Type objectType = typeFromDesc(constPool.getFieldrefClassName(index)); verifyAssignable(objectType, simplePop(frame)); } } private void evalShift(Type expected, Frame frame) throws BadBytecode { Type value2 = simplePop(frame); Type value1 = simplePop(frame); verifyAssignable(Type.INTEGER, value2); verifyAssignable(expected, value1); simplePush(value1, frame); } private void evalStore(Type expected, int index, Frame frame, Subroutine subroutine) throws BadBytecode { Type type = simplePop(frame); // RETURN_ADDRESS is allowed by ASTORE if (! (expected == Type.OBJECT && type == Type.RETURN_ADDRESS)) verifyAssignable(expected, type); simpleSetLocal(index, type, frame); access(index, type, subroutine); } private void evalWide(int pos, CodeIterator iter, Frame frame, Subroutine subroutine) throws BadBytecode { int opcode = iter.byteAt(pos + 1); int index = iter.u16bitAt(pos + 2); switch (opcode) { case ILOAD: evalLoad(Type.INTEGER, index, frame, subroutine); break; case LLOAD: evalLoad(Type.LONG, index, frame, subroutine); break; case FLOAD: evalLoad(Type.FLOAT, index, frame, subroutine); break; case DLOAD: evalLoad(Type.DOUBLE, index, frame, subroutine); break; case ALOAD: evalLoad(Type.OBJECT, index, frame, subroutine); break; case ISTORE: evalStore(Type.INTEGER, index, frame, subroutine); break; case LSTORE: evalStore(Type.LONG, index, frame, subroutine); break; case FSTORE: evalStore(Type.FLOAT, index, frame, subroutine); break; case DSTORE: evalStore(Type.DOUBLE, index, frame, subroutine); break; case ASTORE: evalStore(Type.OBJECT, index, frame, subroutine); break; case IINC: verifyAssignable(Type.INTEGER, frame.getLocal(index)); break; case RET: verifyAssignable(Type.RETURN_ADDRESS, frame.getLocal(index)); break; default: throw new BadBytecode("Invalid WIDE operand [pos = " + pos + "]: " + opcode); } } private Type getType(String name) throws BadBytecode { try { return Type.get(classPool.get(name)); } catch (NotFoundException e) { throw new BadBytecode("Could not find class [pos = " + lastPos + "]: " + name); } } private Type[] paramTypesFromDesc(String desc) throws BadBytecode { CtClass classes[] = null; try { classes = Descriptor.getParameterTypes(desc, classPool); } catch (NotFoundException e) { throw new BadBytecode("Could not find class in descriptor [pos = " + lastPos + "]: " + e.getMessage()); } if (classes == null) throw new BadBytecode("Could not obtain parameters for descriptor [pos = " + lastPos + "]: " + desc); Type[] types = new Type[classes.length]; for (int i = 0; i < types.length; i++) types[i] = Type.get(classes[i]); return types; } private Type returnTypeFromDesc(String desc) throws BadBytecode { CtClass clazz = null; try { clazz = Descriptor.getReturnType(desc, classPool); } catch (NotFoundException e) { throw new BadBytecode("Could not find class in descriptor [pos = " + lastPos + "]: " + e.getMessage()); } if (clazz == null) throw new BadBytecode("Could not obtain return type for descriptor [pos = " + lastPos + "]: " + desc); return Type.get(clazz); } private Type simplePeek(Frame frame) { Type type = frame.peek(); return (type == Type.TOP) ? frame.getStack(frame.getTopIndex() - 1) : type; } private Type simplePop(Frame frame) { Type type = frame.pop(); return (type == Type.TOP) ? frame.pop() : type; } private void simplePush(Type type, Frame frame) { frame.push(type); if (type.getSize() == 2) frame.push(Type.TOP); } private void access(int index, Type type, Subroutine subroutine) { if (subroutine == null) return; subroutine.access(index); if (type.getSize() == 2) subroutine.access(index + 1); } private void simpleSetLocal(int index, Type type, Frame frame) { frame.setLocal(index, type); if (type.getSize() == 2) frame.setLocal(index + 1, Type.TOP); } private Type typeFromDesc(String desc) throws BadBytecode { CtClass clazz = null; try { clazz = Descriptor.toCtClass(desc, classPool); } catch (NotFoundException e) { throw new BadBytecode("Could not find class in descriptor [pos = " + lastPos + "]: " + e.getMessage()); } if (clazz == null) throw new BadBytecode("Could not obtain type for descriptor [pos = " + lastPos + "]: " + desc); return Type.get(clazz); } private void verifyAssignable(Type expected, Type type) throws BadBytecode { if (! expected.isAssignableFrom(type)) throw new BadBytecode("Expected type: " + expected + " Got: " + type + " [pos = " + lastPos + "]"); } }
true
true
public void execute(MethodInfo method, int pos, CodeIterator iter, Frame frame, Subroutine subroutine) throws BadBytecode { this.lastPos = pos; int opcode = iter.byteAt(pos); // Declared opcode in order switch (opcode) { case NOP: break; case ACONST_NULL: frame.push(Type.UNINIT); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: frame.push(Type.INTEGER); break; case LCONST_0: case LCONST_1: frame.push(Type.LONG); frame.push(Type.TOP); break; case FCONST_0: case FCONST_1: case FCONST_2: frame.push(Type.FLOAT); break; case DCONST_0: case DCONST_1: frame.push(Type.DOUBLE); frame.push(Type.TOP); break; case BIPUSH: case SIPUSH: frame.push(Type.INTEGER); break; case LDC: evalLDC(iter.byteAt(pos + 1), frame); break; case LDC_W : case LDC2_W : evalLDC(iter.u16bitAt(pos + 1), frame); break; case ILOAD: evalLoad(Type.INTEGER, iter.byteAt(pos + 1), frame, subroutine); break; case LLOAD: evalLoad(Type.LONG, iter.byteAt(pos + 1), frame, subroutine); break; case FLOAD: evalLoad(Type.FLOAT, iter.byteAt(pos + 1), frame, subroutine); break; case DLOAD: evalLoad(Type.DOUBLE, iter.byteAt(pos + 1), frame, subroutine); break; case ALOAD: evalLoad(Type.OBJECT, iter.byteAt(pos + 1), frame, subroutine); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: evalLoad(Type.INTEGER, opcode - ILOAD_0, frame, subroutine); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: evalLoad(Type.LONG, opcode - LLOAD_0, frame, subroutine); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: evalLoad(Type.FLOAT, opcode - FLOAD_0, frame, subroutine); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: evalLoad(Type.DOUBLE, opcode - DLOAD_0, frame, subroutine); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: evalLoad(Type.OBJECT, opcode - ALOAD_0, frame, subroutine); break; case IALOAD: evalArrayLoad(Type.INTEGER, frame); break; case LALOAD: evalArrayLoad(Type.LONG, frame); break; case FALOAD: evalArrayLoad(Type.FLOAT, frame); break; case DALOAD: evalArrayLoad(Type.DOUBLE, frame); break; case AALOAD: evalArrayLoad(Type.OBJECT, frame); break; case BALOAD: case CALOAD: case SALOAD: evalArrayLoad(Type.INTEGER, frame); break; case ISTORE: evalStore(Type.INTEGER, iter.byteAt(pos + 1), frame, subroutine); break; case LSTORE: evalStore(Type.LONG, iter.byteAt(pos + 1), frame, subroutine); break; case FSTORE: evalStore(Type.FLOAT, iter.byteAt(pos + 1), frame, subroutine); break; case DSTORE: evalStore(Type.DOUBLE, iter.byteAt(pos + 1), frame, subroutine); break; case ASTORE: evalStore(Type.OBJECT, iter.byteAt(pos + 1), frame, subroutine); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: evalStore(Type.INTEGER, opcode - ISTORE_0, frame, subroutine); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: evalStore(Type.LONG, opcode - LSTORE_0, frame, subroutine); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: evalStore(Type.FLOAT, opcode - FSTORE_0, frame, subroutine); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: evalStore(Type.DOUBLE, opcode - DSTORE_0, frame, subroutine); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: evalStore(Type.OBJECT, opcode - ASTORE_0, frame, subroutine); break; case IASTORE: evalArrayStore(Type.INTEGER, frame); break; case LASTORE: evalArrayStore(Type.LONG, frame); break; case FASTORE: evalArrayStore(Type.FLOAT, frame); break; case DASTORE: evalArrayStore(Type.DOUBLE, frame); break; case AASTORE: evalArrayStore(Type.OBJECT, frame); break; case BASTORE: case CASTORE: case SASTORE: evalArrayStore(Type.INTEGER, frame); break; case POP: if (frame.pop() == Type.TOP) throw new BadBytecode("POP can not be used with a category 2 value, pos = " + pos); break; case POP2: frame.pop(); frame.pop(); break; case DUP: { Type type = frame.peek(); if (type == Type.TOP) throw new BadBytecode("DUP can not be used with a category 2 value, pos = " + pos); frame.push(frame.peek()); break; } case DUP_X1: case DUP_X2: { Type type = frame.peek(); if (type == Type.TOP) throw new BadBytecode("DUP can not be used with a category 2 value, pos = " + pos); int end = frame.getTopIndex(); int insert = end - (opcode - DUP_X1) - 1; frame.push(type); while (end > insert) { frame.setStack(end, frame.getStack(end - 1)); end--; } frame.setStack(insert, type); break; } case DUP2: frame.push(frame.getStack(frame.getTopIndex() - 1)); frame.push(frame.getStack(frame.getTopIndex() - 1)); break; case DUP2_X1: case DUP2_X2: { int end = frame.getTopIndex(); int insert = end - (opcode - DUP2_X1) - 1; Type type1 = frame.getStack(frame.getTopIndex() - 1); Type type2 = frame.peek(); frame.push(type1); frame.push(type2); while (end > insert) { frame.setStack(end, frame.getStack(end - 2)); end--; } frame.setStack(insert, type2); frame.setStack(insert - 1, type1); break; } case SWAP: { Type type1 = frame.pop(); Type type2 = frame.pop(); if (type1.getSize() == 2 || type2.getSize() == 2) throw new BadBytecode("Swap can not be used with category 2 values, pos = " + pos); frame.push(type1); frame.push(type2); break; } // Math case IADD: evalBinaryMath(Type.INTEGER, frame); break; case LADD: evalBinaryMath(Type.LONG, frame); break; case FADD: evalBinaryMath(Type.FLOAT, frame); break; case DADD: evalBinaryMath(Type.DOUBLE, frame); break; case ISUB: evalBinaryMath(Type.INTEGER, frame); break; case LSUB: evalBinaryMath(Type.LONG, frame); break; case FSUB: evalBinaryMath(Type.FLOAT, frame); break; case DSUB: evalBinaryMath(Type.DOUBLE, frame); break; case IMUL: evalBinaryMath(Type.INTEGER, frame); break; case LMUL: evalBinaryMath(Type.LONG, frame); break; case FMUL: evalBinaryMath(Type.FLOAT, frame); break; case DMUL: evalBinaryMath(Type.DOUBLE, frame); break; case IDIV: evalBinaryMath(Type.INTEGER, frame); break; case LDIV: evalBinaryMath(Type.LONG, frame); break; case FDIV: evalBinaryMath(Type.FLOAT, frame); break; case DDIV: evalBinaryMath(Type.DOUBLE, frame); break; case IREM: evalBinaryMath(Type.INTEGER, frame); break; case LREM: evalBinaryMath(Type.LONG, frame); break; case FREM: evalBinaryMath(Type.FLOAT, frame); break; case DREM: evalBinaryMath(Type.DOUBLE, frame); break; // Unary case INEG: verifyAssignable(Type.INTEGER, simplePeek(frame)); break; case LNEG: verifyAssignable(Type.LONG, simplePeek(frame)); break; case FNEG: verifyAssignable(Type.FLOAT, simplePeek(frame)); break; case DNEG: verifyAssignable(Type.DOUBLE, simplePeek(frame)); break; // Shifts case ISHL: evalShift(Type.INTEGER, frame); break; case LSHL: evalShift(Type.LONG, frame); break; case ISHR: evalShift(Type.INTEGER, frame); break; case LSHR: evalShift(Type.LONG, frame); break; case IUSHR: evalShift(Type.INTEGER,frame); break; case LUSHR: evalShift(Type.LONG, frame); break; // Bitwise Math case IAND: evalBinaryMath(Type.INTEGER, frame); break; case LAND: evalBinaryMath(Type.LONG, frame); break; case IOR: evalBinaryMath(Type.INTEGER, frame); break; case LOR: evalBinaryMath(Type.LONG, frame); break; case IXOR: evalBinaryMath(Type.INTEGER, frame); break; case LXOR: evalBinaryMath(Type.LONG, frame); break; case IINC: { int index = iter.byteAt(pos + 1); verifyAssignable(Type.INTEGER, frame.getLocal(index)); access(index, Type.INTEGER, subroutine); break; } // Conversion case I2L: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.LONG, frame); break; case I2F: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case I2D: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case L2I: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case L2F: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case L2D: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case F2I: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case F2L: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.LONG, frame); break; case F2D: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case D2I: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case D2L: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.LONG, frame); break; case D2F: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case I2B: case I2C: case I2S: verifyAssignable(Type.INTEGER, frame.peek()); break; case LCMP: verifyAssignable(Type.LONG, simplePop(frame)); verifyAssignable(Type.LONG, simplePop(frame)); frame.push(Type.INTEGER); break; case FCMPL: case FCMPG: verifyAssignable(Type.FLOAT, simplePop(frame)); verifyAssignable(Type.FLOAT, simplePop(frame)); frame.push(Type.INTEGER); break; case DCMPL: case DCMPG: verifyAssignable(Type.DOUBLE, simplePop(frame)); verifyAssignable(Type.DOUBLE, simplePop(frame)); frame.push(Type.INTEGER); break; // Control flow case IFEQ: case IFNE: case IFLT: case IFGE: case IFGT: case IFLE: verifyAssignable(Type.INTEGER, simplePop(frame)); break; case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPGE: case IF_ICMPGT: case IF_ICMPLE: verifyAssignable(Type.INTEGER, simplePop(frame)); verifyAssignable(Type.INTEGER, simplePop(frame)); break; case IF_ACMPEQ: case IF_ACMPNE: verifyAssignable(Type.OBJECT, simplePop(frame)); verifyAssignable(Type.OBJECT, simplePop(frame)); break; case GOTO: break; case JSR: frame.push(Type.RETURN_ADDRESS); break; case RET: verifyAssignable(Type.RETURN_ADDRESS, frame.getLocal(iter.byteAt(pos + 1))); break; case TABLESWITCH: case LOOKUPSWITCH: case IRETURN: verifyAssignable(Type.INTEGER, simplePop(frame)); break; case LRETURN: verifyAssignable(Type.LONG, simplePop(frame)); break; case FRETURN: verifyAssignable(Type.FLOAT, simplePop(frame)); break; case DRETURN: verifyAssignable(Type.DOUBLE, simplePop(frame)); break; case ARETURN: try { CtClass returnType = Descriptor.getReturnType(method.getDescriptor(), classPool); verifyAssignable(Type.get(returnType), simplePop(frame)); } catch (NotFoundException e) { throw new RuntimeException(e); } break; case RETURN: break; case GETSTATIC: evalGetField(opcode, iter.u16bitAt(pos + 1), frame); break; case PUTSTATIC: evalPutField(opcode, iter.u16bitAt(pos + 1), frame); break; case GETFIELD: evalGetField(opcode, iter.u16bitAt(pos + 1), frame); break; case PUTFIELD: evalPutField(opcode, iter.u16bitAt(pos + 1), frame); break; case INVOKEVIRTUAL: case INVOKESPECIAL: case INVOKESTATIC: evalInvokeMethod(opcode, iter.u16bitAt(pos + 1), frame); break; case INVOKEINTERFACE: evalInvokeIntfMethod(opcode, iter.u16bitAt(pos + 1), frame); break; case 186: throw new RuntimeException("Bad opcode 186"); case NEW: frame.push(typeFromDesc(constPool.getClassInfo(iter.u16bitAt(pos + 1)))); break; case NEWARRAY: evalNewArray(pos, iter, frame); break; case ANEWARRAY: evalNewObjectArray(pos, iter, frame); break; case ARRAYLENGTH: { Type array = simplePop(frame); if (! array.isArray() && array != Type.UNINIT) throw new BadBytecode("Array length passed a non-array [pos = " + pos + "]: " + array); frame.push(Type.INTEGER); break; } case ATHROW: verifyAssignable(THROWABLE_TYPE, simplePop(frame)); break; case CHECKCAST: verifyAssignable(Type.OBJECT, simplePop(frame)); frame.push(typeFromDesc(constPool.getClassInfo(iter.u16bitAt(pos + 1)))); break; case INSTANCEOF: verifyAssignable(Type.OBJECT, simplePop(frame)); frame.push(Type.INTEGER); break; case MONITORENTER: case MONITOREXIT: verifyAssignable(Type.OBJECT, simplePop(frame)); break; case WIDE: evalWide(pos, iter, frame, subroutine); break; case MULTIANEWARRAY: evalNewObjectArray(pos, iter, frame); break; case IFNULL: case IFNONNULL: verifyAssignable(Type.OBJECT, simplePop(frame)); break; case GOTO_W: break; case JSR_W: frame.push(Type.RETURN_ADDRESS); break; } }
public void execute(MethodInfo method, int pos, CodeIterator iter, Frame frame, Subroutine subroutine) throws BadBytecode { this.lastPos = pos; int opcode = iter.byteAt(pos); // Declared opcode in order switch (opcode) { case NOP: break; case ACONST_NULL: frame.push(Type.UNINIT); break; case ICONST_M1: case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: frame.push(Type.INTEGER); break; case LCONST_0: case LCONST_1: frame.push(Type.LONG); frame.push(Type.TOP); break; case FCONST_0: case FCONST_1: case FCONST_2: frame.push(Type.FLOAT); break; case DCONST_0: case DCONST_1: frame.push(Type.DOUBLE); frame.push(Type.TOP); break; case BIPUSH: case SIPUSH: frame.push(Type.INTEGER); break; case LDC: evalLDC(iter.byteAt(pos + 1), frame); break; case LDC_W : case LDC2_W : evalLDC(iter.u16bitAt(pos + 1), frame); break; case ILOAD: evalLoad(Type.INTEGER, iter.byteAt(pos + 1), frame, subroutine); break; case LLOAD: evalLoad(Type.LONG, iter.byteAt(pos + 1), frame, subroutine); break; case FLOAD: evalLoad(Type.FLOAT, iter.byteAt(pos + 1), frame, subroutine); break; case DLOAD: evalLoad(Type.DOUBLE, iter.byteAt(pos + 1), frame, subroutine); break; case ALOAD: evalLoad(Type.OBJECT, iter.byteAt(pos + 1), frame, subroutine); break; case ILOAD_0: case ILOAD_1: case ILOAD_2: case ILOAD_3: evalLoad(Type.INTEGER, opcode - ILOAD_0, frame, subroutine); break; case LLOAD_0: case LLOAD_1: case LLOAD_2: case LLOAD_3: evalLoad(Type.LONG, opcode - LLOAD_0, frame, subroutine); break; case FLOAD_0: case FLOAD_1: case FLOAD_2: case FLOAD_3: evalLoad(Type.FLOAT, opcode - FLOAD_0, frame, subroutine); break; case DLOAD_0: case DLOAD_1: case DLOAD_2: case DLOAD_3: evalLoad(Type.DOUBLE, opcode - DLOAD_0, frame, subroutine); break; case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: evalLoad(Type.OBJECT, opcode - ALOAD_0, frame, subroutine); break; case IALOAD: evalArrayLoad(Type.INTEGER, frame); break; case LALOAD: evalArrayLoad(Type.LONG, frame); break; case FALOAD: evalArrayLoad(Type.FLOAT, frame); break; case DALOAD: evalArrayLoad(Type.DOUBLE, frame); break; case AALOAD: evalArrayLoad(Type.OBJECT, frame); break; case BALOAD: case CALOAD: case SALOAD: evalArrayLoad(Type.INTEGER, frame); break; case ISTORE: evalStore(Type.INTEGER, iter.byteAt(pos + 1), frame, subroutine); break; case LSTORE: evalStore(Type.LONG, iter.byteAt(pos + 1), frame, subroutine); break; case FSTORE: evalStore(Type.FLOAT, iter.byteAt(pos + 1), frame, subroutine); break; case DSTORE: evalStore(Type.DOUBLE, iter.byteAt(pos + 1), frame, subroutine); break; case ASTORE: evalStore(Type.OBJECT, iter.byteAt(pos + 1), frame, subroutine); break; case ISTORE_0: case ISTORE_1: case ISTORE_2: case ISTORE_3: evalStore(Type.INTEGER, opcode - ISTORE_0, frame, subroutine); break; case LSTORE_0: case LSTORE_1: case LSTORE_2: case LSTORE_3: evalStore(Type.LONG, opcode - LSTORE_0, frame, subroutine); break; case FSTORE_0: case FSTORE_1: case FSTORE_2: case FSTORE_3: evalStore(Type.FLOAT, opcode - FSTORE_0, frame, subroutine); break; case DSTORE_0: case DSTORE_1: case DSTORE_2: case DSTORE_3: evalStore(Type.DOUBLE, opcode - DSTORE_0, frame, subroutine); break; case ASTORE_0: case ASTORE_1: case ASTORE_2: case ASTORE_3: evalStore(Type.OBJECT, opcode - ASTORE_0, frame, subroutine); break; case IASTORE: evalArrayStore(Type.INTEGER, frame); break; case LASTORE: evalArrayStore(Type.LONG, frame); break; case FASTORE: evalArrayStore(Type.FLOAT, frame); break; case DASTORE: evalArrayStore(Type.DOUBLE, frame); break; case AASTORE: evalArrayStore(Type.OBJECT, frame); break; case BASTORE: case CASTORE: case SASTORE: evalArrayStore(Type.INTEGER, frame); break; case POP: if (frame.pop() == Type.TOP) throw new BadBytecode("POP can not be used with a category 2 value, pos = " + pos); break; case POP2: frame.pop(); frame.pop(); break; case DUP: { Type type = frame.peek(); if (type == Type.TOP) throw new BadBytecode("DUP can not be used with a category 2 value, pos = " + pos); frame.push(frame.peek()); break; } case DUP_X1: case DUP_X2: { Type type = frame.peek(); if (type == Type.TOP) throw new BadBytecode("DUP can not be used with a category 2 value, pos = " + pos); int end = frame.getTopIndex(); int insert = end - (opcode - DUP_X1) - 1; frame.push(type); while (end > insert) { frame.setStack(end, frame.getStack(end - 1)); end--; } frame.setStack(insert, type); break; } case DUP2: frame.push(frame.getStack(frame.getTopIndex() - 1)); frame.push(frame.getStack(frame.getTopIndex() - 1)); break; case DUP2_X1: case DUP2_X2: { int end = frame.getTopIndex(); int insert = end - (opcode - DUP2_X1) - 1; Type type1 = frame.getStack(frame.getTopIndex() - 1); Type type2 = frame.peek(); frame.push(type1); frame.push(type2); while (end > insert) { frame.setStack(end, frame.getStack(end - 2)); end--; } frame.setStack(insert, type2); frame.setStack(insert - 1, type1); break; } case SWAP: { Type type1 = frame.pop(); Type type2 = frame.pop(); if (type1.getSize() == 2 || type2.getSize() == 2) throw new BadBytecode("Swap can not be used with category 2 values, pos = " + pos); frame.push(type1); frame.push(type2); break; } // Math case IADD: evalBinaryMath(Type.INTEGER, frame); break; case LADD: evalBinaryMath(Type.LONG, frame); break; case FADD: evalBinaryMath(Type.FLOAT, frame); break; case DADD: evalBinaryMath(Type.DOUBLE, frame); break; case ISUB: evalBinaryMath(Type.INTEGER, frame); break; case LSUB: evalBinaryMath(Type.LONG, frame); break; case FSUB: evalBinaryMath(Type.FLOAT, frame); break; case DSUB: evalBinaryMath(Type.DOUBLE, frame); break; case IMUL: evalBinaryMath(Type.INTEGER, frame); break; case LMUL: evalBinaryMath(Type.LONG, frame); break; case FMUL: evalBinaryMath(Type.FLOAT, frame); break; case DMUL: evalBinaryMath(Type.DOUBLE, frame); break; case IDIV: evalBinaryMath(Type.INTEGER, frame); break; case LDIV: evalBinaryMath(Type.LONG, frame); break; case FDIV: evalBinaryMath(Type.FLOAT, frame); break; case DDIV: evalBinaryMath(Type.DOUBLE, frame); break; case IREM: evalBinaryMath(Type.INTEGER, frame); break; case LREM: evalBinaryMath(Type.LONG, frame); break; case FREM: evalBinaryMath(Type.FLOAT, frame); break; case DREM: evalBinaryMath(Type.DOUBLE, frame); break; // Unary case INEG: verifyAssignable(Type.INTEGER, simplePeek(frame)); break; case LNEG: verifyAssignable(Type.LONG, simplePeek(frame)); break; case FNEG: verifyAssignable(Type.FLOAT, simplePeek(frame)); break; case DNEG: verifyAssignable(Type.DOUBLE, simplePeek(frame)); break; // Shifts case ISHL: evalShift(Type.INTEGER, frame); break; case LSHL: evalShift(Type.LONG, frame); break; case ISHR: evalShift(Type.INTEGER, frame); break; case LSHR: evalShift(Type.LONG, frame); break; case IUSHR: evalShift(Type.INTEGER,frame); break; case LUSHR: evalShift(Type.LONG, frame); break; // Bitwise Math case IAND: evalBinaryMath(Type.INTEGER, frame); break; case LAND: evalBinaryMath(Type.LONG, frame); break; case IOR: evalBinaryMath(Type.INTEGER, frame); break; case LOR: evalBinaryMath(Type.LONG, frame); break; case IXOR: evalBinaryMath(Type.INTEGER, frame); break; case LXOR: evalBinaryMath(Type.LONG, frame); break; case IINC: { int index = iter.byteAt(pos + 1); verifyAssignable(Type.INTEGER, frame.getLocal(index)); access(index, Type.INTEGER, subroutine); break; } // Conversion case I2L: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.LONG, frame); break; case I2F: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case I2D: verifyAssignable(Type.INTEGER, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case L2I: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case L2F: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case L2D: verifyAssignable(Type.LONG, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case F2I: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case F2L: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.LONG, frame); break; case F2D: verifyAssignable(Type.FLOAT, simplePop(frame)); simplePush(Type.DOUBLE, frame); break; case D2I: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.INTEGER, frame); break; case D2L: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.LONG, frame); break; case D2F: verifyAssignable(Type.DOUBLE, simplePop(frame)); simplePush(Type.FLOAT, frame); break; case I2B: case I2C: case I2S: verifyAssignable(Type.INTEGER, frame.peek()); break; case LCMP: verifyAssignable(Type.LONG, simplePop(frame)); verifyAssignable(Type.LONG, simplePop(frame)); frame.push(Type.INTEGER); break; case FCMPL: case FCMPG: verifyAssignable(Type.FLOAT, simplePop(frame)); verifyAssignable(Type.FLOAT, simplePop(frame)); frame.push(Type.INTEGER); break; case DCMPL: case DCMPG: verifyAssignable(Type.DOUBLE, simplePop(frame)); verifyAssignable(Type.DOUBLE, simplePop(frame)); frame.push(Type.INTEGER); break; // Control flow case IFEQ: case IFNE: case IFLT: case IFGE: case IFGT: case IFLE: verifyAssignable(Type.INTEGER, simplePop(frame)); break; case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPGE: case IF_ICMPGT: case IF_ICMPLE: verifyAssignable(Type.INTEGER, simplePop(frame)); verifyAssignable(Type.INTEGER, simplePop(frame)); break; case IF_ACMPEQ: case IF_ACMPNE: verifyAssignable(Type.OBJECT, simplePop(frame)); verifyAssignable(Type.OBJECT, simplePop(frame)); break; case GOTO: break; case JSR: frame.push(Type.RETURN_ADDRESS); break; case RET: verifyAssignable(Type.RETURN_ADDRESS, frame.getLocal(iter.byteAt(pos + 1))); break; case TABLESWITCH: case LOOKUPSWITCH: case IRETURN: verifyAssignable(Type.INTEGER, simplePop(frame)); break; case LRETURN: verifyAssignable(Type.LONG, simplePop(frame)); break; case FRETURN: verifyAssignable(Type.FLOAT, simplePop(frame)); break; case DRETURN: verifyAssignable(Type.DOUBLE, simplePop(frame)); break; case ARETURN: try { CtClass returnType = Descriptor.getReturnType(method.getDescriptor(), classPool); verifyAssignable(Type.get(returnType), simplePop(frame)); } catch (NotFoundException e) { throw new RuntimeException(e); } break; case RETURN: break; case GETSTATIC: evalGetField(opcode, iter.u16bitAt(pos + 1), frame); break; case PUTSTATIC: evalPutField(opcode, iter.u16bitAt(pos + 1), frame); break; case GETFIELD: evalGetField(opcode, iter.u16bitAt(pos + 1), frame); break; case PUTFIELD: evalPutField(opcode, iter.u16bitAt(pos + 1), frame); break; case INVOKEVIRTUAL: case INVOKESPECIAL: case INVOKESTATIC: evalInvokeMethod(opcode, iter.u16bitAt(pos + 1), frame); break; case INVOKEINTERFACE: evalInvokeIntfMethod(opcode, iter.u16bitAt(pos + 1), frame); break; case 186: throw new RuntimeException("Bad opcode 186"); case NEW: frame.push(typeFromDesc(constPool.getClassInfo(iter.u16bitAt(pos + 1)))); break; case NEWARRAY: evalNewArray(pos, iter, frame); break; case ANEWARRAY: evalNewObjectArray(pos, iter, frame); break; case ARRAYLENGTH: { Type array = simplePop(frame); if (! array.isArray() && array != Type.UNINIT) throw new BadBytecode("Array length passed a non-array [pos = " + pos + "]: " + array); frame.push(Type.INTEGER); break; } case ATHROW: verifyAssignable(THROWABLE_TYPE, simplePop(frame)); break; case CHECKCAST: verifyAssignable(Type.OBJECT, simplePop(frame)); frame.push(typeFromDesc(constPool.getClassInfo(iter.u16bitAt(pos + 1)))); break; case INSTANCEOF: verifyAssignable(Type.OBJECT, simplePop(frame)); frame.push(Type.INTEGER); break; case MONITORENTER: case MONITOREXIT: verifyAssignable(Type.OBJECT, simplePop(frame)); break; case WIDE: evalWide(pos, iter, frame, subroutine); break; case MULTIANEWARRAY: evalNewObjectArray(pos, iter, frame); break; case IFNULL: case IFNONNULL: verifyAssignable(Type.OBJECT, simplePop(frame)); break; case GOTO_W: break; case JSR_W: frame.push(Type.RETURN_ADDRESS); break; } }
diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jpql/expressions/TestEntityTypeExpression.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jpql/expressions/TestEntityTypeExpression.java index 8a336ff96..ceba5c665 100644 --- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jpql/expressions/TestEntityTypeExpression.java +++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jpql/expressions/TestEntityTypeExpression.java @@ -1,215 +1,222 @@ /* * 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.openjpa.persistence.jpql.expressions; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.persistence.EntityManager; import org.apache.openjpa.persistence.common.apps.*; import org.apache.openjpa.persistence.common.utils.AbstractTestCase; public class TestEntityTypeExpression extends AbstractTestCase { private int userid1, userid2, userid3, userid4, userid5, userid6; public TestEntityTypeExpression(String name) { super(name, "jpqlclausescactusapp"); } public void setUp() { deleteAll(CompUser.class); EntityManager em = currentEntityManager(); startTx(em); Address[] add = new Address[]{ new Address("43 Sansome", "SF", "United-Kingdom", "94104"), new Address("24 Mink", "ANTIOCH", "USA", "94513"), new Address("23 Ogbete", "CoalCamp", "NIGERIA", "00000"), new Address("10 Wilshire", "Worcester", "CANADA", "80080"), new Address("23 Bellflower", "Ogui", null, "02000"), new Address("22 Montgomery", "SF", null, "50054") }; CompUser user1 = createUser("Seetha", "MAC", add[0], 36, true); CompUser user2 = createUser("Shannon", "PC", add[1], 36, false); CompUser user3 = createUser("Ugo", "PC", add[2], 19, true); CompUser user4 = createUser("Jacob", "LINUX", add[3], 10, true); CompUser user5 = createUser("Famzy", "UNIX", add[4], 29, false); CompUser user6 = createUser("Shade", "UNIX", add[5], 23, false); em.persist(user1); userid1 = user1.getUserid(); em.persist(user2); userid2 = user2.getUserid(); em.persist(user3); userid3 = user3.getUserid(); em.persist(user4); userid4 = user4.getUserid(); em.persist(user5); userid5 = user5.getUserid(); em.persist(user6); userid6 = user6.getUserid(); endTx(em); endEm(em); } @SuppressWarnings("unchecked") public void testTypeExpression() { EntityManager em = currentEntityManager(); String query = null; List<CompUser> rs = null; CompUser user = null; // test collection-valued input parameters in in-expressions Collection params = new ArrayList(2); params.add(FemaleUser.class); params.add(MaleUser.class); Collection params2 = new ArrayList(3); params2.add(36); params2.add(29); params2.add(19); String param3 = "PC"; query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2" + " and e.computerName = ?3 ORDER By e.name"; rs = em.createQuery(query). setParameter(1, params). setParameter(2, params2). setParameter(3, param3).getResultList(); user = rs.get(0); assertEquals("Shannon", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2 ORDER By e.name"; rs = em.createQuery(query). setParameter(1, params). setParameter(2, params2).getResultList(); user = rs.get(0); assertEquals("Famzy", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in :params ORDER BY e.age"; rs = em.createQuery(query). setParameter("params", params).getResultList(); user = rs.get(0); assertEquals("Jacob", user.getName()); query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = MaleUser"; rs = em.createQuery(query).getResultList(); Object type = rs.get(0); assertEquals(type, MaleUser.class); query = "SELECT TYPE(e) FROM CompUser e where TYPE(e) = ?1"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).getResultList(); type = rs.get(0); assertEquals(type, FemaleUser.class); query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = ?1"; rs = em.createQuery(query). setParameter(1, MaleUser.class).getResultList(); type = rs.get(0); assertEquals(type, MaleUser.class); query = "SELECT e, FemaleUser, a FROM Address a, FemaleUser e " + " where e.address IS NOT NULL"; List<Object> rs2 = em.createQuery(query).getResultList(); type = ((Object[]) rs2.get(0))[1]; assertEquals(type, FemaleUser.class); - query = "SELECT e FROM CompUser e where TYPE(e) = :typeName"; + query = "SELECT e FROM CompUser e where TYPE(e) = :typeName " + + " ORDER BY e.name"; rs = em.createQuery(query). setParameter("typeName", FemaleUser.class).getResultList(); + assertTrue(rs.size()==3); user = rs.get(0); + assertEquals("Famzy", user.getName()); + user = rs.get(1); + assertEquals("Shade", user.getName()); + user = rs.get(2); assertEquals("Shannon", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) = ?1 ORDER BY e.name"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).getResultList(); user = rs.get(0); assertEquals("Famzy", user.getName()); - query = "SELECT e FROM CompUser e where TYPE(e) in (?1) ORDER BY e.name DESC"; + query = "SELECT e FROM CompUser e where TYPE(e) in (?1)" + + " ORDER BY e.name DESC"; rs = em.createQuery(query). setParameter(1, MaleUser.class).getResultList(); user = rs.get(0); assertEquals("Ugo", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in (?1, ?2)" + " ORDER BY e.name DESC"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).setParameter(2, MaleUser.class). getResultList(); user = rs.get(0); assertEquals("Ugo", user.getName()); query = "select sum(e.age) FROM CompUser e GROUP BY e.age" + " HAVING ABS(e.age) = :param"; Long sum = (Long) em.createQuery(query). setParameter("param", new Double(36)).getSingleResult(); assertEquals(sum.intValue(), 72); String[] queries = { "SELECT e FROM CompUser e where TYPE(e) = MaleUser", "SELECT e from CompUser e where TYPE(e) in (FemaleUser)", "SELECT e from CompUser e where TYPE(e) not in (FemaleUser)", "SELECT e from CompUser e where TYPE(e) in (MaleUser, FemaleUser)", "SELECT TYPE(e) FROM CompUser e where TYPE(e) = MaleUser", "SELECT TYPE(e) FROM CompUser e", "SELECT TYPE(a.user) FROM Address a", "SELECT MaleUser FROM CompUser e", "SELECT MaleUser FROM Address a", "SELECT " + " CASE TYPE(e) WHEN FemaleUser THEN 'Female' " + " ELSE 'Male' " + " END " + " FROM CompUser e", }; for (int i = 0; i < queries.length; i++) { query = queries[i]; List<Object> rs1 = em.createQuery(query).getResultList(); Object obj = rs1.get(0); obj.toString(); } endEm(em); } public CompUser createUser(String name, String cName, Address add, int age, boolean isMale) { CompUser user = null; if (isMale) { user = new MaleUser(); user.setName(name); user.setComputerName(cName); user.setAddress(add); user.setAge(age); } else { user = new FemaleUser(); user.setName(name); user.setComputerName(cName); user.setAddress(add); user.setAge(age); } return user; } }
false
true
public void testTypeExpression() { EntityManager em = currentEntityManager(); String query = null; List<CompUser> rs = null; CompUser user = null; // test collection-valued input parameters in in-expressions Collection params = new ArrayList(2); params.add(FemaleUser.class); params.add(MaleUser.class); Collection params2 = new ArrayList(3); params2.add(36); params2.add(29); params2.add(19); String param3 = "PC"; query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2" + " and e.computerName = ?3 ORDER By e.name"; rs = em.createQuery(query). setParameter(1, params). setParameter(2, params2). setParameter(3, param3).getResultList(); user = rs.get(0); assertEquals("Shannon", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2 ORDER By e.name"; rs = em.createQuery(query). setParameter(1, params). setParameter(2, params2).getResultList(); user = rs.get(0); assertEquals("Famzy", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in :params ORDER BY e.age"; rs = em.createQuery(query). setParameter("params", params).getResultList(); user = rs.get(0); assertEquals("Jacob", user.getName()); query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = MaleUser"; rs = em.createQuery(query).getResultList(); Object type = rs.get(0); assertEquals(type, MaleUser.class); query = "SELECT TYPE(e) FROM CompUser e where TYPE(e) = ?1"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).getResultList(); type = rs.get(0); assertEquals(type, FemaleUser.class); query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = ?1"; rs = em.createQuery(query). setParameter(1, MaleUser.class).getResultList(); type = rs.get(0); assertEquals(type, MaleUser.class); query = "SELECT e, FemaleUser, a FROM Address a, FemaleUser e " + " where e.address IS NOT NULL"; List<Object> rs2 = em.createQuery(query).getResultList(); type = ((Object[]) rs2.get(0))[1]; assertEquals(type, FemaleUser.class); query = "SELECT e FROM CompUser e where TYPE(e) = :typeName"; rs = em.createQuery(query). setParameter("typeName", FemaleUser.class).getResultList(); user = rs.get(0); assertEquals("Shannon", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) = ?1 ORDER BY e.name"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).getResultList(); user = rs.get(0); assertEquals("Famzy", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in (?1) ORDER BY e.name DESC"; rs = em.createQuery(query). setParameter(1, MaleUser.class).getResultList(); user = rs.get(0); assertEquals("Ugo", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in (?1, ?2)" + " ORDER BY e.name DESC"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).setParameter(2, MaleUser.class). getResultList(); user = rs.get(0); assertEquals("Ugo", user.getName()); query = "select sum(e.age) FROM CompUser e GROUP BY e.age" + " HAVING ABS(e.age) = :param"; Long sum = (Long) em.createQuery(query). setParameter("param", new Double(36)).getSingleResult(); assertEquals(sum.intValue(), 72); String[] queries = { "SELECT e FROM CompUser e where TYPE(e) = MaleUser", "SELECT e from CompUser e where TYPE(e) in (FemaleUser)", "SELECT e from CompUser e where TYPE(e) not in (FemaleUser)", "SELECT e from CompUser e where TYPE(e) in (MaleUser, FemaleUser)", "SELECT TYPE(e) FROM CompUser e where TYPE(e) = MaleUser", "SELECT TYPE(e) FROM CompUser e", "SELECT TYPE(a.user) FROM Address a", "SELECT MaleUser FROM CompUser e", "SELECT MaleUser FROM Address a", "SELECT " + " CASE TYPE(e) WHEN FemaleUser THEN 'Female' " + " ELSE 'Male' " + " END " + " FROM CompUser e", }; for (int i = 0; i < queries.length; i++) { query = queries[i]; List<Object> rs1 = em.createQuery(query).getResultList(); Object obj = rs1.get(0); obj.toString(); } endEm(em); }
public void testTypeExpression() { EntityManager em = currentEntityManager(); String query = null; List<CompUser> rs = null; CompUser user = null; // test collection-valued input parameters in in-expressions Collection params = new ArrayList(2); params.add(FemaleUser.class); params.add(MaleUser.class); Collection params2 = new ArrayList(3); params2.add(36); params2.add(29); params2.add(19); String param3 = "PC"; query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2" + " and e.computerName = ?3 ORDER By e.name"; rs = em.createQuery(query). setParameter(1, params). setParameter(2, params2). setParameter(3, param3).getResultList(); user = rs.get(0); assertEquals("Shannon", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2 ORDER By e.name"; rs = em.createQuery(query). setParameter(1, params). setParameter(2, params2).getResultList(); user = rs.get(0); assertEquals("Famzy", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in :params ORDER BY e.age"; rs = em.createQuery(query). setParameter("params", params).getResultList(); user = rs.get(0); assertEquals("Jacob", user.getName()); query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = MaleUser"; rs = em.createQuery(query).getResultList(); Object type = rs.get(0); assertEquals(type, MaleUser.class); query = "SELECT TYPE(e) FROM CompUser e where TYPE(e) = ?1"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).getResultList(); type = rs.get(0); assertEquals(type, FemaleUser.class); query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = ?1"; rs = em.createQuery(query). setParameter(1, MaleUser.class).getResultList(); type = rs.get(0); assertEquals(type, MaleUser.class); query = "SELECT e, FemaleUser, a FROM Address a, FemaleUser e " + " where e.address IS NOT NULL"; List<Object> rs2 = em.createQuery(query).getResultList(); type = ((Object[]) rs2.get(0))[1]; assertEquals(type, FemaleUser.class); query = "SELECT e FROM CompUser e where TYPE(e) = :typeName " + " ORDER BY e.name"; rs = em.createQuery(query). setParameter("typeName", FemaleUser.class).getResultList(); assertTrue(rs.size()==3); user = rs.get(0); assertEquals("Famzy", user.getName()); user = rs.get(1); assertEquals("Shade", user.getName()); user = rs.get(2); assertEquals("Shannon", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) = ?1 ORDER BY e.name"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).getResultList(); user = rs.get(0); assertEquals("Famzy", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in (?1)" + " ORDER BY e.name DESC"; rs = em.createQuery(query). setParameter(1, MaleUser.class).getResultList(); user = rs.get(0); assertEquals("Ugo", user.getName()); query = "SELECT e FROM CompUser e where TYPE(e) in (?1, ?2)" + " ORDER BY e.name DESC"; rs = em.createQuery(query). setParameter(1, FemaleUser.class).setParameter(2, MaleUser.class). getResultList(); user = rs.get(0); assertEquals("Ugo", user.getName()); query = "select sum(e.age) FROM CompUser e GROUP BY e.age" + " HAVING ABS(e.age) = :param"; Long sum = (Long) em.createQuery(query). setParameter("param", new Double(36)).getSingleResult(); assertEquals(sum.intValue(), 72); String[] queries = { "SELECT e FROM CompUser e where TYPE(e) = MaleUser", "SELECT e from CompUser e where TYPE(e) in (FemaleUser)", "SELECT e from CompUser e where TYPE(e) not in (FemaleUser)", "SELECT e from CompUser e where TYPE(e) in (MaleUser, FemaleUser)", "SELECT TYPE(e) FROM CompUser e where TYPE(e) = MaleUser", "SELECT TYPE(e) FROM CompUser e", "SELECT TYPE(a.user) FROM Address a", "SELECT MaleUser FROM CompUser e", "SELECT MaleUser FROM Address a", "SELECT " + " CASE TYPE(e) WHEN FemaleUser THEN 'Female' " + " ELSE 'Male' " + " END " + " FROM CompUser e", }; for (int i = 0; i < queries.length; i++) { query = queries[i]; List<Object> rs1 = em.createQuery(query).getResultList(); Object obj = rs1.get(0); obj.toString(); } endEm(em); }
diff --git a/src/main/java/org/waarp/openr66/context/task/TransferTask.java b/src/main/java/org/waarp/openr66/context/task/TransferTask.java index 1abef42a..acf9dde9 100644 --- a/src/main/java/org/waarp/openr66/context/task/TransferTask.java +++ b/src/main/java/org/waarp/openr66/context/task/TransferTask.java @@ -1,171 +1,174 @@ /** * This file is part of Waarp Project. * * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the * COPYRIGHT.txt in the distribution for a full listing of individual contributors. * * All Waarp Project 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. * * Waarp 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 Waarp . If not, see * <http://www.gnu.org/licenses/>. */ package org.waarp.openr66.context.task; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.waarp.common.logging.WaarpInternalLogger; import org.waarp.common.logging.WaarpInternalLoggerFactory; import org.waarp.openr66.client.SubmitTransfer; import org.waarp.openr66.context.R66Session; import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.database.data.DbTaskRunner; import org.waarp.openr66.protocol.configuration.Configuration; import org.waarp.openr66.protocol.utils.R66Future; /** * Transfer task:<br> * * Result of arguments will be as r66send command.<br> * Format is like r66send command in any order except "-info" which should be the last item:<br> * "-file filepath -to requestedHost -rule rule [-md5] [-start yyyyMMddHHmmss or -delay (delay or +delay)] [-info information]" * <br> * <br> * INFO is the only one field that can contains blank character.<br> * * @author Frederic Bregier * */ public class TransferTask extends AbstractTask { /** * Internal Logger */ private static final WaarpInternalLogger logger = WaarpInternalLoggerFactory .getLogger(TransferTask.class); /** * @param argRule * @param delay * @param argTransfer * @param session */ public TransferTask(String argRule, int delay, String argTransfer, R66Session session) { super(TaskType.TRANSFER, delay, argRule, argTransfer, session); } /* * (non-Javadoc) * @see org.waarp.openr66.context.task.AbstractTask#run() */ @Override public void run() { logger.info("Transfer with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); String[] args = finalname.split(" "); if (args.length < 6) { futureCompletion.setFailure( new OpenR66RunnerErrorException("Not enough argument in Transfer")); return; } String filepath = null; String requested = null; String rule = null; String information = null; boolean isMD5 = false; int blocksize = Configuration.configuration.BLOCKSIZE; Timestamp timestart = null; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-to")) { i++; requested = args[i]; } else if (args[i].equalsIgnoreCase("-file")) { i++; filepath = args[i]; } else if (args[i].equalsIgnoreCase("-rule")) { i++; rule = args[i]; } else if (args[i].equalsIgnoreCase("-info")) { i++; information = args[i]; i++; while (i < args.length) { information += " " + args[i]; i++; } } else if (args[i].equalsIgnoreCase("-md5")) { isMD5 = true; } else if (args[i].equalsIgnoreCase("-block")) { i++; blocksize = Integer.parseInt(args[i]); if (blocksize < 100) { logger.warn("Block size is too small: " + blocksize); blocksize = Configuration.configuration.BLOCKSIZE; } } else if (args[i].equalsIgnoreCase("-start")) { i++; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); Date date; try { date = dateFormat.parse(args[i]); timestart = new Timestamp(date.getTime()); } catch (ParseException e) { } } else if (args[i].equalsIgnoreCase("-delay")) { i++; - if (args[i].charAt(0) == '+') { - timestart = new Timestamp(System.currentTimeMillis() + - Long.parseLong(args[i].substring(1))); - } else { - timestart = new Timestamp(Long.parseLong(args[i])); + try { + if (args[i].charAt(0) == '+') { + timestart = new Timestamp(System.currentTimeMillis() + + Long.parseLong(args[i].substring(1))); + } else { + timestart = new Timestamp(Long.parseLong(args[i])); + } + } catch (NumberFormatException e) { } } } if (information == null) { information = "noinfo"; } R66Future future = new R66Future(true); SubmitTransfer transaction = new SubmitTransfer(future, requested, filepath, rule, information, isMD5, blocksize, DbConstant.ILLEGALVALUE, timestart); transaction.run(); future.awaitUninterruptibly(); futureCompletion.setResult(future.getResult()); DbTaskRunner runner = future.getResult().runner; if (future.isSuccess()) { logger.info("Prepare transfer in\n SUCCESS\n " + runner.toShortString() + "\n <REMOTE>" + requested + "</REMOTE>"); futureCompletion.setSuccess(); } else { if (runner != null) { if (future.getCause() == null) { futureCompletion.cancel(); } else { futureCompletion.setFailure(future.getCause()); } logger.error("Prepare transfer in\n FAILURE\n " + runner.toShortString() + "\n <REMOTE>" + requested + "</REMOTE>", future.getCause()); } else { if (future.getCause() == null) { futureCompletion.cancel(); } else { futureCompletion.setFailure(future.getCause()); } logger.error("Prepare transfer in\n FAILURE without any runner back", future.getCause()); } } } }
true
true
public void run() { logger.info("Transfer with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); String[] args = finalname.split(" "); if (args.length < 6) { futureCompletion.setFailure( new OpenR66RunnerErrorException("Not enough argument in Transfer")); return; } String filepath = null; String requested = null; String rule = null; String information = null; boolean isMD5 = false; int blocksize = Configuration.configuration.BLOCKSIZE; Timestamp timestart = null; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-to")) { i++; requested = args[i]; } else if (args[i].equalsIgnoreCase("-file")) { i++; filepath = args[i]; } else if (args[i].equalsIgnoreCase("-rule")) { i++; rule = args[i]; } else if (args[i].equalsIgnoreCase("-info")) { i++; information = args[i]; i++; while (i < args.length) { information += " " + args[i]; i++; } } else if (args[i].equalsIgnoreCase("-md5")) { isMD5 = true; } else if (args[i].equalsIgnoreCase("-block")) { i++; blocksize = Integer.parseInt(args[i]); if (blocksize < 100) { logger.warn("Block size is too small: " + blocksize); blocksize = Configuration.configuration.BLOCKSIZE; } } else if (args[i].equalsIgnoreCase("-start")) { i++; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); Date date; try { date = dateFormat.parse(args[i]); timestart = new Timestamp(date.getTime()); } catch (ParseException e) { } } else if (args[i].equalsIgnoreCase("-delay")) { i++; if (args[i].charAt(0) == '+') { timestart = new Timestamp(System.currentTimeMillis() + Long.parseLong(args[i].substring(1))); } else { timestart = new Timestamp(Long.parseLong(args[i])); } } } if (information == null) { information = "noinfo"; } R66Future future = new R66Future(true); SubmitTransfer transaction = new SubmitTransfer(future, requested, filepath, rule, information, isMD5, blocksize, DbConstant.ILLEGALVALUE, timestart); transaction.run(); future.awaitUninterruptibly(); futureCompletion.setResult(future.getResult()); DbTaskRunner runner = future.getResult().runner; if (future.isSuccess()) { logger.info("Prepare transfer in\n SUCCESS\n " + runner.toShortString() + "\n <REMOTE>" + requested + "</REMOTE>"); futureCompletion.setSuccess(); } else { if (runner != null) { if (future.getCause() == null) { futureCompletion.cancel(); } else { futureCompletion.setFailure(future.getCause()); } logger.error("Prepare transfer in\n FAILURE\n " + runner.toShortString() + "\n <REMOTE>" + requested + "</REMOTE>", future.getCause()); } else { if (future.getCause() == null) { futureCompletion.cancel(); } else { futureCompletion.setFailure(future.getCause()); } logger.error("Prepare transfer in\n FAILURE without any runner back", future.getCause()); } } }
public void run() { logger.info("Transfer with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); String[] args = finalname.split(" "); if (args.length < 6) { futureCompletion.setFailure( new OpenR66RunnerErrorException("Not enough argument in Transfer")); return; } String filepath = null; String requested = null; String rule = null; String information = null; boolean isMD5 = false; int blocksize = Configuration.configuration.BLOCKSIZE; Timestamp timestart = null; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-to")) { i++; requested = args[i]; } else if (args[i].equalsIgnoreCase("-file")) { i++; filepath = args[i]; } else if (args[i].equalsIgnoreCase("-rule")) { i++; rule = args[i]; } else if (args[i].equalsIgnoreCase("-info")) { i++; information = args[i]; i++; while (i < args.length) { information += " " + args[i]; i++; } } else if (args[i].equalsIgnoreCase("-md5")) { isMD5 = true; } else if (args[i].equalsIgnoreCase("-block")) { i++; blocksize = Integer.parseInt(args[i]); if (blocksize < 100) { logger.warn("Block size is too small: " + blocksize); blocksize = Configuration.configuration.BLOCKSIZE; } } else if (args[i].equalsIgnoreCase("-start")) { i++; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); Date date; try { date = dateFormat.parse(args[i]); timestart = new Timestamp(date.getTime()); } catch (ParseException e) { } } else if (args[i].equalsIgnoreCase("-delay")) { i++; try { if (args[i].charAt(0) == '+') { timestart = new Timestamp(System.currentTimeMillis() + Long.parseLong(args[i].substring(1))); } else { timestart = new Timestamp(Long.parseLong(args[i])); } } catch (NumberFormatException e) { } } } if (information == null) { information = "noinfo"; } R66Future future = new R66Future(true); SubmitTransfer transaction = new SubmitTransfer(future, requested, filepath, rule, information, isMD5, blocksize, DbConstant.ILLEGALVALUE, timestart); transaction.run(); future.awaitUninterruptibly(); futureCompletion.setResult(future.getResult()); DbTaskRunner runner = future.getResult().runner; if (future.isSuccess()) { logger.info("Prepare transfer in\n SUCCESS\n " + runner.toShortString() + "\n <REMOTE>" + requested + "</REMOTE>"); futureCompletion.setSuccess(); } else { if (runner != null) { if (future.getCause() == null) { futureCompletion.cancel(); } else { futureCompletion.setFailure(future.getCause()); } logger.error("Prepare transfer in\n FAILURE\n " + runner.toShortString() + "\n <REMOTE>" + requested + "</REMOTE>", future.getCause()); } else { if (future.getCause() == null) { futureCompletion.cancel(); } else { futureCompletion.setFailure(future.getCause()); } logger.error("Prepare transfer in\n FAILURE without any runner back", future.getCause()); } } }
diff --git a/src/test/java/org/openmrs/contrib/databaseexporter/DatabaseExporterTest.java b/src/test/java/org/openmrs/contrib/databaseexporter/DatabaseExporterTest.java index 7a0c3c1..4bcfda6 100644 --- a/src/test/java/org/openmrs/contrib/databaseexporter/DatabaseExporterTest.java +++ b/src/test/java/org/openmrs/contrib/databaseexporter/DatabaseExporterTest.java @@ -1,46 +1,46 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.contrib.databaseexporter; import org.junit.Test; import java.lang.Exception; import java.util.ArrayList; import java.util.List; public class DatabaseExporterTest { @Test public void shouldTest() throws Exception { List<String> config = new ArrayList<String>(); config.add("rwanda/deidentifyPatients"); config.add("rwanda/deidentifyProviders"); config.add("rwanda/deidentifyUsers"); - config.add("rwanda/removeSyncData"); + config.add("removeSyncData"); config.add("rwanda/trimArchiveData"); - config.add("rwanda/removeAllPatients"); + config.add("removeAllPatients"); config.add("rwanda/trimUsers"); config.add("rwanda/trimProviders"); config.add("-localDbName=openmrs_rwink"); config.add("-user=openmrs"); config.add("-password=openmrs"); config.add("-logSql=true"); DatabaseExporter.main(config.toArray(new String[] {})); } }
false
true
public void shouldTest() throws Exception { List<String> config = new ArrayList<String>(); config.add("rwanda/deidentifyPatients"); config.add("rwanda/deidentifyProviders"); config.add("rwanda/deidentifyUsers"); config.add("rwanda/removeSyncData"); config.add("rwanda/trimArchiveData"); config.add("rwanda/removeAllPatients"); config.add("rwanda/trimUsers"); config.add("rwanda/trimProviders"); config.add("-localDbName=openmrs_rwink"); config.add("-user=openmrs"); config.add("-password=openmrs"); config.add("-logSql=true"); DatabaseExporter.main(config.toArray(new String[] {})); }
public void shouldTest() throws Exception { List<String> config = new ArrayList<String>(); config.add("rwanda/deidentifyPatients"); config.add("rwanda/deidentifyProviders"); config.add("rwanda/deidentifyUsers"); config.add("removeSyncData"); config.add("rwanda/trimArchiveData"); config.add("removeAllPatients"); config.add("rwanda/trimUsers"); config.add("rwanda/trimProviders"); config.add("-localDbName=openmrs_rwink"); config.add("-user=openmrs"); config.add("-password=openmrs"); config.add("-logSql=true"); DatabaseExporter.main(config.toArray(new String[] {})); }
diff --git a/src/fr/enseirb/odroidx/movieselector/ContainerData.java b/src/fr/enseirb/odroidx/movieselector/ContainerData.java index e1e6a32..a56d62c 100644 --- a/src/fr/enseirb/odroidx/movieselector/ContainerData.java +++ b/src/fr/enseirb/odroidx/movieselector/ContainerData.java @@ -1,61 +1,61 @@ package fr.enseirb.odroidx.movieselector; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import android.content.Context; import android.widget.Toast; public class ContainerData { static public Context context; public static ArrayList<Movie> getMovies(String ip, Context context){ SAXParserFactory fabrique = SAXParserFactory.newInstance(); SAXParser parser = null; ArrayList<Movie> movies = null; try { parser = fabrique.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } - URL url = null; + URL url; try { - url = new URL(ip + "/vod.xml"); + url = new URL("http://" + ip + ":8080/dash-manager/vod"); } catch (MalformedURLException e) { e.printStackTrace(); - Toast.makeText(context, "Malformed URL malformed or unreachabke vod.xml", Toast.LENGTH_LONG).show(); + Toast.makeText(context, "Malformed URL or unreachable XML", Toast.LENGTH_LONG).show(); return null; } DefaultHandler handler = new ParserXMLHandler(); try { parser.parse(url.openConnection().getInputStream(), handler); movies = ((ParserXMLHandler) handler).getData(); } catch (SAXException e) { e.printStackTrace(); Toast.makeText(context, "Impossible to parse vod.xml", Toast.LENGTH_LONG).show(); return null; } catch (IOException e) { e.printStackTrace(); Toast.makeText(context, "Connection to server impossible", Toast.LENGTH_LONG).show(); return null; } return movies; } }
false
true
public static ArrayList<Movie> getMovies(String ip, Context context){ SAXParserFactory fabrique = SAXParserFactory.newInstance(); SAXParser parser = null; ArrayList<Movie> movies = null; try { parser = fabrique.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } URL url = null; try { url = new URL(ip + "/vod.xml"); } catch (MalformedURLException e) { e.printStackTrace(); Toast.makeText(context, "Malformed URL malformed or unreachabke vod.xml", Toast.LENGTH_LONG).show(); return null; } DefaultHandler handler = new ParserXMLHandler(); try { parser.parse(url.openConnection().getInputStream(), handler); movies = ((ParserXMLHandler) handler).getData(); } catch (SAXException e) { e.printStackTrace(); Toast.makeText(context, "Impossible to parse vod.xml", Toast.LENGTH_LONG).show(); return null; } catch (IOException e) { e.printStackTrace(); Toast.makeText(context, "Connection to server impossible", Toast.LENGTH_LONG).show(); return null; } return movies; }
public static ArrayList<Movie> getMovies(String ip, Context context){ SAXParserFactory fabrique = SAXParserFactory.newInstance(); SAXParser parser = null; ArrayList<Movie> movies = null; try { parser = fabrique.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } URL url; try { url = new URL("http://" + ip + ":8080/dash-manager/vod"); } catch (MalformedURLException e) { e.printStackTrace(); Toast.makeText(context, "Malformed URL or unreachable XML", Toast.LENGTH_LONG).show(); return null; } DefaultHandler handler = new ParserXMLHandler(); try { parser.parse(url.openConnection().getInputStream(), handler); movies = ((ParserXMLHandler) handler).getData(); } catch (SAXException e) { e.printStackTrace(); Toast.makeText(context, "Impossible to parse vod.xml", Toast.LENGTH_LONG).show(); return null; } catch (IOException e) { e.printStackTrace(); Toast.makeText(context, "Connection to server impossible", Toast.LENGTH_LONG).show(); return null; } return movies; }
diff --git a/ActiveObjects/src/net/java/ao/EntityProxy.java b/ActiveObjects/src/net/java/ao/EntityProxy.java index e082091..b96c87c 100644 --- a/ActiveObjects/src/net/java/ao/EntityProxy.java +++ b/ActiveObjects/src/net/java/ao/EntityProxy.java @@ -1,610 +1,610 @@ /* * Copyright 2007 Daniel Spiewak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.java.ao; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.InputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import net.java.ao.schema.OnUpdate; /** * @author Daniel Spiewak */ class EntityProxy<T extends Entity> implements InvocationHandler { private int id; private Class<T> type; private EntityManager manager; private ImplementationWrapper<T> implementation; private final Map<String, Object> cache; private final ReadWriteLock cacheLock = new ReentrantReadWriteLock(); private final Set<String> dirtyFields; private final ReadWriteLock dirtyFieldsLock = new ReentrantReadWriteLock(); private List<PropertyChangeListener> listeners; public EntityProxy(EntityManager manager, Class<T> type) { this.type = type; this.manager = manager; cache = new HashMap<String, Object>(); dirtyFields = new LinkedHashSet<String>(); listeners = new LinkedList<PropertyChangeListener>(); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getEntityType")) { return type; } if (implementation == null) { implementation = new ImplementationWrapper<T>((T) proxy); } MethodImplWrapper methodImpl = implementation.getMethod(method.getName(), method.getParameterTypes()); if (methodImpl != null) { if (!Common.getCallingClass(1).equals(methodImpl.getMethod().getDeclaringClass()) && !methodImpl.getMethod().getDeclaringClass().equals(Object.class)) { return methodImpl.getMethod().invoke(methodImpl.getInstance(), args); } } if (method.getName().equals("setID")) { setID((Integer) args[0]); return Void.TYPE; } else if (method.getName().equals("getID")) { return getID(); } else if (method.getName().equals("save")) { save(); return Void.TYPE; } else if (method.getName().equals("getTableName")) { return getTableName(); } else if (method.getName().equals("getEntityManager")) { return getManager(); } else if (method.getName().equals("addPropertyChangeListener")) { addPropertyChangeListener((PropertyChangeListener) args[0]); } else if (method.getName().equals("removePropertyChangeListener")) { removePropertyChangeListener((PropertyChangeListener) args[0]); } else if (method.getName().equals("hashCode")) { return hashCodeImpl(); } else if (method.getName().equals("equals")) { return equalsImpl((Entity) proxy, args[0]); } else if (method.getName().equals("toString")) { return toStringImpl(); } String tableName = getManager().getNameConverter().getName(type); Mutator mutatorAnnotation = method.getAnnotation(Mutator.class); Accessor accessorAnnotation = method.getAnnotation(Accessor.class); OneToMany oneToManyAnnotation = method.getAnnotation(OneToMany.class); ManyToMany manyToManyAnnotation = method.getAnnotation(ManyToMany.class); OnUpdate onUpdateAnnotation = method.getAnnotation(OnUpdate.class); if (mutatorAnnotation != null) { invokeSetter((T) proxy, id, tableName, mutatorAnnotation.value(), args[0], onUpdateAnnotation != null); return Void.TYPE; } else if (accessorAnnotation != null) { return invokeGetter(getID(), tableName, accessorAnnotation.value(), method.getReturnType(), onUpdateAnnotation != null); } else if (oneToManyAnnotation != null && method.getReturnType().isArray() && Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) { Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType(); String otherTableName = getManager().getNameConverter().getName(type); return retrieveRelations(otherTableName, oneToManyAnnotation.value(), new String[] { "id" }, getID(), (Class<? extends Entity>) type); } else if (manyToManyAnnotation != null && method.getReturnType().isArray() && Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) { Class<? extends Entity> throughType = manyToManyAnnotation.value(); Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType(); String otherTableName = getManager().getNameConverter().getName(throughType); return retrieveRelations(otherTableName, null, Common.getMappingFields(throughType, type), getID(), throughType, type); } else if (method.getName().startsWith("get")) { String name = Common.convertDowncaseName(method.getName().substring(3)); if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) { name += "ID"; } - return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation != null); + return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation == null); } else if (method.getName().startsWith("is")) { String name = Common.convertDowncaseName(method.getName().substring(2)); if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) { name += "ID"; } - return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation != null); + return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation == null); } else if (method.getName().startsWith("set")) { String name = Common.convertDowncaseName(method.getName().substring(3)); if (Common.interfaceInheritsFrom(method.getParameterTypes()[0], Entity.class)) { name += "ID"; } - invokeSetter((T) proxy, id, tableName, name, args[0], onUpdateAnnotation != null); + invokeSetter((T) proxy, id, tableName, name, args[0], onUpdateAnnotation == null); return Void.TYPE; } return null; } public int getID() { return id; } public String getTableName() { return getManager().getNameConverter().getName(type); } public void setID(int id) { this.id = id; } public void save() throws SQLException { dirtyFieldsLock.writeLock().lock(); try { if (dirtyFields.isEmpty()) { return; } String table = getTableName(); Connection conn = getConnectionImpl(); cacheLock.readLock().lock(); try { StringBuilder sql = new StringBuilder("UPDATE " + table + " SET "); for (String field : dirtyFields) { sql.append(field); if (cache.containsKey(field)) { sql.append(" = ?,"); } else { sql.append(" = NULL,"); } } if (dirtyFields.size() > 0) { sql.setLength(sql.length() - 1); } sql.append(" WHERE id = ?"); Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString()); PreparedStatement stmt = conn.prepareStatement(sql.toString()); int index = 1; for (String field : dirtyFields) { if (cache.containsKey(field)) { convertValue(stmt, index++, cache.get(field)); } } stmt.setInt(index++, id); stmt.executeUpdate(); dirtyFields.removeAll(dirtyFields); stmt.close(); } finally { cacheLock.readLock().unlock(); closeConnectionImpl(conn); } } finally { dirtyFieldsLock.writeLock().unlock(); } } public void addPropertyChangeListener(PropertyChangeListener listener) { listeners.add(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { listeners.remove(listener); } public int hashCodeImpl() { return (int) (new Random(getID()).nextFloat() * getID()) + getID() % (2 << 15); } public boolean equalsImpl(Entity proxy, Object obj) { if (proxy == obj) { return true; } if (obj instanceof Entity) { Entity entity = (Entity) obj; return entity.getID() == proxy.getID() && entity.getTableName().equals(proxy.getTableName()); } return false; } public String toStringImpl() { return getManager().getNameConverter().getName(type) + " {id = " + getID() + "}"; } public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof EntityProxy) { EntityProxy<?> proxy = (EntityProxy<?>) obj; if (proxy.type.equals(type) && proxy.id == id) { return true; } } return false; } public int hashCode() { return type.hashCode(); } void addToCache(String key, Object value) { if (key.trim().equalsIgnoreCase("id")) { return; } cacheLock.writeLock().lock(); try { if (!cache.containsKey(key)) { cache.put(key, value); } } finally { cacheLock.writeLock().unlock(); } } Class<T> getType() { return type; } // any dirty fields are kept in the cache, since they have yet to be saved void flushCache() { cacheLock.writeLock().lock(); dirtyFieldsLock.readLock().lock(); try { for (String fieldName : cache.keySet()) { if (!dirtyFields.contains(fieldName)) { cache.remove(fieldName); } } } finally { dirtyFieldsLock.readLock().unlock(); cacheLock.writeLock().unlock(); } } private EntityManager getManager() { return manager; } private Connection getConnectionImpl() throws SQLException { return DBEncapsulator.getInstance(getManager().getProvider()).getConnection(); } private void closeConnectionImpl(Connection conn) throws SQLException { DBEncapsulator.getInstance(getManager().getProvider()).closeConnection(conn); } private <V> V invokeGetter(int id, String table, String name, Class<V> type, boolean shouldCache) throws Throwable { V back = null; if (shouldCache) { cacheLock.writeLock().lock(); } try { if (shouldCache && cache.containsKey(name)) { Object value = cache.get(name); if (instanceOf(value, type)) { return (V) value; } else if (Common.interfaceInheritsFrom(type, Entity.class) && value instanceof Integer) { value = getManager().get((Class<? extends Entity>) type, (Integer) value); cache.put(name, value); return (V) value; } else { cache.remove(name); // invalid cached value } } Connection conn = getConnectionImpl(); try { String sql = "SELECT " + name + " FROM " + table + " WHERE id = ?"; Logger.getLogger("net.java.ao").log(Level.INFO, sql); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, id); ResultSet res = stmt.executeQuery(); if (res.next()) { back = convertValue(res, name, type); } res.close(); stmt.close(); } finally { closeConnectionImpl(conn); } if (shouldCache && back != null) { cache.put(name, back); } } finally { if (shouldCache) { cacheLock.writeLock().unlock(); } } return back; } private void invokeSetter(T entity, int id, String table, String name, Object value, boolean shouldCache) throws Throwable { boolean saveable = Common.interfaceInheritsFrom(type, SaveableEntity.class); Object oldValue = null; if (value != null) { Class<?> type = value.getClass(); if (value instanceof Entity) { type = ((Entity) value).getEntityType(); } oldValue = invokeGetter(id, table, name, type, shouldCache); } invokeSetterImpl(name, value); PropertyChangeEvent evt = new PropertyChangeEvent(entity, name, oldValue, value); for (PropertyChangeListener l : listeners) { l.propertyChange(evt); } dirtyFieldsLock.writeLock().lock(); try { dirtyFields.add(name); } finally { dirtyFieldsLock.writeLock().unlock(); } if (!saveable) { save(); } } private void invokeSetterImpl(String name, Object value) throws Throwable { cacheLock.writeLock().lock(); try { cache.put(name, value); } finally { cacheLock.writeLock().unlock(); } } private <V extends Entity> V[] retrieveRelations(String table, String[] inMapFields, String[] outMapFields, int id, Class<V> type) throws SQLException { return retrieveRelations(table, inMapFields, outMapFields, id, type, type); } private <V extends Entity> V[] retrieveRelations(String table, String[] inMapFields, String[] outMapFields, int id, Class<? extends Entity> type, Class<V> finalType) throws SQLException { List<V> back = new ArrayList<V>(); Connection conn = getConnectionImpl(); if (inMapFields == null || inMapFields.length == 0) { inMapFields = Common.getMappingFields(type, this.type); } try { StringBuilder sql = new StringBuilder("SELECT DISTINCT a.outMap AS outMap FROM ("); int numParams = 0; for (String outMap : outMapFields) { for (String inMap : inMapFields) { sql.append("SELECT "); sql.append(outMap); sql.append(" AS outMap,"); sql.append(inMap); sql.append(" AS inMap FROM "); sql.append(table); sql.append(" WHERE "); sql.append(inMap); sql.append(" = ? UNION "); numParams++; } } sql.setLength(sql.length() - " UNION ".length()); sql.append(") a"); Logger.getLogger("net.java.ao").log(Level.INFO, sql.toString()); PreparedStatement stmt = conn.prepareStatement(sql.toString()); for (int i = 0; i < numParams; i++) { stmt.setInt(i + 1, id); } ResultSet res = stmt.executeQuery(); while (res.next()) { if (finalType.equals(this.type) && res.getInt("outMap") == id) { continue; } back.add(getManager().get(finalType, res.getInt("outMap"))); } res.close(); stmt.close(); } finally { closeConnectionImpl(conn); } return back.toArray((V[]) Array.newInstance(finalType, back.size())); } private <V> V convertValue(ResultSet res, String field, Class<V> type) throws SQLException { if (res.getString(field) == null) { return null; } if (type.equals(Integer.class) || type.equals(int.class)) { return (V) new Integer(res.getInt(field)); } else if (type.equals(Long.class) || type.equals(long.class)) { return (V) new Long(res.getLong(field)); } else if (type.equals(Short.class) || type.equals(short.class)) { return (V) new Short(res.getShort(field)); } else if (type.equals(Float.class) || type.equals(float.class)) { return (V) new Float(res.getFloat(field)); } else if (type.equals(Double.class) || type.equals(double.class)) { return (V) new Double(res.getDouble(field)); } else if (type.equals(Byte.class) || type.equals(byte.class)) { return (V) new Byte(res.getByte(field)); } else if (type.equals(Boolean.class) || type.equals(boolean.class)) { return (V) new Boolean(res.getBoolean(field)); } else if (type.equals(String.class)) { return (V) res.getString(field); } else if (type.equals(URL.class)) { try { return (V) new URL(res.getString(field)); } catch (MalformedURLException e) { throw (SQLException) new SQLException().initCause(e); } } else if (Common.typeInstanceOf(type, Calendar.class)) { Calendar back = Calendar.getInstance(); back.setTimeInMillis(res.getTimestamp(field).getTime()); return (V) back; } else if (Common.typeInstanceOf(type, Date.class)) { return (V) new Date(res.getTimestamp(field).getTime()); } else if (type.equals(URL.class)) { return (V) res.getURL(field); } else if (type.equals(InputStream.class)) { return (V) res.getBlob(field).getBinaryStream(); } else if (Common.interfaceInheritsFrom(type, Entity.class)) { return (V) getManager().get((Class<? extends Entity>) type, res.getInt(field)); } else { throw new RuntimeException("Unrecognized type: " + type.toString()); } } private void convertValue(PreparedStatement stmt, int index, Object value) throws SQLException { if (value instanceof Integer) { stmt.setInt(index, (Integer) value); } else if (value instanceof Long) { stmt.setLong(index, (Long) value); } else if (value instanceof Short) { stmt.setShort(index, (Short) value); } else if (value instanceof Float) { stmt.setFloat(index, (Float) value); } else if (value instanceof Double) { stmt.setDouble(index, (Double) value); } else if (value instanceof Byte) { stmt.setByte(index, (Byte) value); } else if (value instanceof Boolean) { stmt.setBoolean(index, (Boolean) value); } else if (value instanceof String) { stmt.setString(index, (String) value); } else if (value instanceof URL) { stmt.setString(index, value.toString()); } else if (value instanceof Calendar) { stmt.setTimestamp(index, new Timestamp(((Calendar) value).getTimeInMillis())); } else if (value instanceof Date) { stmt.setTimestamp(index, new Timestamp(((Date) value).getTime())); } else if (value instanceof Entity) { stmt.setInt(index, ((Entity) value).getID()); } else if (value == null) { stmt.setString(index, null); } else { throw new RuntimeException("Unrecognized type: " + value.getClass().toString()); } } private boolean instanceOf(Object value, Class<?> type) { if (type.isPrimitive()) { if (type.equals(boolean.class)) { return instanceOf(value, Boolean.class); } else if (type.equals(char.class)) { return instanceOf(value, Character.class); } else if (type.equals(byte.class)) { return instanceOf(value, Byte.class); } else if (type.equals(short.class)) { return instanceOf(value, Short.class); } else if (type.equals(int.class)) { return instanceOf(value, Integer.class); } else if (type.equals(long.class)) { return instanceOf(value, Long.class); } else if (type.equals(float.class)) { return instanceOf(value, Float.class); } else if (type.equals(double.class)) { return instanceOf(value, Double.class); } } else { return type.isInstance(value); } return false; } // special call from ObjectOutputStream private void writeObject(ObjectOutputStream oos) throws IOException { try { save(); } catch (SQLException e) { throw (IOException) new IOException().initCause(e); } oos.defaultWriteObject(); } }
false
true
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getEntityType")) { return type; } if (implementation == null) { implementation = new ImplementationWrapper<T>((T) proxy); } MethodImplWrapper methodImpl = implementation.getMethod(method.getName(), method.getParameterTypes()); if (methodImpl != null) { if (!Common.getCallingClass(1).equals(methodImpl.getMethod().getDeclaringClass()) && !methodImpl.getMethod().getDeclaringClass().equals(Object.class)) { return methodImpl.getMethod().invoke(methodImpl.getInstance(), args); } } if (method.getName().equals("setID")) { setID((Integer) args[0]); return Void.TYPE; } else if (method.getName().equals("getID")) { return getID(); } else if (method.getName().equals("save")) { save(); return Void.TYPE; } else if (method.getName().equals("getTableName")) { return getTableName(); } else if (method.getName().equals("getEntityManager")) { return getManager(); } else if (method.getName().equals("addPropertyChangeListener")) { addPropertyChangeListener((PropertyChangeListener) args[0]); } else if (method.getName().equals("removePropertyChangeListener")) { removePropertyChangeListener((PropertyChangeListener) args[0]); } else if (method.getName().equals("hashCode")) { return hashCodeImpl(); } else if (method.getName().equals("equals")) { return equalsImpl((Entity) proxy, args[0]); } else if (method.getName().equals("toString")) { return toStringImpl(); } String tableName = getManager().getNameConverter().getName(type); Mutator mutatorAnnotation = method.getAnnotation(Mutator.class); Accessor accessorAnnotation = method.getAnnotation(Accessor.class); OneToMany oneToManyAnnotation = method.getAnnotation(OneToMany.class); ManyToMany manyToManyAnnotation = method.getAnnotation(ManyToMany.class); OnUpdate onUpdateAnnotation = method.getAnnotation(OnUpdate.class); if (mutatorAnnotation != null) { invokeSetter((T) proxy, id, tableName, mutatorAnnotation.value(), args[0], onUpdateAnnotation != null); return Void.TYPE; } else if (accessorAnnotation != null) { return invokeGetter(getID(), tableName, accessorAnnotation.value(), method.getReturnType(), onUpdateAnnotation != null); } else if (oneToManyAnnotation != null && method.getReturnType().isArray() && Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) { Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType(); String otherTableName = getManager().getNameConverter().getName(type); return retrieveRelations(otherTableName, oneToManyAnnotation.value(), new String[] { "id" }, getID(), (Class<? extends Entity>) type); } else if (manyToManyAnnotation != null && method.getReturnType().isArray() && Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) { Class<? extends Entity> throughType = manyToManyAnnotation.value(); Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType(); String otherTableName = getManager().getNameConverter().getName(throughType); return retrieveRelations(otherTableName, null, Common.getMappingFields(throughType, type), getID(), throughType, type); } else if (method.getName().startsWith("get")) { String name = Common.convertDowncaseName(method.getName().substring(3)); if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) { name += "ID"; } return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation != null); } else if (method.getName().startsWith("is")) { String name = Common.convertDowncaseName(method.getName().substring(2)); if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) { name += "ID"; } return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation != null); } else if (method.getName().startsWith("set")) { String name = Common.convertDowncaseName(method.getName().substring(3)); if (Common.interfaceInheritsFrom(method.getParameterTypes()[0], Entity.class)) { name += "ID"; } invokeSetter((T) proxy, id, tableName, name, args[0], onUpdateAnnotation != null); return Void.TYPE; } return null; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getEntityType")) { return type; } if (implementation == null) { implementation = new ImplementationWrapper<T>((T) proxy); } MethodImplWrapper methodImpl = implementation.getMethod(method.getName(), method.getParameterTypes()); if (methodImpl != null) { if (!Common.getCallingClass(1).equals(methodImpl.getMethod().getDeclaringClass()) && !methodImpl.getMethod().getDeclaringClass().equals(Object.class)) { return methodImpl.getMethod().invoke(methodImpl.getInstance(), args); } } if (method.getName().equals("setID")) { setID((Integer) args[0]); return Void.TYPE; } else if (method.getName().equals("getID")) { return getID(); } else if (method.getName().equals("save")) { save(); return Void.TYPE; } else if (method.getName().equals("getTableName")) { return getTableName(); } else if (method.getName().equals("getEntityManager")) { return getManager(); } else if (method.getName().equals("addPropertyChangeListener")) { addPropertyChangeListener((PropertyChangeListener) args[0]); } else if (method.getName().equals("removePropertyChangeListener")) { removePropertyChangeListener((PropertyChangeListener) args[0]); } else if (method.getName().equals("hashCode")) { return hashCodeImpl(); } else if (method.getName().equals("equals")) { return equalsImpl((Entity) proxy, args[0]); } else if (method.getName().equals("toString")) { return toStringImpl(); } String tableName = getManager().getNameConverter().getName(type); Mutator mutatorAnnotation = method.getAnnotation(Mutator.class); Accessor accessorAnnotation = method.getAnnotation(Accessor.class); OneToMany oneToManyAnnotation = method.getAnnotation(OneToMany.class); ManyToMany manyToManyAnnotation = method.getAnnotation(ManyToMany.class); OnUpdate onUpdateAnnotation = method.getAnnotation(OnUpdate.class); if (mutatorAnnotation != null) { invokeSetter((T) proxy, id, tableName, mutatorAnnotation.value(), args[0], onUpdateAnnotation != null); return Void.TYPE; } else if (accessorAnnotation != null) { return invokeGetter(getID(), tableName, accessorAnnotation.value(), method.getReturnType(), onUpdateAnnotation != null); } else if (oneToManyAnnotation != null && method.getReturnType().isArray() && Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) { Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType(); String otherTableName = getManager().getNameConverter().getName(type); return retrieveRelations(otherTableName, oneToManyAnnotation.value(), new String[] { "id" }, getID(), (Class<? extends Entity>) type); } else if (manyToManyAnnotation != null && method.getReturnType().isArray() && Common.interfaceInheritsFrom(method.getReturnType().getComponentType(), Entity.class)) { Class<? extends Entity> throughType = manyToManyAnnotation.value(); Class<? extends Entity> type = (Class<? extends Entity>) method.getReturnType().getComponentType(); String otherTableName = getManager().getNameConverter().getName(throughType); return retrieveRelations(otherTableName, null, Common.getMappingFields(throughType, type), getID(), throughType, type); } else if (method.getName().startsWith("get")) { String name = Common.convertDowncaseName(method.getName().substring(3)); if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) { name += "ID"; } return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation == null); } else if (method.getName().startsWith("is")) { String name = Common.convertDowncaseName(method.getName().substring(2)); if (Common.interfaceInheritsFrom(method.getReturnType(), Entity.class)) { name += "ID"; } return invokeGetter(getID(), tableName, name, method.getReturnType(), onUpdateAnnotation == null); } else if (method.getName().startsWith("set")) { String name = Common.convertDowncaseName(method.getName().substring(3)); if (Common.interfaceInheritsFrom(method.getParameterTypes()[0], Entity.class)) { name += "ID"; } invokeSetter((T) proxy, id, tableName, name, args[0], onUpdateAnnotation == null); return Void.TYPE; } return null; }
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java index b4ce25d63..82045483c 100644 --- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java +++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java @@ -1,2065 +1,2062 @@ /******************************************************************************* * Copyright (c) 2000, 2002 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM - Initial API and implementation ******************************************************************************/ package org.eclipse.core.internal.resources; import java.io.IOException; import java.util.*; import org.eclipse.core.internal.events.*; import org.eclipse.core.internal.localstore.CoreFileSystemLibrary; import org.eclipse.core.internal.localstore.FileSystemResourceManager; import org.eclipse.core.internal.properties.PropertyManager; import org.eclipse.core.internal.utils.Assert; import org.eclipse.core.internal.utils.Policy; import org.eclipse.core.internal.watson.*; import org.eclipse.core.resources.*; import org.eclipse.core.resources.team.IMoveDeleteHook; import org.eclipse.core.resources.team.TeamHook; import org.eclipse.core.runtime.*; public class Workspace extends PlatformObject implements IWorkspace, ICoreConstants { protected WorkspacePreferences description; protected LocalMetaArea localMetaArea; protected boolean openFlag = false; protected ElementTree tree; protected ElementTree operationTree; // tree at the start of the current operation protected SaveManager saveManager; protected BuildManager buildManager; protected NatureManager natureManager; protected NotificationManager notificationManager; protected FileSystemResourceManager fileSystemManager; protected PathVariableManager pathVariableManager; protected PropertyManager propertyManager; protected MarkerManager markerManager; protected WorkManager workManager; protected AliasManager aliasManager; protected long nextNodeId = 0; protected long nextModificationStamp = 0; protected long nextMarkerId = 0; protected Synchronizer synchronizer; protected IProject[] buildOrder = null; protected IWorkspaceRoot defaultRoot = new WorkspaceRoot(Path.ROOT, this); protected final HashSet lifecycleListeners = new HashSet(10); protected static final String REFRESH_ON_STARTUP = "-refresh"; //$NON-NLS-1$ /** * File modification validation. If it is true and validator is null, we try/initialize * validator first time through. If false, there is no validator. */ protected boolean shouldValidate = true; /** * The currently installed file modification validator. */ protected IFileModificationValidator validator = null; /** * The currently installed Move/Delete hook. */ protected IMoveDeleteHook moveDeleteHook = null; /** * The currently installed team hook. */ protected TeamHook teamHook = null; // whether the resources plugin is in debug mode. public static boolean DEBUG = false; /** This field is used to control the access to the workspace tree inside operations. It is useful when calling alien code. Since we usually are in the same thread as the alien code we are calling, our concurrency model would allow the alien code to run operations that could change the tree. If this field is set to true, a beginOperation(true) fails, so the alien code would fail and be logged in our SafeRunnable wrappers, not affecting the normal workspace operation. */ protected boolean treeLocked; /** indicates if the workspace crashed in a previous session */ protected boolean crashed = false; public Workspace() { super(); localMetaArea = new LocalMetaArea(); tree = new ElementTree(); /* tree should only be modified during operations */ tree.immutable(); treeLocked = true; tree.setTreeData(newElement(IResource.ROOT)); } /** * Adds a listener for internal workspace lifecycle events. There is no way to * remove lifecycle listeners. */ public void addLifecycleListener(ILifecycleListener listener) { lifecycleListeners.add(listener); } /** * @see IWorkspace */ public void addResourceChangeListener(IResourceChangeListener listener) { notificationManager.addListener(listener, IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.POST_CHANGE); } /** * @see IWorkspace */ public void addResourceChangeListener(IResourceChangeListener listener, int eventMask) { notificationManager.addListener(listener, eventMask); } /** * @see IWorkspace */ public ISavedState addSaveParticipant(Plugin plugin, ISaveParticipant participant) throws CoreException { Assert.isNotNull(plugin, "Plugin must not be null"); //$NON-NLS-1$ Assert.isNotNull(participant, "Participant must not be null"); //$NON-NLS-1$ return saveManager.addParticipant(plugin, participant); } public void beginOperation(boolean createNewTree) throws CoreException { WorkManager workManager = getWorkManager(); workManager.incrementNestedOperations(); if (!workManager.isBalanced()) Assert.isTrue(false, "Operation was not prepared."); //$NON-NLS-1$ if (treeLocked && createNewTree) { String message = Policy.bind("resources.cannotModify"); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.ERROR, null, message, null); } if (workManager.getPreparedOperationDepth() > 1) { if (createNewTree && tree.isImmutable()) newWorkingTree(); return; } if (createNewTree) { // stash the current tree as the basis for this operation. operationTree = tree; newWorkingTree(); } } private void broadcastChanges(ElementTree currentTree, int type, boolean lockTree, boolean updateState, IProgressMonitor monitor) { if (operationTree == null) return; monitor.subTask(MSG_RESOURCES_UPDATING); notificationManager.broadcastChanges(currentTree, type, lockTree, updateState); } /** * Broadcasts an internal workspace lifecycle event to interested * internal listeners. */ protected void broadcastEvent(LifecycleEvent event) throws CoreException { for (Iterator it = lifecycleListeners.iterator(); it.hasNext();) { ILifecycleListener listener = (ILifecycleListener) it.next(); listener.handleEvent(event); } } public void build(int trigger, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(null, Policy.opWork); try { prepareOperation(); beginOperation(true); getBuildManager().build(trigger, Policy.subMonitorFor(monitor, Policy.opWork)); } finally { getWorkManager().avoidAutoBuild(); endOperation(false, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * @see IWorkspace#checkpoint */ public void checkpoint(boolean build) { boolean immutable = true; try { /* if it was not called by the current operation, just ignore */ if (!getWorkManager().isCurrentOperation()) return; immutable = tree.isImmutable(); broadcastChanges(tree, IResourceChangeEvent.PRE_AUTO_BUILD, false, false, Policy.monitorFor(null)); if (build && isAutoBuilding()) getBuildManager().build(IncrementalProjectBuilder.AUTO_BUILD, Policy.monitorFor(null)); broadcastChanges(tree, IResourceChangeEvent.POST_AUTO_BUILD, false, false, Policy.monitorFor(null)); broadcastChanges(tree, IResourceChangeEvent.POST_CHANGE, true, true, Policy.monitorFor(null)); getMarkerManager().resetMarkerDeltas(); } catch (CoreException e) { // ignore any CoreException. There shouldn't be any as the buildmanager and notification manager // should be catching and logging... } finally { if (!immutable) newWorkingTree(); } } /** * Deletes all the files and directories from the given root down (inclusive). * Returns false if we could not delete some file or an exception occurred * at any point in the deletion. * Even if an exception occurs, a best effort is made to continue deleting. */ public static boolean clear(java.io.File root) { boolean result = true; if (root.isDirectory()) { String[] list = root.list(); // for some unknown reason, list() can return null. // Just skip the children If it does. if (list != null) for (int i = 0; i < list.length; i++) result &= clear(new java.io.File(root, list[i])); } try { if (root.exists()) result &= root.delete(); } catch (Exception e) { result = false; } return result; } /** * Closes this workspace; ignored if this workspace is not open. * The state of this workspace is not saved before the workspace * is shut down. * <p> * If the workspace was saved immediately prior to closing, * it will have the same set of projects * (open or closed) when reopened for a subsequent session. * Otherwise, closing a workspace may lose some or all of the * changes made since the last save or snapshot. * </p> * <p> * Note that session properties are discarded when a workspace is closed. * </p> * <p> * This method is long-running; progress and cancellation are provided * by the given progress monitor. * </p> * * @param monitor a progress monitor, or <code>null</code> if progress * reporting and cancellation are not desired * @exception CoreException if the workspace could not be shutdown. */ public void close(IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { String msg = Policy.bind("resources.closing.0"); //$NON-NLS-1$ int rootCount = tree.getChildCount(Path.ROOT); monitor.beginTask(msg, rootCount + 2); monitor.subTask(msg); //this operation will never end because the world is going away try { prepareOperation(); if (isOpen()) { beginOperation(true); IProject[] projects = getRoot().getProjects(); for (int i = 0; i < projects.length; i++) { //notify managers of closing so they can cleanup broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_CLOSE, projects[i])); monitor.worked(1); } //empty the workspace tree so we leave in a clean state deleteResource(getRoot()); openFlag = false; } // endOperation not needed here } finally { // Shutdown needs to be executed anyway. Doesn't matter if the workspace was not open. shutdown(Policy.subMonitorFor(monitor, 2, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); } } finally { monitor.done(); } } /** * Implementation of API method declared on IWorkspace. * * @deprecated Replaced by <code>IWorkspace.computeProjectOrder</code>, which * produces a more usable result when there are cycles in project reference * graph. */ public IProject[][] computePrerequisiteOrder(IProject[] targets) { return computePrerequisiteOrder1(targets); } /* * Compatible reimplementation of * <code>IWorkspace.computePrerequisiteOrder</code> using * <code>IWorkspace.computeProjectOrder</code>. * * @since 2.1 */ private IProject[][] computePrerequisiteOrder1(IProject[] projects) { IWorkspace.ProjectOrder r = computeProjectOrder(projects); if (!r.hasCycles) { return new IProject[][] {r.projects, new IProject[0]}; } // when there are cycles, we need to remove all knotted projects from // r.projects to form result[0] and merge all knots to form result[1] // Set<IProject> bad Set bad = new HashSet(); // Set<IProject> bad Set keepers = new HashSet(Arrays.asList(r.projects)); for (int i = 0; i < r.knots.length; i++) { IProject[] knot = r.knots[i]; for (int j = 0; j < knot.length; j++) { IProject project = knot[j]; // keep only selected projects in knot if (keepers.contains(project)) { bad.add(project); } } } IProject[] result2 = new IProject[bad.size()]; bad.toArray(result2); // List<IProject> p List p = new LinkedList(); p.addAll(Arrays.asList(r.projects)); for (Iterator it = p.listIterator(); it.hasNext(); ) { IProject project = (IProject) it.next(); if (bad.contains(project)) { // remove knotted projects from the main answer it.remove(); } } IProject[] result1 = new IProject[p.size()]; p.toArray(result1); return new IProject[][] {result1, result2}; } /** * Implementation of API method declared on IWorkspace. * * @since 2.1 */ public ProjectOrder computeProjectOrder(IProject[] projects) { // compute the full project order for all accessible projects ProjectOrder fullProjectOrder = computeFullProjectOrder(); // "fullProjectOrder.projects" contains no inaccessible projects // but might contain accessible projects omitted from "projects" // optimize common case where "projects" includes everything int accessibleCount = 0; for (int i = 0; i < projects.length; i++) { if (projects[i].isAccessible()) { accessibleCount++; } } // no filtering required if the subset accounts for the full list if (accessibleCount == fullProjectOrder.projects.length) { return fullProjectOrder; } // otherwise we need to eliminate mention of other projects... // ... from "fullProjectOrder.projects"... // Set<IProject> keepers Set keepers = new HashSet(Arrays.asList(projects)); // List<IProject> p List reducedProjects = new ArrayList(fullProjectOrder.projects.length); for (int i = 0; i < fullProjectOrder.projects.length; i++) { IProject project = fullProjectOrder.projects[i]; if (keepers.contains(project)) { // remove projects not in the initial subset reducedProjects.add(project); } } IProject[] p1 = new IProject[reducedProjects.size()]; reducedProjects.toArray(p1); // ... and from "fullProjectOrder.knots" // List<IProject[]> k List reducedKnots = new ArrayList(fullProjectOrder.knots.length); for (int i = 0; i < fullProjectOrder.knots.length; i++) { IProject[] knot = fullProjectOrder.knots[i]; List x = new ArrayList(knot.length); for (int j = 0; j < knot.length; j++) { IProject project = knot[j]; if (keepers.contains(project)) { x.add(project); } } // keep knots containing 2 or more projects in the specified subset if (x.size() > 1) { reducedKnots.add(x.toArray(new IProject[x.size()])); } } IProject[][] k1 = new IProject[reducedKnots.size()][]; // okay to use toArray here because reducedKnots elements are IProject[] reducedKnots.toArray(k1); return new ProjectOrder(p1, (k1.length > 0), k1); } /** * Computes the global total ordering of all open projects in the * workspace based on project references. If an existing and open project P * references another existing and open project Q also included in the list, * then Q should come before P in the resulting ordering. Closed and non- * existent projects are ignored, and will not appear in the result. References * to non-existent or closed projects are also ignored, as are any self- * references. * <p> * When there are choices, the choice is made in a reasonably stable way. For * example, given an arbitrary choice between two projects, the one with the * lower collating project name is usually selected. * </p> * <p> * When the project reference graph contains cyclic references, it is * impossible to honor all of the relationships. In this case, the result * ignores as few relationships as possible. For example, if P2 references P1, * P4 references P3, and P2 and P3 reference each other, then exactly one of the * relationships between P2 and P3 will have to be ignored. The outcome will be * either [P1, P2, P3, P4] or [P1, P3, P2, P4]. The result also contains * complete details of any cycles present. * </p> * * @return result describing the global project order * @since 2.1 */ private ProjectOrder computeFullProjectOrder() { // determine the full set of accessible projects in the workspace // order the set in descending alphabetical order of project name SortedSet allAccessibleProjects = new TreeSet(new Comparator() { public int compare(Object x, Object y) { IProject px = (IProject) x; IProject py = (IProject) y; return py.getName().compareTo(px.getName()); }}); IProject[] allProjects = getRoot().getProjects(); // List<IProject[]> edges List edges = new ArrayList(allProjects.length); for (int i = 0; i < allProjects.length; i++) { IProject project = allProjects[i]; // ignore projects that are not accessible if (project.isAccessible()) { allAccessibleProjects.add(project); IProject[] refs= null; try { refs = project.getReferencedProjects(); } catch (CoreException e) { // can't happen - project is accessible } for (int j = 0; j < refs.length; j++) { IProject ref = refs[j]; // ignore self references and references to projects that are // not accessible if (ref.isAccessible() && !ref.equals(project)) { edges.add(new IProject[] {project, ref}); } } } } ProjectOrder fullProjectOrder = ComputeProjectOrder.computeProjectOrder(allAccessibleProjects, edges); return fullProjectOrder; } /* * @see IWorkspace#copy */ public IStatus copy(IResource[] resources, IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { int opWork = Math.max(resources.length, 1); int totalWork = Policy.totalWork * opWork / Policy.opWork; String message = Policy.bind("resources.copying.0"); //$NON-NLS-1$ monitor.beginTask(message, totalWork); Assert.isLegal(resources != null); if (resources.length == 0) return ResourceStatus.OK_STATUS; // to avoid concurrent changes to this array resources = (IResource[]) resources.clone(); IPath parentPath = null; message = Policy.bind("resources.copyProblem"); //$NON-NLS-1$ MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null); try { prepareOperation(); beginOperation(true); for (int i = 0; i < resources.length; i++) { Policy.checkCanceled(monitor); IResource resource = resources[i]; if (resource == null || isDuplicate(resources, i)) { monitor.worked(1); continue; } // test siblings if (parentPath == null) parentPath = resource.getFullPath().removeLastSegments(1); if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) { // test copy requirements try { IPath destinationPath = destination.append(resource.getName()); IStatus requirements = ((Resource) resource).checkCopyRequirements(destinationPath, resource.getType(), updateFlags); if (requirements.isOK()) { try { resource.copy(destinationPath, updateFlags, Policy.subMonitorFor(monitor, 1)); } catch (CoreException e) { status.merge(e.getStatus()); } } else { monitor.worked(1); status.merge(requirements); } } catch (CoreException e) { monitor.worked(1); status.merge(e.getStatus()); } } else { monitor.worked(1); message = Policy.bind("resources.notChild", resources[i].getFullPath().toString(), parentPath.toString()); //$NON-NLS-1$ status.merge(new ResourceStatus(IResourceStatus.OPERATION_FAILED, resources[i].getFullPath(), message)); } } } catch (OperationCanceledException e) { getWorkManager().operationCanceled(); throw e; } finally { endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork)); } if (status.matches(IStatus.ERROR)) throw new ResourceException(status); return status.isOK() ? ResourceStatus.OK_STATUS : (IStatus) status; } finally { monitor.done(); } } /** * @see IWorkspace#copy */ public IStatus copy(IResource[] resources, IPath destination, boolean force, IProgressMonitor monitor) throws CoreException { int updateFlags = force ? IResource.FORCE : IResource.NONE; return copy(resources, destination, updateFlags , monitor); } protected void copyTree(IResource source, IPath destination, int depth, int updateFlags, boolean keepSyncInfo) throws CoreException { // retrieve the resource at the destination if there is one (phantoms included). // if there isn't one, then create a new handle based on the type that we are // trying to copy IResource destinationResource = getRoot().findMember(destination, true); if (destinationResource == null) { int destinationType; if (source.getType() == IResource.FILE) destinationType = IResource.FILE; else if (destination.segmentCount() == 1) destinationType = IResource.PROJECT; else destinationType = IResource.FOLDER; destinationResource = newResource(destination, destinationType); } // create the resource at the destination ResourceInfo sourceInfo = ((Resource) source).getResourceInfo(true, false); if (destinationResource.getType() != source.getType()) { sourceInfo = (ResourceInfo) sourceInfo.clone(); sourceInfo.setType(destinationResource.getType()); } ResourceInfo newInfo = createResource(destinationResource, sourceInfo, false, false, keepSyncInfo); // get/set the node id from the source's resource info so we can later put it in the // info for the destination resource. This will help us generate the proper deltas, // indicating a move rather than a add/delete long nodeid = ((Resource) source).getResourceInfo(true, false).getNodeId(); newInfo.setNodeId(nodeid); // preserve local sync info ResourceInfo oldInfo = ((Resource) source).getResourceInfo(true, false); newInfo.setFlags(newInfo.getFlags() | (oldInfo.getFlags() & M_LOCAL_EXISTS)); // update link locations in project descriptions if (source.isLinked()) { LinkDescription linkDescription; if ((updateFlags & IResource.SHALLOW) != 0) { //for shallow move the destination is also a linked resource newInfo.set(ICoreConstants.M_LINK); linkDescription = new LinkDescription(destinationResource, source.getLocation()); } else { //for deep move the destination is not a linked resource newInfo.clear(ICoreConstants.M_LINK); linkDescription = null; } Project project = (Project)destinationResource.getProject(); project.internalGetDescription().setLinkLocation(destinationResource.getName(), linkDescription); project.writeDescription(IResource.NONE); } // do the recursion. if we have a file then it has no members so return. otherwise // recursively call this method on the container's members if the depth tells us to if (depth == IResource.DEPTH_ZERO || source.getType() == IResource.FILE) return; if (depth == IResource.DEPTH_ONE) depth = IResource.DEPTH_ZERO; IResource[] children = ((IContainer) source).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); for (int i = 0; i < children.length; i++) { IResource child = children[i]; IPath childPath = destination.append(child.getName()); copyTree(child, childPath, depth, updateFlags, keepSyncInfo); } } /** * Returns the number of resources in a subtree of the resource tree. * @param path The subtree to count resources for * @param depth The depth of the subtree to count * @param phantom If true, phantoms are included, otherwise they are ignored. */ public int countResources(IPath root, int depth, final boolean phantom) { if (!tree.includes(root)) return 0; switch (depth) { case IResource.DEPTH_ZERO: return 1; case IResource.DEPTH_ONE: return 1 + tree.getChildCount(root); case IResource.DEPTH_INFINITE: final int[] count = new int[1]; IElementContentVisitor visitor = new IElementContentVisitor() { public void visitElement(ElementTree tree, IPathRequestor requestor, Object elementContents) { if (phantom || !((ResourceInfo)elementContents).isSet(M_PHANTOM)) count[0]++; } }; new ElementTreeIterator().iterate(tree, visitor, root); return count[0]; } return 0; } public ResourceInfo createResource(IResource resource, ResourceInfo info, boolean phantom, boolean overwrite) throws CoreException { return createResource(resource, info, phantom, overwrite, false); } /* * Creates the given resource in the tree and returns the new resource info object. * If phantom is true, the created element is marked as a phantom. * If there is already be an element in the tree for the given resource * in the given state (i.e., phantom), a CoreException is thrown. * If there is already a phantom in the tree and the phantom flag is false, * the element is overwritten with the new element. (but the synchronization * information is preserved) If the specified resource info is null, then create * a new one. * * If keepSyncInfo is set to be true, the sync info in the given ResourceInfo is NOT * cleared before being created and thus any sync info already existing at that namespace * (as indicated by an already existing phantom resource) will be lost. */ public ResourceInfo createResource(IResource resource, ResourceInfo info, boolean phantom, boolean overwrite, boolean keepSyncInfo) throws CoreException { info = info == null ? newElement(resource.getType()) : (ResourceInfo) info.clone(); ResourceInfo original = getResourceInfo(resource.getFullPath(), true, false); if (phantom) { info.set(M_PHANTOM); info.setModificationStamp(IResource.NULL_STAMP); } // if nothing existed at the destination then just create the resource in the tree if (original == null) { // we got here from a copy/move. we don't want to copy over any sync info // from the source so clear it. if (!keepSyncInfo) info.setSyncInfo(null); tree.createElement(resource.getFullPath(), info); } else { // if overwrite==true then slam the new info into the tree even if one existed before if (overwrite || (!phantom && original.isSet(M_PHANTOM))) { // copy over the sync info and flags from the old resource info // since we are replacing a phantom with a real resource // DO NOT set the sync info dirty flag because we want to // preserve the old sync info so its not dirty // XXX: must copy over the generic sync info from the old info to the new // XXX: do we really need to clone the sync info here? if (!keepSyncInfo) info.setSyncInfo(original.getSyncInfo(true)); // mark the markers bit as dirty so we snapshot an empty marker set for // the new resource info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY); tree.setElementData(resource.getFullPath(), info); } else { String message = Policy.bind("resources.mustNotExist", resource.getFullPath().toString()); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.RESOURCE_EXISTS, resource.getFullPath(), message, null); } } return info; } /* * Creates the given resource in the tree and returns the new resource info object. * If phantom is true, the created element is marked as a phantom. * If there is already be an element in the tree for the given resource * in the given state (i.e., phantom), a CoreException is thrown. * If there is already a phantom in the tree and the phantom flag is false, * the element is overwritten with the new element. (but the synchronization * information is preserved) */ public ResourceInfo createResource(IResource resource, boolean phantom) throws CoreException { return createResource(resource, null, phantom, false); } public ResourceInfo createResource(IResource resource, boolean phantom, boolean overwrite) throws CoreException { return createResource(resource, null, phantom, overwrite); } public static WorkspaceDescription defaultWorkspaceDescription() { return new WorkspaceDescription("Workspace"); //$NON-NLS-1$ } /* * @see IWorkspace#delete */ public IStatus delete(IResource[] resources, int updateFlags, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { int opWork = Math.max(resources.length, 1); int totalWork = Policy.totalWork * opWork / Policy.opWork; String message = Policy.bind("resources.deleting.0"); //$NON-NLS-1$ monitor.beginTask(message, totalWork); message = Policy.bind("resources.deleteProblem"); //$NON-NLS-1$ MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null); if (resources.length == 0) return result; resources = (IResource[]) resources.clone(); // to avoid concurrent changes to this array try { prepareOperation(); beginOperation(true); for (int i = 0; i < resources.length; i++) { Policy.checkCanceled(monitor); Resource resource = (Resource) resources[i]; if (resource == null) { monitor.worked(1); continue; } try { resource.delete(updateFlags, Policy.subMonitorFor(monitor, 1)); } catch (CoreException e) { // Don't really care about the exception unless the resource is still around. ResourceInfo info = resource.getResourceInfo(false, false); if (resource.exists(resource.getFlags(info), false)) { message = Policy.bind("resources.couldnotDelete", resource.getFullPath().toString()); //$NON-NLS-1$ result.merge(new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, resource.getFullPath(), message)); result.merge(e.getStatus()); } } } if (result.matches(IStatus.ERROR)) throw new ResourceException(result); return result; } catch (OperationCanceledException e) { getWorkManager().operationCanceled(); throw e; } finally { endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork)); } } finally { monitor.done(); } } /* * @see IWorkspace#delete */ public IStatus delete(IResource[] resources, boolean force, IProgressMonitor monitor) throws CoreException { int updateFlags = force ? IResource.FORCE : IResource.NONE; updateFlags |= IResource.KEEP_HISTORY; return delete(resources, updateFlags, monitor); } /** * @see IWorkspace */ public void deleteMarkers(IMarker[] markers) throws CoreException { Assert.isNotNull(markers); if (markers.length == 0) return; // clone to avoid outside changes markers = (IMarker[]) markers.clone(); try { prepareOperation(); beginOperation(true); for (int i = 0; i < markers.length; ++i) if (markers[i] != null && markers[i].getResource() != null) markerManager.removeMarker(markers[i].getResource(), markers[i].getId()); } finally { endOperation(false, null); } } /** * Delete the given resource from the current tree of the receiver. * This method simply removes the resource from the tree. No cleanup or * other management is done. Use IResource.delete for proper deletion. * If the given resource is the root, all of its children (i.e., all projects) are * deleted but the root is left. */ void deleteResource(IResource resource) { IPath path = resource.getFullPath(); if (path.equals(Path.ROOT)) { IProject[] children = getRoot().getProjects(); for (int i = 0; i < children.length; i++) tree.deleteElement(children[i].getFullPath()); } else tree.deleteElement(path); } /** * For debugging purposes only. Dumps plugin stats to console */ public void dumpStats() { EventStats.dumpStats(); } /** * End an operation (group of resource changes). * Notify interested parties that some resource changes have taken place. * This is used in the middle of batch executions to broadcast intermediate * results. All registered resource change listeners are notified. If autobuilding * is enabled, a build is run. */ public void endOperation(boolean build, IProgressMonitor monitor) throws CoreException { WorkManager workManager = getWorkManager(); try { workManager.setBuild(build); // if we are not exiting a top level operation then just decrement the count and return if (workManager.getPreparedOperationDepth() > 1) return; // do the following in a try/finally to ensure that the operation tree is null'd at the end // as we are completing a top level operation. try { // if the tree is locked we likely got here in some finally block after a failed begin. // Since the tree is locked, nothing could have been done so there is nothing to do. Assert.isTrue(!(treeLocked && workManager.shouldBuild()), "The tree should not be locked."); //$NON-NLS-1$ // check for a programming error on using beginOperation/endOperation Assert.isTrue(workManager.getPreparedOperationDepth() > 0, "Mismatched begin/endOperation"); //$NON-NLS-1$ // At this time we need to rebalance the nested operations. It is necessary because // build() and snapshot() should not fail if they are called. workManager.rebalanceNestedOperations(); // If autobuild is on, give each open project a chance to build. We have to tell each one // because there is no way of knowing whether or not there is a relevant change // for the project without computing the delta for each builder in each project relative // to its last built state. If we have guaranteed corelation between the notification delta // and the last time autobuild was done, then we could look at the notification delta and // see which projects had changed and only build them. Currently there is no such // guarantee. // Note that building a project when there is actually nothing to do is not free but // is should not be too expensive. The computed delta will be empty and so the builder itself // will not actually be run. This does require however the delta computation. // // This is done in a try finally to ensure that we always decrement the operation count. // The operationCount cannot be decremented before this as the build must be done // inside an operation. Note that we only ever get here if we are at a top level operation. // As such, the operationCount will always be 0 (zero) after this. OperationCanceledException cancel = null; CoreException signal = null; monitor = Policy.monitorFor(monitor); monitor.subTask(MSG_RESOURCES_UPDATING); //$NON-NLS-1$ broadcastChanges(tree, IResourceChangeEvent.PRE_AUTO_BUILD, false, false, Policy.monitorFor(null)); if (isAutoBuilding() && shouldBuild()) { try { getBuildManager().build(IncrementalProjectBuilder.AUTO_BUILD, monitor); } catch (OperationCanceledException e) { cancel = e; } catch (CoreException sig) { signal = sig; } } broadcastChanges(tree, IResourceChangeEvent.POST_AUTO_BUILD, false, false, Policy.monitorFor(null)); broadcastChanges(tree, IResourceChangeEvent.POST_CHANGE, true, true, Policy.monitorFor(null)); getMarkerManager().resetMarkerDeltas(); // Perform a snapshot if we are sufficiently out of date. Be sure to make the tree immutable first tree.immutable(); saveManager.snapshotIfNeeded(); //make sure the monitor subtask message is cleared. monitor.subTask(""); //$NON-NLS-1$ if (cancel != null) throw cancel; if (signal != null) throw signal; } finally { // make sure that the tree is immutable. Only do this if we are ending a top-level operation. tree.immutable(); operationTree = null; } } finally { workManager.checkOut(); } } /** * Flush the build order cache for the workspace. Only needed if the * description does not already have a build order. That is, if this * is really a cache. */ protected void flushBuildOrder() { if (description.getBuildOrder(false) == null) buildOrder = null; } /** * @see IWorkspace */ public void forgetSavedTree(String pluginId) { Assert.isNotNull(pluginId, "PluginId must not be null"); //$NON-NLS-1$ saveManager.forgetSavedTree(pluginId); } public AliasManager getAliasManager() { return aliasManager; } /** * Returns this workspace's build manager */ public BuildManager getBuildManager() { return buildManager; } /** * Returns the order in which open projects in this workspace will be built. * <p> * The project build order is based on information specified in the workspace * description. The projects are built in the order specified by * <code>IWorkspaceDescription.getBuildOrder</code>; closed or non-existent * projects are ignored and not included in the result. If * <code>IWorkspaceDescription.getBuildOrder</code> is non-null, the default * build order is used; again, only open projects are included in the result. * </p> * <p> * The returned value is cached in the <code>buildOrder</code> field. * </p> * * @return the list of currently open projects in the workspace in the order in * which they would be built by <code>IWorkspace.build</code>. * @see IWorkspace#build * @see IWorkspaceDescription#getBuildOrder * @since 2.1 */ public IProject[] getBuildOrder() { if (buildOrder != null) { // return previously-computed and cached project build order return buildOrder; } // see if a particular build order is specified String[] order = description.getBuildOrder(false); if (order != null) { // convert from project names to project handles // and eliminate non-existent and closed projects List projectList = new ArrayList(order.length); for (int i = 0; i < order.length; i++) { IProject project = getRoot().getProject(order[i]); //FIXME should non-accessible projects be removed? if (project.isAccessible()) { projectList.add(project); } } buildOrder = new IProject[projectList.size()]; projectList.toArray(buildOrder); } else { // use default project build order // computed for all accessible projects in workspace buildOrder = computeFullProjectOrder().projects; } return buildOrder; } /** * @see IWorkspace#getDanglingReferences */ public Map getDanglingReferences() { IProject[] projects = getRoot().getProjects(); Map result = new HashMap(projects.length); for (int i = 0; i < projects.length; i++) { Project project = (Project) projects[i]; if (!project.isAccessible()) continue; IProject[] refs = project.internalGetDescription().getReferencedProjects(false); List dangling = new ArrayList(refs.length); for (int j = 0; j < refs.length; j++) if (!refs[i].exists()) dangling.add(refs[i]); if (!dangling.isEmpty()) result.put(projects[i], dangling.toArray(new IProject[dangling.size()])); } return result; } /** * @see IWorkspace */ public IWorkspaceDescription getDescription() { WorkspaceDescription workingCopy = defaultWorkspaceDescription(); description.copyTo(workingCopy); return workingCopy; } /** * Returns the current element tree for this workspace */ public ElementTree getElementTree() { return tree; } public FileSystemResourceManager getFileSystemManager() { return fileSystemManager; } /** * Returns the marker manager for this workspace */ public MarkerManager getMarkerManager() { return markerManager; } public LocalMetaArea getMetaArea() { return localMetaArea; } protected IMoveDeleteHook getMoveDeleteHook() { if (moveDeleteHook == null) initializeMoveDeleteHook(); return moveDeleteHook; } /** * @see IWorkspace#getNatureDescriptor(String) */ public IProjectNatureDescriptor getNatureDescriptor(String natureId) { return natureManager.getNatureDescriptor(natureId); } /** * @see IWorkspace#getNatureDescriptors() */ public IProjectNatureDescriptor[] getNatureDescriptors() { return natureManager.getNatureDescriptors(); } /** * Returns the nature manager for this workspace. */ public NatureManager getNatureManager() { return natureManager; } public NotificationManager getNotificationManager() { return notificationManager; } /** * @see org.eclipse.core.resources.IWorkspace#getPathVariableManager() */ public IPathVariableManager getPathVariableManager() { return pathVariableManager; } public PropertyManager getPropertyManager() { return propertyManager; } /** * Returns the resource info for the identified resource. * null is returned if no such resource can be found. * If the phantom flag is true, phantom resources are considered. * If the mutable flag is true, the info is opened for change. * * This method DOES NOT throw an exception if the resource is not found. */ public ResourceInfo getResourceInfo(IPath path, boolean phantom, boolean mutable) { try { if (path.segmentCount() == 0) { ResourceInfo info = (ResourceInfo)tree.getTreeData(); Assert.isNotNull(info, "Tree root info must never be null"); //$NON-NLS-1$ return info; } ResourceInfo result = null; if (!tree.includes(path)) return null; if (mutable) result = (ResourceInfo) tree.openElementData(path); else result = (ResourceInfo) tree.getElementData(path); if (result != null && (!phantom && result.isSet(M_PHANTOM))) return null; return result; } catch (IllegalArgumentException e) { return null; } } /** * @see IWorkspace#getRoot */ public IWorkspaceRoot getRoot() { return defaultRoot; } public SaveManager getSaveManager() { return saveManager; } /** * @see IWorkspace#getSynchronizer */ public ISynchronizer getSynchronizer() { return synchronizer; } /** * Returns the installed team hook. Never returns null. */ protected TeamHook getTeamHook() { if (teamHook == null) initializeTeamHook(); return teamHook; } /** * We should not have direct references to this field. All references should go through * this method. */ public WorkManager getWorkManager() throws CoreException { if (workManager == null) { String message = Policy.bind("resources.shutdown"); //$NON-NLS-1$ throw new ResourceException(new ResourceStatus(IResourceStatus.INTERNAL_ERROR, null, message)); } return workManager; } /** * A file modification validator hasn't been initialized. Check the extension point and * try to create a new validator if a user has one defined as an extension. */ protected void initializeValidator() { shouldValidate = false; IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_FILE_MODIFICATION_VALIDATOR); // no-one is plugged into the extension point so disable validation if (configs == null || configs.length == 0) { return; } // can only have one defined at a time. log a warning, disable validation, but continue with // the #setContents (e.g. don't throw an exception) if (configs.length > 1) { //XXX: shoud provide a meaningful status code IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneValidator"), null); //$NON-NLS-1$ ResourcesPlugin.getPlugin().getLog().log(status); return; } // otherwise we have exactly one validator extension. Try to create a new instance // from the user-specified class. try { IConfigurationElement config = configs[0]; validator = (IFileModificationValidator) config.createExecutableExtension("class"); //$NON-NLS-1$ shouldValidate = true; } catch (CoreException e) { //XXX: shoud provide a meaningful status code IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initValidator"), e); //$NON-NLS-1$ ResourcesPlugin.getPlugin().getLog().log(status); } } /** * A move/delete hook hasn't been initialized. Check the extension point and * try to create a new hook if a user has one defined as an extension. Otherwise * use the Core's implementation as the default. */ protected void initializeMoveDeleteHook() { try { IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_MOVE_DELETE_HOOK); // no-one is plugged into the extension point so disable validation if (configs == null || configs.length == 0) { return; } // can only have one defined at a time. log a warning if (configs.length > 1) { //XXX: shoud provide a meaningful status code IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneHook"), null); //$NON-NLS-1$ ResourcesPlugin.getPlugin().getLog().log(status); return; } // otherwise we have exactly one hook extension. Try to create a new instance // from the user-specified class. try { IConfigurationElement config = configs[0]; moveDeleteHook = (IMoveDeleteHook) config.createExecutableExtension("class"); //$NON-NLS-1$ } catch (CoreException e) { //XXX: shoud provide a meaningful status code IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initHook"), e); //$NON-NLS-1$ ResourcesPlugin.getPlugin().getLog().log(status); } } finally { // for now just use Core's implementation if (moveDeleteHook == null) moveDeleteHook = new MoveDeleteHook(); } } /** * A team hook hasn't been initialized. Check the extension point and * try to create a new hook if a user has one defined as an extension. * Otherwise use the Core's implementation as the default. */ protected void initializeTeamHook() { try { IConfigurationElement[] configs = Platform.getPluginRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_TEAM_HOOK); // no-one is plugged into the extension point so disable validation if (configs == null || configs.length == 0) { return; } // can only have one defined at a time. log a warning if (configs.length > 1) { //XXX: shoud provide a meaningful status code IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.oneTeamHook"), null); //$NON-NLS-1$ ResourcesPlugin.getPlugin().getLog().log(status); return; } // otherwise we have exactly one hook extension. Try to create a new instance // from the user-specified class. try { IConfigurationElement config = configs[0]; teamHook = (TeamHook) config.createExecutableExtension("class"); //$NON-NLS-1$ } catch (CoreException e) { //XXX: shoud provide a meaningful status code IStatus status = new ResourceStatus(IResourceStatus.ERROR, 1, null, Policy.bind("resources.initTeamHook"), e); //$NON-NLS-1$ ResourcesPlugin.getPlugin().getLog().log(status); } } finally { // default to use Core's implementation if (teamHook == null) teamHook = new TeamHook(); } } public WorkspaceDescription internalGetDescription() { return description; } /** * @see IWorkspace */ public boolean isAutoBuilding() { return description.isAutoBuilding(); } /** * Returns true if the object at the specified position has any * other copy in the given array. */ private static boolean isDuplicate(Object[] array, int position) { if (array == null || position >= array.length) return false; for (int j = position - 1; j >= 0; j--) if (array[j].equals(array[position])) return true; return false; } /** * @see IWorkspace#isOpen */ public boolean isOpen() { return openFlag; } /** * Returns true if the given file system locations overlap (they are the same, * or one is a proper prefix of the other), and false otherwise. * Does the right thing with respect to case insensitive platforms. */ protected boolean isOverlapping(IPath location1, IPath location2) { IPath one = location1; IPath two = location2; // If we are on a case-insensitive file system then convert to all lowercase. if (!CoreFileSystemLibrary.isCaseSensitive()) { one = new Path(location1.toOSString().toLowerCase()); two = new Path(location2.toOSString().toLowerCase()); } return one.isPrefixOf(two) || two.isPrefixOf(one); } public boolean isTreeLocked() { return treeLocked; } /** * Link the given tree into the receiver's tree at the specified resource. */ protected void linkTrees(IPath path, ElementTree[] newTrees) throws CoreException { tree = tree.mergeDeltaChain(path, newTrees); } /** * @see IWorkspace#loadProjectDescription * @since 2.0 */ public IProjectDescription loadProjectDescription(IPath path) throws CoreException { IProjectDescription result = null; IOException e = null; try { result = (IProjectDescription) new ModelObjectReader().read(path); if (result != null) { // check to see if we are using in the default area or not. use java.io.File for // testing equality because it knows better w.r.t. drives and case sensitivity IPath user = path.removeLastSegments(1); IPath platform = Platform.getLocation().append(result.getName()); if (!user.toFile().equals(platform.toFile())) result.setLocation(user); } } catch (IOException ex) { e = ex; } if (result == null || e != null) { String message = Policy.bind("resources.errorReadProject", path.toOSString());//$NON-NLS1 //$NON-NLS-1$ IStatus status = new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, message, e); throw new ResourceException(status); } return result; } /* * @see IWorkspace#move */ public IStatus move(IResource[] resources, IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { int opWork = Math.max(resources.length, 1); int totalWork = Policy.totalWork * opWork / Policy.opWork; String message = Policy.bind("resources.moving.0"); //$NON-NLS-1$ monitor.beginTask(message, totalWork); Assert.isLegal(resources != null); if (resources.length == 0) return ResourceStatus.OK_STATUS; resources = (IResource[]) resources.clone(); // to avoid concurrent changes to this array IPath parentPath = null; message = Policy.bind("resources.moveProblem"); //$NON-NLS-1$ MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null); try { prepareOperation(); beginOperation(true); for (int i = 0; i < resources.length; i++) { Policy.checkCanceled(monitor); Resource resource = (Resource) resources[i]; if (resource == null || isDuplicate(resources, i)) { monitor.worked(1); continue; } // test siblings if (parentPath == null) parentPath = resource.getFullPath().removeLastSegments(1); if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) { // test move requirements try { IStatus requirements = resource.checkMoveRequirements(destination.append(resource.getName()), resource.getType(), updateFlags); if (requirements.isOK()) { try { resource.move(destination.append(resource.getName()), updateFlags, Policy.subMonitorFor(monitor, 1)); } catch (CoreException e) { status.merge(e.getStatus()); } } else { monitor.worked(1); status.merge(requirements); } } catch (CoreException e) { monitor.worked(1); status.merge(e.getStatus()); } } else { monitor.worked(1); message = Policy.bind("resources.notChild", resource.getFullPath().toString(), parentPath.toString()); //$NON-NLS-1$ status.merge(new ResourceStatus(IResourceStatus.OPERATION_FAILED, resource.getFullPath(), message)); } } } catch (OperationCanceledException e) { getWorkManager().operationCanceled(); throw e; } finally { endOperation(true, Policy.subMonitorFor(monitor, totalWork - opWork)); } if (status.matches(IStatus.ERROR)) throw new ResourceException(status); return status.isOK() ? (IStatus) ResourceStatus.OK_STATUS : (IStatus) status; } finally { monitor.done(); } } /** * @see IWorkspace#move */ public IStatus move(IResource[] resources, IPath destination, boolean force, IProgressMonitor monitor) throws CoreException { int updateFlags = force ? IResource.FORCE : IResource.NONE; updateFlags |= IResource.KEEP_HISTORY; return move(resources, destination, updateFlags, monitor); } /** * Moves this resource's subtree to the destination. This operation should only be * used by move methods. Destination must be a valid destination for this resource. * The keepSyncInfo boolean is used to indicated whether or not the sync info should * be moved from the source to the destination. */ /* package */ void move(Resource source, IPath destination, int depth, int updateFlags, boolean keepSyncInfo) throws CoreException { // overlay the tree at the destination path, preserving any important info // in any already existing resource infos copyTree(source, destination, depth, updateFlags, keepSyncInfo); source.fixupAfterMoveSource(); } /** * Create and return a new tree element of the given type. */ protected ResourceInfo newElement(int type) { ResourceInfo result = null; switch (type) { case IResource.FILE : case IResource.FOLDER : result = new ResourceInfo(); break; case IResource.PROJECT : result = new ProjectInfo(); break; case IResource.ROOT : result = new RootInfo(); break; } result.setNodeId(nextNodeId()); result.setModificationStamp(nextModificationStamp()); result.setType(type); return result; } /** * @see IWorkspace#newProjectDescription */ public IProjectDescription newProjectDescription(String projectName) { IProjectDescription result = new ProjectDescription(); result.setName(projectName); return result; } public Resource newResource(IPath path, int type) { String message; switch (type) { case IResource.FOLDER : message = "Path must include project and resource name."; //$NON-NLS-1$ Assert.isLegal(path.segmentCount() >= ICoreConstants.MINIMUM_FOLDER_SEGMENT_LENGTH , message); return new Folder(path.makeAbsolute(), this); case IResource.FILE : message = "Path must include project and resource name."; //$NON-NLS-1$ Assert.isLegal(path.segmentCount() >= ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH, message); return new File(path.makeAbsolute(), this); case IResource.PROJECT : return (Resource) getRoot().getProject(path.lastSegment()); case IResource.ROOT : return (Resource) getRoot(); } Assert.isLegal(false); // will never get here because of assertion. return null; } /** * Opens a new mutable element tree layer, thus allowing * modifications to the tree. */ public ElementTree newWorkingTree() { tree = tree.newEmptyDelta(); return tree; } /** * Returns the next, previously unassigned, marker id. */ protected long nextMarkerId() { return nextMarkerId++; } public long nextModificationStamp() { return nextModificationStamp++; } public long nextNodeId() { return nextNodeId++; } /** * Opens this workspace using the data at its location in the local file system. * This workspace must not be open. * If the operation succeeds, the result will detail any serious * (but non-fatal) problems encountered while opening the workspace. * The status code will be <code>OK</code> if there were no problems. * An exception is thrown if there are fatal problems opening the workspace, * in which case the workspace is left closed. * <p> * This method is long-running; progress and cancellation are provided * by the given progress monitor. * </p> * * @param monitor a progress monitor, or <code>null</code> if progress * reporting and cancellation are not desired * @return status with code <code>OK</code> if no problems; * otherwise status describing any serious but non-fatal problems. * * @exception CoreException if the workspace could not be opened. * Reasons include: * <ul> * <li> There is no valid workspace structure at the given location * in the local file system.</li> * <li> The workspace structure on disk appears to be hopelessly corrupt.</li> * </ul> * @see IWorkspace#getLocation * @see ResourcePlugin#containsWorkspace */ public IStatus open(IProgressMonitor monitor) throws CoreException { // This method is not inside an operation because it is the one responsible for // creating the WorkManager object (who takes care of operations). String message = Policy.bind("resources.workspaceOpen"); //$NON-NLS-1$ Assert.isTrue(!isOpen(), message); if (!getMetaArea().hasSavedWorkspace()) { message = Policy.bind("resources.readWorkspaceMeta"); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.FAILED_READ_METADATA, Platform.getLocation(), message, null); } description = new WorkspacePreferences(); description.setDefaults(Workspace.defaultWorkspaceDescription()); // if we have an old description file, read it (getting rid of it) WorkspaceDescription oldDescription = getMetaArea().readOldWorkspace(); if (oldDescription != null) { description.copyFrom(oldDescription); ResourcesPlugin.getPlugin().savePluginPreferences(); } // create root location localMetaArea.locationFor(getRoot()).toFile().mkdirs(); // turn off autobuilding while we open the workspace. This is in // case an operation is triggered. We don't want to do an autobuild // just yet. Any changes will be reported the next time we build. boolean oldBuildFlag = description.isAutoBuilding(); try { description.setAutoBuilding(false); IProgressMonitor nullMonitor = Policy.monitorFor(null); startup(nullMonitor); //restart the notification manager so it is initialized with the right tree notificationManager.startup(null); openFlag = true; if (crashed || refreshRequested()) { try { getRoot().refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { //don't fail entire open if refresh failed, just report as minor warning return e.getStatus(); } } return ResourceStatus.OK_STATUS; } finally { description.setAutoBuilding(oldBuildFlag); } } /** * Called before checking the pre-conditions of an operation. */ public void prepareOperation() throws CoreException { getWorkManager().checkIn(); if (!isOpen()) { String message = Policy.bind("resources.workspaceClosed"); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.OPERATION_FAILED, null, message, null); } } protected boolean refreshRequested() { String[] args = Platform.getCommandLineArgs(); for (int i = 0; i < args.length; i++) if (args[i].equalsIgnoreCase(REFRESH_ON_STARTUP)) return true; return false; } /** * @see IWorkspace */ public void removeResourceChangeListener(IResourceChangeListener listener) { notificationManager.removeListener(listener); } /** * @see IWorkspace */ public void removeSaveParticipant(Plugin plugin) { Assert.isNotNull(plugin, "Plugin must not be null"); //$NON-NLS-1$ saveManager.removeParticipant(plugin); } /** * @see IWorkspace#run */ public void run(IWorkspaceRunnable job, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(null, Policy.totalWork); try { prepareOperation(); beginOperation(true); job.run(Policy.subMonitorFor(monitor, Policy.opWork, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); } catch (OperationCanceledException e) { getWorkManager().operationCanceled(); throw e; } finally { endOperation(false, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * @see IWorkspace */ public IStatus save(boolean full, IProgressMonitor monitor) throws CoreException { String message; // if a full save was requested, and this is a top-level op, try the save. Otherwise // fail the operation. if (full) { // If the workmanager thread is null or is different than this thread // it is OK to start the save because it will wait until the other thread // is finished. Otherwise, someone in this thread has tried to do a save // inside of an operation (which is not allowed by the spec). if (getWorkManager().getCurrentOperationThread() == Thread.currentThread()) { message = Policy.bind("resources.saveOp"); //$NON-NLS-1$ throw new ResourceException(IResourceStatus.OPERATION_FAILED, null, message, null); } return saveManager.save(ISaveContext.FULL_SAVE, null, monitor); } // A snapshot was requested. Start an operation (if not already started) and // signal that a snapshot should be done at the end. try { prepareOperation(); beginOperation(false); saveManager.requestSnapshot(); message = Policy.bind("resources.snapRequest"); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.OK, message); } finally { endOperation(false, null); } } public void setCrashed(boolean value) { crashed = value; } /** * @see IWorkspace */ public void setDescription(IWorkspaceDescription value) throws CoreException { // if both the old and new description's build orders are null, leave the // workspace's build order slot because it is caching the computed order. // Otherwise, set the slot to null to force recomputation or building from the description. WorkspaceDescription newDescription = (WorkspaceDescription) value; String[] newOrder = newDescription.getBuildOrder(false); if (description.getBuildOrder(false) != null || newOrder != null) buildOrder = null; description.copyFrom(newDescription); Policy.setupAutoBuildProgress(description.isAutoBuilding()); ResourcesPlugin.getPlugin().savePluginPreferences(); } public void setTreeLocked(boolean locked) { treeLocked = locked; } public void setWorkspaceLock(WorkspaceLock lock) { workManager.setWorkspaceLock(lock); } private boolean shouldBuild() throws CoreException { return getWorkManager().shouldBuild() && ElementTree.hasChanges(tree, operationTree, ResourceComparator.getComparator(false), true); } protected void shutdown(IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { IManager[] managers = { buildManager, notificationManager, propertyManager, pathVariableManager, fileSystemManager, markerManager, saveManager, workManager, aliasManager}; monitor.beginTask(null, managers.length); String message = Policy.bind("resources.shutdownProblems"); //$NON-NLS-1$ MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, null); // best effort to shutdown every object and free resources for (int i = 0; i < managers.length; i++) { IManager manager = managers[i]; if (manager == null) monitor.worked(1); else { try { manager.shutdown(Policy.subMonitorFor(monitor, 1)); } catch (Exception e) { message = Policy.bind("resources.shutdownProblems"); //$NON-NLS-1$ status.add(new Status(Status.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, message, e)); } } } buildManager = null; notificationManager = null; propertyManager = null; pathVariableManager = null; fileSystemManager = null; markerManager = null; synchronizer = null; saveManager = null; workManager = null; if (!status.isOK()) throw new CoreException(status); } finally { monitor.done(); } } /** * @see IWorkspace#sortNatureSet(String[]) */ public String[] sortNatureSet(String[] natureIds) { return natureManager.sortNatureSet(natureIds); } protected void startup(IProgressMonitor monitor) throws CoreException { // ensure the tree is locked during the startup notification workManager = new WorkManager(this); workManager.startup(null); fileSystemManager = new FileSystemResourceManager(this); fileSystemManager.startup(monitor); propertyManager = new PropertyManager(this); propertyManager.startup(monitor); pathVariableManager = new PathVariableManager(this); pathVariableManager.startup(null); natureManager = new NatureManager(); natureManager.startup(null); buildManager = new BuildManager(this); buildManager.startup(null); notificationManager = new NotificationManager(this); notificationManager.startup(null); markerManager = new MarkerManager(this); markerManager.startup(null); synchronizer = new Synchronizer(this); saveManager = new SaveManager(this); saveManager.startup(null); //must start after save manager, because (read) access to tree is needed aliasManager = new AliasManager(this); aliasManager.startup(null); treeLocked = false; // unlock the tree. } /** * Returns a string representation of this working state's * structure suitable for debug purposes. */ public String toDebugString() { final StringBuffer buffer = new StringBuffer("\nDump of " + toString() + ":\n"); //$NON-NLS-1$ //$NON-NLS-2$ buffer.append(" parent: " + tree.getParent()); //$NON-NLS-1$ ElementTreeIterator iterator = new ElementTreeIterator(); IElementPathContentVisitor visitor = new IElementPathContentVisitor() { public void visitElement(ElementTree tree, IPath path, Object elementContents) { buffer.append("\n " + path + ": " + elementContents); //$NON-NLS-1$ //$NON-NLS-2$ } }; iterator.iterateWithPath(tree, visitor, Path.ROOT); return buffer.toString(); } public void updateModificationStamp(ResourceInfo info) { info.setModificationStamp(nextModificationStamp()); } /* (non-javadoc) * Method declared on IWorkspace. */ public IStatus validateEdit(final IFile[] files, final Object context) { // if validation is turned off then just return if (!shouldValidate) { String message = Policy.bind("resources.readOnly2"); //$NON-NLS-1$ MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IStatus.OK, message, null); for (int i=0; i<files.length; i++) { if (files[i].isReadOnly()) { IPath filePath = files[i].getFullPath(); message = Policy.bind("resources.readOnly", filePath.toString()); //$NON-NLS-1$ result.add(new ResourceStatus(IResourceStatus.FAILED_WRITE_LOCAL, filePath, message)); } } return result.isOK() ? ResourceStatus.OK_STATUS : (IStatus) result; } // first time through the validator hasn't been initialized so try and create it if (validator == null) initializeValidator(); // we were unable to initialize the validator. Validation has been turned off and // a warning has already been logged so just return. if (validator == null) return ResourceStatus.OK_STATUS; // otherwise call the API and throw an exception if appropriate final IStatus[] status = new IStatus[1]; ISafeRunnable body = new ISafeRunnable() { public void run() throws Exception { status[0] = validator.validateEdit(files, context); } public void handleException(Throwable exception) { status[0] = new ResourceStatus(IResourceStatus.ERROR, null, Policy.bind("resources.errorValidator"), exception); //$NON-NLS-1$ } }; Platform.run(body); return status[0]; } /* (non-javadoc) * Method declared on IWorkspace. */ public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) { //check that the resource has a project as its parent String message; IContainer parent = resource.getParent(); if (parent == null || parent.getType() != IResource.PROJECT) { message = Policy.bind("links.parentNotProject", resource.getFullPath().toString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } if (!parent.isAccessible()) { message = Policy.bind("links.parentNotAccessible", resource.getFullPath().toString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } IPath location = getPathVariableManager().resolvePath(unresolvedLocation); //check nature veto String[] natureIds = ((Project)parent).internalGetDescription().getNatureIds(); IStatus result = getNatureManager().validateLinkCreation(natureIds); if (!result.isOK()) return result; //check team provider veto if (resource.getType() == IResource.FILE) result = getTeamHook().validateCreateLink((IFile)resource, IResource.NONE, location); else result = getTeamHook().validateCreateLink((IFolder)resource, IResource.NONE, location); if (!result.isOK()) return result; //check the standard path name restrictions int segmentCount = location.segmentCount(); for (int i = 0; i < segmentCount; i++) { result = validateName(location.segment(i), resource.getType()); if (!result.isOK()) return result; } //if the location doesn't have a device, see if the OS will assign one if (location.getDevice() == null) location = new Path(location.toFile().getAbsolutePath()); // test if the given location overlaps the platform metadata location IPath testLocation = getMetaArea().getLocation(); if (isOverlapping(location, testLocation)) { message = Policy.bind("links.invalidLocation", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } //test if the given path overlaps the location of the given project testLocation = resource.getProject().getLocation(); if (isOverlapping(location, testLocation)) { message = Policy.bind("links.locationOverlapsProject", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } //check that the location is absolute //Note: this check must be done last because we tolerate this condition in createLink if (!location.isAbsolute()) { if (location.segmentCount() > 0) message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$ else message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message); } // Iterate over each known project and ensure that the location does not // conflict with any project locations or linked resource locations IProject[] projects = getRoot().getProjects(); for (int i = 0; i < projects.length; i++) { IProject project = (IProject) projects[i]; // since we are iterating over the project in the workspace, we // know that they have been created before and must have a description IProjectDescription desc = ((Project) project).internalGetDescription(); testLocation = desc.getLocation(); - // if the project uses the default location then continue - if (testLocation == null) - continue; - if (isOverlapping(location, testLocation)) { + if (testLocation != null && isOverlapping(location, testLocation)) { message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message); } //iterate over linked resources and check for overlap if (!project.isOpen()) continue; IResource[] children = null; try { children = project.members(); } catch (CoreException e) { //ignore projects that cannot be accessed } if (children == null) continue; for (int j = 0; j < children.length; j++) { if (children[j].isLinked()) { testLocation = children[j].getLocation(); - if (isOverlapping(location, testLocation)) { + if (testLocation != null && isOverlapping(location, testLocation)) { message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message); } } } } return ResourceStatus.OK_STATUS; } /** * @see IWorkspace#validateName */ public IStatus validateName(String segment, int type) { String message; /* segment must not be null */ if (segment == null) { message = Policy.bind("resources.nameNull"); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } // cannot be an empty string if (segment.length() == 0) { message = Policy.bind("resources.nameEmpty"); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* segment must not begin or end with a whitespace */ if (Character.isWhitespace(segment.charAt(0)) || Character.isWhitespace(segment.charAt(segment.length() - 1))) { message = Policy.bind("resources.invalidWhitespace",segment); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* segment must not end with a dot */ if (segment.endsWith(".")) { //$NON-NLS-1$ message = Policy.bind("resources.invalidDot", segment); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* test invalid characters */ char[] chars = OS.INVALID_RESOURCE_CHARACTERS; for (int i = 0; i < chars.length; i++) if (segment.indexOf(chars[i]) != -1) { message = Policy.bind("resources.invalidCharInName", String.valueOf(chars[i]), segment); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* test invalid OS names */ if (!OS.isNameValid(segment)) { message = Policy.bind("resources.invalidName", segment); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } return ResourceStatus.OK_STATUS; } /** * @see IWorkspace#validateNatureSet(String[]) */ public IStatus validateNatureSet(String[] natureIds) { return natureManager.validateNatureSet(natureIds); } /** * @see IWorkspace#validatePath */ public IStatus validatePath(String path, int type) { String message; /* path must not be null */ if (path == null) { message = Policy.bind("resources.pathNull"); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* path must not have a device separator */ if (path.indexOf(IPath.DEVICE_SEPARATOR) != -1) { message = Policy.bind("resources.invalidCharInPath", String.valueOf(IPath.DEVICE_SEPARATOR), path); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* path must not be the root path */ IPath testPath = new Path(path); if (testPath.isRoot()) { message = Policy.bind("resources.invalidRoot"); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* path must be absolute */ if (!testPath.isAbsolute()) { message = Policy.bind("resources.mustBeAbsolute", path); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /* validate segments */ int numberOfSegments = testPath.segmentCount(); if ((type & IResource.PROJECT) != 0) { if (numberOfSegments == ICoreConstants.PROJECT_SEGMENT_LENGTH) { return validateName(testPath.segment(0), IResource.PROJECT); } else if (type == IResource.PROJECT) { message = Policy.bind("resources.projectPath",path); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } } if ((type & (IResource.FILE | IResource.FOLDER)) != 0) if (numberOfSegments >= ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH) { IStatus status = validateName(testPath.segment(0), IResource.PROJECT); if (!status.isOK()) return status; int fileFolderType = type &= ~IResource.PROJECT; int segmentCount = testPath.segmentCount(); // ignore first segment (the project) for (int i = 1; i < segmentCount; i++) { status = validateName(testPath.segment(i), fileFolderType); if (!status.isOK()) return status; } return ResourceStatus.OK_STATUS; } else { message = Policy.bind("resources.resourcePath",path); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } message = Policy.bind("resources.invalidPath", path); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } /** * @see IWorkspace#validateProjectLocation */ public IStatus validateProjectLocation(IProject context, IPath unresolvedLocation) { String message; // the default default is ok for all projects if (unresolvedLocation == null) { return ResourceStatus.OK_STATUS; } //check the standard path name restrictions IPath location = getPathVariableManager().resolvePath(unresolvedLocation); int segmentCount = location.segmentCount(); for (int i = 0; i < segmentCount; i++) { IStatus result = validateName(location.segment(i), IResource.PROJECT); if (!result.isOK()) return result; } //check that the location is absolute if (!location.isAbsolute()) { if (location.segmentCount() > 0) message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$ else message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message); } //if the location doesn't have a device, see if the OS will assign one if (location.getDevice() == null) location = new Path(location.toFile().getAbsolutePath()); // test if the given location overlaps the default default location IPath defaultDefaultLocation = Platform.getLocation(); if (isOverlapping(location, defaultDefaultLocation)) { message = Policy.bind("resources.overlapLocal", location.toString(), defaultDefaultLocation.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } // Iterate over each known project and ensure that the location does not // conflict with any of their already defined locations. IProject[] projects = getRoot().getProjects(); for (int j = 0; j < projects.length; j++) { IProject project = (IProject) projects[j]; // since we are iterating over the project in the workspace, we // know that they have been created before and must have a description IProjectDescription desc = ((Project) project).internalGetDescription(); IPath definedLocalLocation = desc.getLocation(); // if the project uses the default location then continue if (definedLocalLocation == null) continue; //tolerate locations being the same if this is the project being tested if (project.equals(context) && definedLocalLocation.equals(location)) continue; if (isOverlapping(location, definedLocalLocation)) { message = Policy.bind("resources.overlapLocal", location.toString(), definedLocalLocation.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } } return ResourceStatus.OK_STATUS; } /** * Internal method. To be called only from the following methods: * <ul> * <li><code>IFile#appendContents</code></li> * <li><code>IFile#setContents(InputStream, boolean, boolean, IProgressMonitor)</code></li> * <li><code>IFile#setContents(IFileState, boolean, boolean, IProgressMonitor)</code></li> * </ul> * * @see IFileModificationValidator#validateSave */ protected void validateSave(final IFile file) throws CoreException { // if validation is turned off then just return if (!shouldValidate) return; // first time through the validator hasn't been initialized so try and create it if (validator == null) initializeValidator(); // we were unable to initialize the validator. Validation has been turned off and // a warning has already been logged so just return. if (validator == null) return; // otherwise call the API and throw an exception if appropriate final IStatus[] status = new IStatus[1]; ISafeRunnable body = new ISafeRunnable() { public void run() throws Exception { status[0] = validator.validateSave(file); } public void handleException(Throwable exception) { status[0] = new ResourceStatus(IResourceStatus.ERROR, null, Policy.bind("resources.errorValidator"), exception); //$NON-NLS-1$ } }; Platform.run(body); if (!status[0].isOK()) throw new ResourceException(status[0]); } }
false
true
public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) { //check that the resource has a project as its parent String message; IContainer parent = resource.getParent(); if (parent == null || parent.getType() != IResource.PROJECT) { message = Policy.bind("links.parentNotProject", resource.getFullPath().toString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } if (!parent.isAccessible()) { message = Policy.bind("links.parentNotAccessible", resource.getFullPath().toString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } IPath location = getPathVariableManager().resolvePath(unresolvedLocation); //check nature veto String[] natureIds = ((Project)parent).internalGetDescription().getNatureIds(); IStatus result = getNatureManager().validateLinkCreation(natureIds); if (!result.isOK()) return result; //check team provider veto if (resource.getType() == IResource.FILE) result = getTeamHook().validateCreateLink((IFile)resource, IResource.NONE, location); else result = getTeamHook().validateCreateLink((IFolder)resource, IResource.NONE, location); if (!result.isOK()) return result; //check the standard path name restrictions int segmentCount = location.segmentCount(); for (int i = 0; i < segmentCount; i++) { result = validateName(location.segment(i), resource.getType()); if (!result.isOK()) return result; } //if the location doesn't have a device, see if the OS will assign one if (location.getDevice() == null) location = new Path(location.toFile().getAbsolutePath()); // test if the given location overlaps the platform metadata location IPath testLocation = getMetaArea().getLocation(); if (isOverlapping(location, testLocation)) { message = Policy.bind("links.invalidLocation", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } //test if the given path overlaps the location of the given project testLocation = resource.getProject().getLocation(); if (isOverlapping(location, testLocation)) { message = Policy.bind("links.locationOverlapsProject", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } //check that the location is absolute //Note: this check must be done last because we tolerate this condition in createLink if (!location.isAbsolute()) { if (location.segmentCount() > 0) message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$ else message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message); } // Iterate over each known project and ensure that the location does not // conflict with any project locations or linked resource locations IProject[] projects = getRoot().getProjects(); for (int i = 0; i < projects.length; i++) { IProject project = (IProject) projects[i]; // since we are iterating over the project in the workspace, we // know that they have been created before and must have a description IProjectDescription desc = ((Project) project).internalGetDescription(); testLocation = desc.getLocation(); // if the project uses the default location then continue if (testLocation == null) continue; if (isOverlapping(location, testLocation)) { message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message); } //iterate over linked resources and check for overlap if (!project.isOpen()) continue; IResource[] children = null; try { children = project.members(); } catch (CoreException e) { //ignore projects that cannot be accessed } if (children == null) continue; for (int j = 0; j < children.length; j++) { if (children[j].isLinked()) { testLocation = children[j].getLocation(); if (isOverlapping(location, testLocation)) { message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message); } } } } return ResourceStatus.OK_STATUS; }
public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) { //check that the resource has a project as its parent String message; IContainer parent = resource.getParent(); if (parent == null || parent.getType() != IResource.PROJECT) { message = Policy.bind("links.parentNotProject", resource.getFullPath().toString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } if (!parent.isAccessible()) { message = Policy.bind("links.parentNotAccessible", resource.getFullPath().toString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } IPath location = getPathVariableManager().resolvePath(unresolvedLocation); //check nature veto String[] natureIds = ((Project)parent).internalGetDescription().getNatureIds(); IStatus result = getNatureManager().validateLinkCreation(natureIds); if (!result.isOK()) return result; //check team provider veto if (resource.getType() == IResource.FILE) result = getTeamHook().validateCreateLink((IFile)resource, IResource.NONE, location); else result = getTeamHook().validateCreateLink((IFolder)resource, IResource.NONE, location); if (!result.isOK()) return result; //check the standard path name restrictions int segmentCount = location.segmentCount(); for (int i = 0; i < segmentCount; i++) { result = validateName(location.segment(i), resource.getType()); if (!result.isOK()) return result; } //if the location doesn't have a device, see if the OS will assign one if (location.getDevice() == null) location = new Path(location.toFile().getAbsolutePath()); // test if the given location overlaps the platform metadata location IPath testLocation = getMetaArea().getLocation(); if (isOverlapping(location, testLocation)) { message = Policy.bind("links.invalidLocation", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } //test if the given path overlaps the location of the given project testLocation = resource.getProject().getLocation(); if (isOverlapping(location, testLocation)) { message = Policy.bind("links.locationOverlapsProject", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } //check that the location is absolute //Note: this check must be done last because we tolerate this condition in createLink if (!location.isAbsolute()) { if (location.segmentCount() > 0) message = Policy.bind("pathvar.undefined", location.toOSString(), location.segment(0));//$NON-NLS-1$ else message = Policy.bind("links.relativePath", location.toOSString());//$NON-NLS-1$ return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message); } // Iterate over each known project and ensure that the location does not // conflict with any project locations or linked resource locations IProject[] projects = getRoot().getProjects(); for (int i = 0; i < projects.length; i++) { IProject project = (IProject) projects[i]; // since we are iterating over the project in the workspace, we // know that they have been created before and must have a description IProjectDescription desc = ((Project) project).internalGetDescription(); testLocation = desc.getLocation(); if (testLocation != null && isOverlapping(location, testLocation)) { message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message); } //iterate over linked resources and check for overlap if (!project.isOpen()) continue; IResource[] children = null; try { children = project.members(); } catch (CoreException e) { //ignore projects that cannot be accessed } if (children == null) continue; for (int j = 0; j < children.length; j++) { if (children[j].isLinked()) { testLocation = children[j].getLocation(); if (testLocation != null && isOverlapping(location, testLocation)) { message = Policy.bind("links.overlappingResource", location.toString()); //$NON-NLS-1$ return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, null, message); } } } } return ResourceStatus.OK_STATUS; }
diff --git a/errai-bus/src/main/java/org/jboss/errai/bus/server/io/JSONEncoder.java b/errai-bus/src/main/java/org/jboss/errai/bus/server/io/JSONEncoder.java index 753ddf235..f902558ed 100644 --- a/errai-bus/src/main/java/org/jboss/errai/bus/server/io/JSONEncoder.java +++ b/errai-bus/src/main/java/org/jboss/errai/bus/server/io/JSONEncoder.java @@ -1,284 +1,288 @@ /* * Copyright 2010 JBoss, a divison Red Hat, 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.jboss.errai.bus.server.io; import org.jboss.errai.common.client.protocols.SerializationParts; import org.jboss.errai.common.client.types.DecodingContext; import org.jboss.errai.common.client.types.EncodingContext; import org.jboss.errai.common.client.types.TypeHandler; import org.mvel2.MVEL; import org.mvel2.util.StringAppender; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.sql.Timestamp; import java.util.*; /** * Encodes an object into a JSON string */ public class JSONEncoder { protected static Set<Class> serializableTypes; public static void setSerializableTypes(Set<Class> serializableTypes) { JSONEncoder.serializableTypes = serializableTypes; } public static String encode(Object v) { return _encode(v, new EncodingContext()); } private static String _encode(Object v, EncodingContext ctx) { if (v == null) { return "null"; } else if (v instanceof String) { return "\"" + ((String) v).replaceAll("\"", "\\\\\"") + "\""; } if (v instanceof Number || v instanceof Boolean) { return String.valueOf(v); } else if (v instanceof Collection) { return encodeCollection((Collection) v, ctx); } else if (v instanceof Map) { //noinspection unchecked return encodeMap((Map) v, ctx); } else if (v.getClass().isArray()) { return encodeArray(v, ctx); // CDI Integration: Loading entities after the service was initialized // This may cause the client to throw an exception if the entity is not known // TODO: Improve exception handling for these cases }/* else if (serializableTypes.contains(v.getClass()) || tHandlers.containsKey(v.getClass())) { return encodeObject(v); } else { throw new RuntimeException("cannot serialize type: " + v.getClass().getName()); } */ else if (v instanceof Enum) { return encodeEnum((Enum) v, ctx); } else { return encodeObject(v, ctx); } } private static String encodeObject(Object o, EncodingContext ctx) { if (o == null) return "null"; Class cls = o.getClass(); if (java.util.Date.class.isAssignableFrom(cls)) { - return "{\"__EncodedType\":\"java.util.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + ((java.util.Date) o).getTime() + "}"; + return "{\"__EncodedType\":\"java.util.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + + ((java.util.Date) o).getTime() + "}"; } if (java.sql.Date.class.isAssignableFrom(cls)) { - return "{\"__EncodedType\":\"java.sql.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + ((java.sql.Date) o).getTime() + "}"; + return "{\"__EncodedType\":\"java.sql.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + + ((java.sql.Date) o).getTime() + "}"; } if (tHandlers.containsKey(cls)) { return _encode(convert(o), ctx); } if (ctx.isEncoded(o)) { /** * If this object is referencing a duplicate object in the graph, we only provide an ID reference. */ - return write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + cls.getCanonicalName() + "\",\"" + SerializationParts.OBJECT_ID + "\":\"$" + ctx.markRef(o) + "\"}"); + return write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + cls.getCanonicalName() + "\",\"" + + SerializationParts.OBJECT_ID + "\":\"$" + ctx.markRef(o) + "\"}"); } ctx.markEncoded(o); - StringAppender build = new StringAppender(write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + cls.getName() + "\",\"" + SerializationParts.OBJECT_ID + "\":\"" + String.valueOf(o.hashCode()) + "\"")); + StringAppender build = new StringAppender(write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + + cls.getName() + "\",\"" + SerializationParts.OBJECT_ID + "\":\"" + String.valueOf(o.hashCode()) + "\"")); // Preliminary fix for https://jira.jboss.org/browse/ERRAI-103 // TODO: Review my Mike final Field[] fields = EncodingUtil.getAllEncodingFields(cls); final Serializable[] s = EncodingCache.get(fields, new EncodingCache.ValueProvider<Serializable[]>() { public Serializable[] get() { Serializable[] s = new Serializable[fields.length]; int i = 0; for (Field f : fields) { if ((f.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) != 0 || f.isSynthetic()) { continue; } s[i++] = MVEL.compileExpression(f.getName()); } return s; } }); int i = 0; boolean first = true; for (Field field : fields) { if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) != 0 || field.isSynthetic()) { continue; } else if (first) { build.append(','); first = true; } try { Object v = MVEL.executeExpression(s[i++], o); build.append(write(ctx, '\"')).append(field.getName()).append(write(ctx, '\"')).append(':').append(_encode(v, ctx)); } catch (Throwable t) { System.out.println("failed at encoding: " + field.getName()); t.printStackTrace(); } } return build.append('}').toString(); } private static String encodeMap(Map<Object, Object> map, EncodingContext ctx) { StringAppender mapBuild = new StringAppender("{"); boolean first = true; for (Map.Entry<Object, Object> entry : map.entrySet()) { String val = _encode(entry.getValue(), ctx); if (!first) { mapBuild.append(','); } if (!(entry.getKey() instanceof String)) { mapBuild.append(write(ctx, '\"')); if (!ctx.isEscapeMode()) { mapBuild.append(SerializationParts.EMBEDDED_JSON); } ctx.setEscapeMode(); mapBuild.append(_encode(entry.getKey(), ctx)); ctx.unsetEscapeMode(); mapBuild.append(write(ctx, '\"')); mapBuild.append(":") .append(val); } else { mapBuild.append(_encode(entry.getKey(), ctx)) .append(':').append(val); } first = false; } return mapBuild.append('}').toString(); } private static String encodeCollection(Collection col, EncodingContext ctx) { StringAppender buildCol = new StringAppender("["); Iterator iter = col.iterator(); while (iter.hasNext()) { buildCol.append(_encode(iter.next(), ctx)); if (iter.hasNext()) buildCol.append(','); } return buildCol.append(']').toString(); } private static String encodeArray(Object array, EncodingContext ctx) { StringAppender buildCol = new StringAppender("["); int len = Array.getLength(array); for (int i = 0; i < len; i++) { buildCol.append(_encode(Array.get(array, i), ctx)); if ((i + 1) < len) buildCol.append(','); } return buildCol.append(']').toString(); } private static String encodeEnum(Enum enumer, EncodingContext ctx) { String s = "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + enumer.getClass().getName() + "\", \"EnumStringValue\":\"" + enumer.name() + "\"}"; if (ctx.isEscapeMode()) { return s.replaceAll("\"", "\\\\\""); } else { return s; } } private static final Map<Class, TypeHandler> tHandlers = new HashMap<Class, TypeHandler>(); static { // tHandlers.put(java.sql.Date.class, new TypeHandler<java.sql.Date, String>() { // public String getConverted(java.sql.Date in, DecodingContext ctx) { // return "{__EncodedType:\"java.sql.Date\", __ObjectID:\"" + in.hashCode() + "\", Value:\"" + in.getTime() + "\"}"; // // } // }); // tHandlers.put(java.util.Date.class, new TypeHandler<java.util.Date, String>() { // public String getConverted(java.util.Date in, DecodingContext ctx) { // return "{__EncodedType:\"java.util.Date\", __ObjectID:\"" + in.hashCode() + "\", Value:\"" + in.getTime() + "\"}"; // } // }); tHandlers.put(Timestamp.class, new TypeHandler<Timestamp, Long>() { public Long getConverted(Timestamp in, DecodingContext ctx) { return in.getTime(); } }); tHandlers.put(Character.class, new TypeHandler<Character, String>() { public String getConverted(Character in, DecodingContext ctx) { return String.valueOf(in.charValue()); } }); } private static String write(EncodingContext ctx, String s) { if (ctx.isEscapeMode()) { return s.replaceAll("\"", "\\\\\""); } else { return s; } } private static String write(EncodingContext ctx, char s) { if (ctx.isEscapeMode() && s == '\"') { return "\\\\\""; } else { return String.valueOf(s); } } public static void addEncodingHandler(Class from, TypeHandler handler) { tHandlers.put(from, handler); } private static final DecodingContext STATIC_DEC_CONTEXT = new DecodingContext(); private static Object convert(Object in) { if (in == null || !tHandlers.containsKey(in.getClass())) return in; else { //noinspection unchecked return tHandlers.get(in.getClass()).getConverted(in, STATIC_DEC_CONTEXT); } } }
false
true
private static String encodeObject(Object o, EncodingContext ctx) { if (o == null) return "null"; Class cls = o.getClass(); if (java.util.Date.class.isAssignableFrom(cls)) { return "{\"__EncodedType\":\"java.util.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + ((java.util.Date) o).getTime() + "}"; } if (java.sql.Date.class.isAssignableFrom(cls)) { return "{\"__EncodedType\":\"java.sql.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + ((java.sql.Date) o).getTime() + "}"; } if (tHandlers.containsKey(cls)) { return _encode(convert(o), ctx); } if (ctx.isEncoded(o)) { /** * If this object is referencing a duplicate object in the graph, we only provide an ID reference. */ return write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + cls.getCanonicalName() + "\",\"" + SerializationParts.OBJECT_ID + "\":\"$" + ctx.markRef(o) + "\"}"); } ctx.markEncoded(o); StringAppender build = new StringAppender(write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + cls.getName() + "\",\"" + SerializationParts.OBJECT_ID + "\":\"" + String.valueOf(o.hashCode()) + "\"")); // Preliminary fix for https://jira.jboss.org/browse/ERRAI-103 // TODO: Review my Mike final Field[] fields = EncodingUtil.getAllEncodingFields(cls); final Serializable[] s = EncodingCache.get(fields, new EncodingCache.ValueProvider<Serializable[]>() { public Serializable[] get() { Serializable[] s = new Serializable[fields.length]; int i = 0; for (Field f : fields) { if ((f.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) != 0 || f.isSynthetic()) { continue; } s[i++] = MVEL.compileExpression(f.getName()); } return s; } }); int i = 0; boolean first = true; for (Field field : fields) { if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) != 0 || field.isSynthetic()) { continue; } else if (first) { build.append(','); first = true; } try { Object v = MVEL.executeExpression(s[i++], o); build.append(write(ctx, '\"')).append(field.getName()).append(write(ctx, '\"')).append(':').append(_encode(v, ctx)); } catch (Throwable t) { System.out.println("failed at encoding: " + field.getName()); t.printStackTrace(); } } return build.append('}').toString(); }
private static String encodeObject(Object o, EncodingContext ctx) { if (o == null) return "null"; Class cls = o.getClass(); if (java.util.Date.class.isAssignableFrom(cls)) { return "{\"__EncodedType\":\"java.util.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + ((java.util.Date) o).getTime() + "}"; } if (java.sql.Date.class.isAssignableFrom(cls)) { return "{\"__EncodedType\":\"java.sql.Date\", \"__ObjectID\":\"" + o.hashCode() + "\", \"Value\":" + ((java.sql.Date) o).getTime() + "}"; } if (tHandlers.containsKey(cls)) { return _encode(convert(o), ctx); } if (ctx.isEncoded(o)) { /** * If this object is referencing a duplicate object in the graph, we only provide an ID reference. */ return write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + cls.getCanonicalName() + "\",\"" + SerializationParts.OBJECT_ID + "\":\"$" + ctx.markRef(o) + "\"}"); } ctx.markEncoded(o); StringAppender build = new StringAppender(write(ctx, "{\"" + SerializationParts.ENCODED_TYPE + "\":\"" + cls.getName() + "\",\"" + SerializationParts.OBJECT_ID + "\":\"" + String.valueOf(o.hashCode()) + "\"")); // Preliminary fix for https://jira.jboss.org/browse/ERRAI-103 // TODO: Review my Mike final Field[] fields = EncodingUtil.getAllEncodingFields(cls); final Serializable[] s = EncodingCache.get(fields, new EncodingCache.ValueProvider<Serializable[]>() { public Serializable[] get() { Serializable[] s = new Serializable[fields.length]; int i = 0; for (Field f : fields) { if ((f.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) != 0 || f.isSynthetic()) { continue; } s[i++] = MVEL.compileExpression(f.getName()); } return s; } }); int i = 0; boolean first = true; for (Field field : fields) { if ((field.getModifiers() & (Modifier.TRANSIENT | Modifier.STATIC)) != 0 || field.isSynthetic()) { continue; } else if (first) { build.append(','); first = true; } try { Object v = MVEL.executeExpression(s[i++], o); build.append(write(ctx, '\"')).append(field.getName()).append(write(ctx, '\"')).append(':').append(_encode(v, ctx)); } catch (Throwable t) { System.out.println("failed at encoding: " + field.getName()); t.printStackTrace(); } } return build.append('}').toString(); }
diff --git a/src/main/java/org/basex/build/xml/SAXWrapper.java b/src/main/java/org/basex/build/xml/SAXWrapper.java index 9c448a55e..e5f23a4d8 100644 --- a/src/main/java/org/basex/build/xml/SAXWrapper.java +++ b/src/main/java/org/basex/build/xml/SAXWrapper.java @@ -1,169 +1,169 @@ package org.basex.build.xml; import static org.basex.core.Text.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.basex.build.FileParser; import org.basex.core.ProgressException; import org.basex.core.Prop; import org.basex.io.IO; import org.basex.io.IOFile; import org.basex.util.Util; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * This class parses an XML document with Java's default SAX parser. Note that * large file cannot be parsed with the default parser due to entity handling * (e.g. the DBLP data). * * @author BaseX Team 2005-11, BSD License * @author Christian Gruen */ public final class SAXWrapper extends FileParser { /** File counter. */ long counter; /** Current line. */ int line = 1; /** SAX handler reference. */ private SAXHandler sax; /** Optional XML reader. */ private final SAXSource src; /** File length. */ private long length; /** Properties. */ private final Prop prop; /** * Constructor. * @param s sax source * @param pr Properties */ public SAXWrapper(final SAXSource s, final Prop pr) { this(s, IO.get(s.getSystemId()).name(), "", pr); } /** * Constructor. * @param s sax source * @param n name * @param ta target to insert into * @param pr Properties */ public SAXWrapper(final SAXSource s, final String n, final String ta, final Prop pr) { super(io(s, n), ta); src = s; prop = pr; } /** * Returns IO reference. * @param s sax source * @param n name * @return io */ private static IO io(final SAXSource s, final String n) { final IO io = IO.get(s.getSystemId()); io.name(n); return io; } @Override public void parse() throws IOException { final InputSource is = wrap(src.getInputSource()); final String input = src.getSystemId() == null ? "..." : src.getSystemId(); try { XMLReader r = src.getXMLReader(); if(r == null) { final SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(true); f.setValidating(false); r = f.newSAXParser().getXMLReader(); } sax = new SAXHandler(builder); final String cat = prop.get(Prop.CATFILE); if(!cat.isEmpty()) CatalogResolverWrapper.set(r, cat); r.setDTDHandler(sax); r.setContentHandler(sax); r.setProperty("http://xml.org/sax/properties/lexical-handler", sax); r.setErrorHandler(sax); if(is != null) r.parse(is); else r.parse(src.getSystemId()); } catch(final SAXParseException ex) { final String msg = Util.info(SCANPOS, input, ex.getLineNumber(), ex.getColumnNumber()) + ": " + ex.getMessage(); final IOException ioe = new IOException(msg); ioe.setStackTrace(ex.getStackTrace()); throw ioe; } catch(final ProgressException ex) { throw ex; } catch(final Exception ex) { // occurs, e.g. if document encoding is invalid: // prefix message with source id String msg = ex.getMessage(); if(input != null) msg = "\"" + input + "\": " + msg; // wrap and return original message final IOException ioe = new IOException(msg); ioe.setStackTrace(ex.getStackTrace()); throw ioe; } finally { try { final InputStream in = is.getByteStream(); if(in != null) in.close(); final Reader r = is.getCharacterStream(); - if(r != null) in.close(); + if(r != null) r.close(); } catch(final IOException ex) { Util.debug(ex); } } } /** * Wraps the input source with a stream which counts the number of read bytes. * @param is input source * @return resulting stream * @throws IOException I/O exception */ private InputSource wrap(final InputSource is) throws IOException { if(!(file instanceof IOFile) || is == null || is.getByteStream() != null || is.getSystemId() == null || is.getSystemId().isEmpty()) return is; final InputSource in = new InputSource(new FileInputStream(file.path()) { @Override public int read(final byte[] b, final int off, final int len) throws IOException { final int i = super.read(b, off, len); for(int o = off; o < len; ++o) if(b[off + o] == '\n') ++line; counter += i; return i; } }); src.setInputSource(in); src.setSystemId(is.getSystemId()); length = file.length(); return in; } @Override public String det() { return length == 0 ? super.det() : Util.info(SCANPOS, file.name(), line); } @Override public double prog() { return length == 0 ? sax == null ? 0 : sax.nodes / 3000000d % 1 : (double) counter / length; } }
true
true
public void parse() throws IOException { final InputSource is = wrap(src.getInputSource()); final String input = src.getSystemId() == null ? "..." : src.getSystemId(); try { XMLReader r = src.getXMLReader(); if(r == null) { final SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(true); f.setValidating(false); r = f.newSAXParser().getXMLReader(); } sax = new SAXHandler(builder); final String cat = prop.get(Prop.CATFILE); if(!cat.isEmpty()) CatalogResolverWrapper.set(r, cat); r.setDTDHandler(sax); r.setContentHandler(sax); r.setProperty("http://xml.org/sax/properties/lexical-handler", sax); r.setErrorHandler(sax); if(is != null) r.parse(is); else r.parse(src.getSystemId()); } catch(final SAXParseException ex) { final String msg = Util.info(SCANPOS, input, ex.getLineNumber(), ex.getColumnNumber()) + ": " + ex.getMessage(); final IOException ioe = new IOException(msg); ioe.setStackTrace(ex.getStackTrace()); throw ioe; } catch(final ProgressException ex) { throw ex; } catch(final Exception ex) { // occurs, e.g. if document encoding is invalid: // prefix message with source id String msg = ex.getMessage(); if(input != null) msg = "\"" + input + "\": " + msg; // wrap and return original message final IOException ioe = new IOException(msg); ioe.setStackTrace(ex.getStackTrace()); throw ioe; } finally { try { final InputStream in = is.getByteStream(); if(in != null) in.close(); final Reader r = is.getCharacterStream(); if(r != null) in.close(); } catch(final IOException ex) { Util.debug(ex); } } }
public void parse() throws IOException { final InputSource is = wrap(src.getInputSource()); final String input = src.getSystemId() == null ? "..." : src.getSystemId(); try { XMLReader r = src.getXMLReader(); if(r == null) { final SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(true); f.setValidating(false); r = f.newSAXParser().getXMLReader(); } sax = new SAXHandler(builder); final String cat = prop.get(Prop.CATFILE); if(!cat.isEmpty()) CatalogResolverWrapper.set(r, cat); r.setDTDHandler(sax); r.setContentHandler(sax); r.setProperty("http://xml.org/sax/properties/lexical-handler", sax); r.setErrorHandler(sax); if(is != null) r.parse(is); else r.parse(src.getSystemId()); } catch(final SAXParseException ex) { final String msg = Util.info(SCANPOS, input, ex.getLineNumber(), ex.getColumnNumber()) + ": " + ex.getMessage(); final IOException ioe = new IOException(msg); ioe.setStackTrace(ex.getStackTrace()); throw ioe; } catch(final ProgressException ex) { throw ex; } catch(final Exception ex) { // occurs, e.g. if document encoding is invalid: // prefix message with source id String msg = ex.getMessage(); if(input != null) msg = "\"" + input + "\": " + msg; // wrap and return original message final IOException ioe = new IOException(msg); ioe.setStackTrace(ex.getStackTrace()); throw ioe; } finally { try { final InputStream in = is.getByteStream(); if(in != null) in.close(); final Reader r = is.getCharacterStream(); if(r != null) r.close(); } catch(final IOException ex) { Util.debug(ex); } } }
diff --git a/src/main/java/jline/ConsoleReader.java b/src/main/java/jline/ConsoleReader.java index 687f03e..27ace1c 100644 --- a/src/main/java/jline/ConsoleReader.java +++ b/src/main/java/jline/ConsoleReader.java @@ -1,1390 +1,1390 @@ /* * Copyright (c) 2002-2006, Marc Prud'hommeaux. All rights reserved. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. */ package jline; import java.awt.*; import java.awt.datatransfer.*; import java.io.*; import java.util.*; import java.util.List; /** * A reader for console applications. It supports custom tab-completion, * saveable command history, and command line editing. On some * platforms, platform-specific commands will need to be * issued before the reader will function properly. See * {@link Terminal#initializeTerminal} for convenience methods for * issuing platform-specific setup commands. * * @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a> */ public class ConsoleReader implements ConsoleOperations { String prompt; private boolean useHistory = true; public static final String CR = System.getProperty("line.separator"); /** * Map that contains the operation name to keymay operation mapping. */ public static SortedMap KEYMAP_NAMES; static { Map names = new TreeMap(); names.put("MOVE_TO_BEG", new Short(MOVE_TO_BEG)); names.put("MOVE_TO_END", new Short(MOVE_TO_END)); names.put("PREV_CHAR", new Short(PREV_CHAR)); names.put("NEWLINE", new Short(NEWLINE)); names.put("KILL_LINE", new Short(KILL_LINE)); names.put("PASTE", new Short(PASTE)); names.put("CLEAR_SCREEN", new Short(CLEAR_SCREEN)); names.put("NEXT_HISTORY", new Short(NEXT_HISTORY)); names.put("PREV_HISTORY", new Short(PREV_HISTORY)); names.put("REDISPLAY", new Short(REDISPLAY)); names.put("KILL_LINE_PREV", new Short(KILL_LINE_PREV)); names.put("DELETE_PREV_WORD", new Short(DELETE_PREV_WORD)); names.put("NEXT_CHAR", new Short(NEXT_CHAR)); names.put("REPEAT_PREV_CHAR", new Short(REPEAT_PREV_CHAR)); names.put("SEARCH_PREV", new Short(SEARCH_PREV)); names.put("REPEAT_NEXT_CHAR", new Short(REPEAT_NEXT_CHAR)); names.put("SEARCH_NEXT", new Short(SEARCH_NEXT)); names.put("PREV_SPACE_WORD", new Short(PREV_SPACE_WORD)); names.put("TO_END_WORD", new Short(TO_END_WORD)); names.put("REPEAT_SEARCH_PREV", new Short(REPEAT_SEARCH_PREV)); names.put("PASTE_PREV", new Short(PASTE_PREV)); names.put("REPLACE_MODE", new Short(REPLACE_MODE)); names.put("SUBSTITUTE_LINE", new Short(SUBSTITUTE_LINE)); names.put("TO_PREV_CHAR", new Short(TO_PREV_CHAR)); names.put("NEXT_SPACE_WORD", new Short(NEXT_SPACE_WORD)); names.put("DELETE_PREV_CHAR", new Short(DELETE_PREV_CHAR)); names.put("ADD", new Short(ADD)); names.put("PREV_WORD", new Short(PREV_WORD)); names.put("CHANGE_META", new Short(CHANGE_META)); names.put("DELETE_META", new Short(DELETE_META)); names.put("END_WORD", new Short(END_WORD)); names.put("NEXT_CHAR", new Short(NEXT_CHAR)); names.put("INSERT", new Short(INSERT)); names.put("REPEAT_SEARCH_NEXT", new Short(REPEAT_SEARCH_NEXT)); names.put("PASTE_NEXT", new Short(PASTE_NEXT)); names.put("REPLACE_CHAR", new Short(REPLACE_CHAR)); names.put("SUBSTITUTE_CHAR", new Short(SUBSTITUTE_CHAR)); names.put("TO_NEXT_CHAR", new Short(TO_NEXT_CHAR)); names.put("UNDO", new Short(UNDO)); names.put("NEXT_WORD", new Short(NEXT_WORD)); names.put("DELETE_NEXT_CHAR", new Short(DELETE_NEXT_CHAR)); names.put("CHANGE_CASE", new Short(CHANGE_CASE)); names.put("COMPLETE", new Short(COMPLETE)); names.put("EXIT", new Short(EXIT)); KEYMAP_NAMES = new TreeMap(Collections.unmodifiableMap(names)); } /** * The map for logical operations. */ private final short[] keybindings; /** * If true, issue an audible keyboard bell when appropriate. */ private boolean bellEnabled = true; /** * The current character mask. */ private Character mask = null; /** * The null mask. */ private static final Character NULL_MASK = new Character((char) 0); /** * The number of tab-completion candidates above which a warning * will be prompted before showing all the candidates. */ private int autoprintThreshhold = Integer.getInteger ("jline.completion.threshold", 100).intValue(); // same default as bash /** * The Terminal to use. */ private final Terminal terminal; private CompletionHandler completionHandler = new CandidateListCompletionHandler(); InputStream in; final Writer out; final CursorBuffer buf = new CursorBuffer(); static PrintWriter debugger; History history = new History(); final List completors = new LinkedList(); private Character echoCharacter = null; /** * Create a new reader using {@link FileDescriptor#in} for input * and {@link System#out} for output. {@link FileDescriptor#in} is * used because it has a better chance of being unbuffered. */ public ConsoleReader() throws IOException { this(new FileInputStream(FileDescriptor.in), new PrintWriter(System.out)); } /** * Create a new reader using the specified {@link InputStream} * for input and the specific writer for output, using the * default keybindings resource. */ public ConsoleReader(final InputStream in, final Writer out) throws IOException { this(in, out, null); } public ConsoleReader(final InputStream in, final Writer out, final InputStream bindings) throws IOException { this(in, out, bindings, Terminal.getTerminal()); } /** * Create a new reader. * * @param in the input * @param out the output * @param bindings the key bindings to use * @param term the terminal to use */ public ConsoleReader(InputStream in, Writer out, InputStream bindings, Terminal term) throws IOException { this.terminal = term; setInput(in); this.out = out; if (bindings == null) { String bindingFile = System.getProperty("jline.keybindings", new File(System.getProperty("user.home", ".jlinebindings.properties")).getAbsolutePath()); if (!(new File(bindingFile).isFile())) { bindings = ConsoleReader.class. getResourceAsStream("keybindings.properties"); } else { bindings = new FileInputStream(new File(bindingFile)); } } this.keybindings = new short[Byte.MAX_VALUE * 2]; Arrays.fill(this.keybindings, UNKNOWN); /** * Loads the key bindings. Bindings file is in the format: * * keycode: operation name */ if (bindings != null) { Properties p = new Properties(); p.load(bindings); bindings.close(); for (Iterator i = p.keySet().iterator(); i.hasNext();) { String val = (String) i.next(); try { Short code = new Short(val); String op = (String) p.getProperty(val); Short opval = (Short) KEYMAP_NAMES.get(op); if (opval != null) { keybindings[code.shortValue()] = opval.shortValue(); } } catch (NumberFormatException nfe) { consumeException(nfe); } } // hardwired arrow key bindings // keybindings[VK_UP] = PREV_HISTORY; // keybindings[VK_DOWN] = NEXT_HISTORY; // keybindings[VK_LEFT] = PREV_CHAR; // keybindings[VK_RIGHT] = NEXT_CHAR; } } public Terminal getTerminal() { return this.terminal; } /** * Set the stream for debugging. Development use only. */ public void setDebug(final PrintWriter debugger) { ConsoleReader.debugger = debugger; } /** * Set the stream to be used for console input. */ public void setInput(final InputStream in) { this.in = in; } /** * Returns the stream used for console input. */ public InputStream getInput() { return this.in; } /** * Read the next line and return the contents of the buffer. */ public String readLine() throws IOException { return readLine((String) null); } /** * Read the next line with the specified character mask. If null, then * characters will be echoed. If 0, then no characters will be echoed. */ public String readLine(final Character mask) throws IOException { return readLine(null, mask); } /** * @param bellEnabled if true, enable audible keyboard bells if * an alert is required. */ public void setBellEnabled(final boolean bellEnabled) { this.bellEnabled = bellEnabled; } /** * @return true is audible keyboard bell is enabled. */ public boolean getBellEnabled() { return this.bellEnabled; } /** * Query the terminal to find the current width; * * @see Terminal#getTerminalWidth * @return the width of the current terminal. */ public int getTermwidth() { return Terminal.setupTerminal().getTerminalWidth(); } /** * Query the terminal to find the current width; * * @see Terminal#getTerminalHeight * * @return the height of the current terminal. */ public int getTermheight() { return Terminal.setupTerminal().getTerminalHeight(); } /** * @param autoprintThreshhold the number of candidates to print * without issuing a warning. */ public void setAutoprintThreshhold(final int autoprintThreshhold) { this.autoprintThreshhold = autoprintThreshhold; } /** * @return the number of candidates to print without issing a warning. */ public int getAutoprintThreshhold() { return this.autoprintThreshhold; } int getKeyForAction(short logicalAction) { for (int i = 0; i < keybindings.length; i++) { if (keybindings[i] == logicalAction) { return i; } } return -1; } /** * Clear the echoed characters for the specified character code. */ int clearEcho(int c) throws IOException { // if the terminal is not echoing, then just return... if (!terminal.getEcho()) { return 0; } // otherwise, clear int num = countEchoCharacters((char) c); back(num); drawBuffer(num); return num; } int countEchoCharacters(char c) { // tabs as special: we need to determine the number of spaces // to cancel based on what out current cursor position is if (c == 9) { int tabstop = 8; // will this ever be different? int position = getCursorPosition(); return tabstop - (position % tabstop); } return getPrintableCharacters(c).length(); } /** * Return the number of characters that will be printed when the * specified character is echoed to the screen. Adapted from * cat by Torbjorn Granlund, as repeated in stty by * David MacKenzie. */ StringBuffer getPrintableCharacters(char ch) { StringBuffer sbuff = new StringBuffer(); if (ch >= 32) { if (ch < 127) { sbuff.append(ch); } else if (ch == 127) { sbuff.append('^'); sbuff.append('?'); } else { sbuff.append('M'); sbuff.append('-'); if (ch >= (128 + 32)) { if (ch < (128 + 127)) { sbuff.append((char) (ch - 128)); } else { sbuff.append('^'); sbuff.append('?'); } } else { sbuff.append('^'); sbuff.append((char) (ch - 128 + 64)); } } } else { sbuff.append('^'); sbuff.append((char) (ch + 64)); } return sbuff; } int getCursorPosition() { // FIXME: does not handle anything but a line with a prompt // absolute position return ((prompt == null) ? 0 : prompt.length()) + buf.cursor; } public String readLine(final String prompt) throws IOException { return readLine(prompt, null); } /** * The default prompt that will be issued. */ public void setDefaultPrompt(String prompt) { this.prompt = prompt; } /** * The default prompt that will be issued. */ public String getDefaultPrompt() { return prompt; } /** * Read a line from the <i>in</i> {@link InputStream}, and * return the line (without any trailing newlines). * * @param prompt the prompt to issue to the console, may be null. * @return a line that is read from the terminal, or null if there * was null input (e.g., <i>CTRL-D</i> was pressed). */ public String readLine(final String prompt, final Character mask) throws IOException { this.mask = mask; if (prompt != null) this.prompt = prompt; try { - terminal.beforeReadLine(this, prompt, mask); + terminal.beforeReadLine(this, this.prompt, mask); - if ((prompt != null) && (prompt.length() > 0)) { - out.write(prompt); + if ((this.prompt != null) && (this.prompt.length() > 0)) { + out.write(this.prompt); out.flush(); } // if the terminal is unsupported, just use plain-java reading if (!terminal.isSupported()) { return readLine(in); } while (true) { int[] next = readBinding(); if (next == null) { return null; } int c = next[0]; int code = next[1]; if (c == -1) { return null; } boolean success = true; switch (code) { case EXIT: // ctrl-d if (buf.buffer.length() == 0) { return null; } case COMPLETE: // tab success = complete(); break; case MOVE_TO_BEG: success = setCursorPosition(0); break; case KILL_LINE: // CTRL-K success = killLine(); break; case CLEAR_SCREEN: // CTRL-L success = clearScreen(); break; case KILL_LINE_PREV: // CTRL-U success = resetLine(); break; case NEWLINE: // enter printNewline(); // output newline return finishBuffer(); case DELETE_PREV_CHAR: // backspace success = backspace(); break; case MOVE_TO_END: success = moveToEnd(); break; case PREV_CHAR: success = moveCursor(-1) != 0; break; case NEXT_CHAR: success = moveCursor(1) != 0; break; case NEXT_HISTORY: success = moveHistory(true); break; case PREV_HISTORY: success = moveHistory(false); break; case REDISPLAY: break; case PASTE: success = paste(); break; case DELETE_PREV_WORD: success = deletePreviousWord(); break; case PREV_WORD: success = previousWord(); break; case NEXT_WORD: success = nextWord(); break; case UNKNOWN:default: putChar(c, true); } if (!(success)) { beep(); } flushConsole(); } } finally { - terminal.afterReadLine(this, prompt, mask); + terminal.afterReadLine(this, this.prompt, mask); } } private String readLine(InputStream in) throws IOException { StringBuffer buf = new StringBuffer(); while (true) { int i = in.read(); if ((i == -1) || (i == '\n') || (i == '\r')) { return buf.toString(); } buf.append((char) i); } // return new BufferedReader (new InputStreamReader (in)).readLine (); } /** * Reads the console input and returns an array of the form * [raw, key binding]. */ private int[] readBinding() throws IOException { int c = readVirtualKey(); if (c == -1) { return null; } // extract the appropriate key binding short code = keybindings[c]; if (debugger != null) { debug(" translated: " + (int) c + ": " + code); } return new int[] { c, code }; } /** * Move up or down the history tree. * * @param direction less than 0 to move up the tree, down otherwise */ private final boolean moveHistory(final boolean next) throws IOException { if (next && !history.next()) { return false; } else if (!next && !history.previous()) { return false; } setBuffer(history.current()); return true; } /** * Paste the contents of the clipboard into the console buffer * * @return true if clipboard contents pasted */ public boolean paste() throws IOException { Clipboard clipboard = Toolkit. getDefaultToolkit().getSystemClipboard(); if (clipboard == null) { return false; } Transferable transferable = clipboard.getContents(null); if (transferable == null) { return false; } try { Object content = transferable. getTransferData(DataFlavor.plainTextFlavor); /* * This fix was suggested in bug #1060649 at * http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056 * to get around the deprecated DataFlavor.plainTextFlavor, but * it raises a UnsupportedFlavorException on Mac OS X */ if (content == null) { try { content = new DataFlavor().getReaderForText(transferable); } catch (Exception e) { } } if (content == null) { return false; } String value; if (content instanceof Reader) { // TODO: we might want instead connect to the input stream // so we can interpret individual lines value = ""; String line = null; for (BufferedReader read = new BufferedReader((Reader) content); (line = read.readLine()) != null;) { if (value.length() > 0) { value += "\n"; } value += line; } } else { value = content.toString(); } if (value == null) { return true; } putString(value); return true; } catch (UnsupportedFlavorException ufe) { if (debugger != null) debug(ufe + ""); return false; } } /** * Kill the buffer ahead of the current cursor position. * * @return true if successful */ public boolean killLine() throws IOException { int cp = buf.cursor; int len = buf.buffer.length(); if (cp >= len) { return false; } int num = buf.buffer.length() - cp; clearAhead(num); for (int i = 0; i < num; i++) { buf.buffer.deleteCharAt(len - i - 1); } return true; } /** * Clear the screen by issuing the ANSI "clear screen" code. */ public boolean clearScreen() throws IOException { if (!terminal.isANSISupported()) { return false; } // send the ANSI code to clear the screen printString(((char) 27) + "[2J"); flushConsole(); // then send the ANSI code to go to position 1,1 printString(((char) 27) + "[1;1H"); flushConsole(); redrawLine(); return true; } /** * Use the completors to modify the buffer with the * appropriate completions. * * @return true if successful */ private final boolean complete() throws IOException { // debug ("tab for (" + buf + ")"); if (completors.size() == 0) { return false; } List candidates = new LinkedList(); String bufstr = buf.buffer.toString(); int cursor = buf.cursor; int position = -1; for (Iterator i = completors.iterator(); i.hasNext();) { Completor comp = (Completor) i.next(); if ((position = comp.complete(bufstr, cursor, candidates)) != -1) { break; } } // no candidates? Fail. if (candidates.size() == 0) { return false; } return completionHandler.complete(this, candidates, position); } public CursorBuffer getCursorBuffer() { return buf; } /** * Output the specified {@link Collection} in proper columns. * * @param stuff the stuff to print */ public void printColumns(final Collection stuff) throws IOException { if ((stuff == null) || (stuff.size() == 0)) { return; } int width = getTermwidth(); int maxwidth = 0; for (Iterator i = stuff.iterator(); i.hasNext(); maxwidth = Math.max(maxwidth, i.next().toString().length())) { ; } StringBuffer line = new StringBuffer(); for (Iterator i = stuff.iterator(); i.hasNext();) { String cur = (String) i.next(); if ((line.length() + maxwidth) > width) { printString(line.toString().trim()); printNewline(); line.setLength(0); } pad(cur, maxwidth + 3, line); } if (line.length() > 0) { printString(line.toString().trim()); printNewline(); line.setLength(0); } } /** * Append <i>toPad</i> to the specified <i>appendTo</i>, as * well as (<i>toPad.length () - len</i>) spaces. * * @param toPad the {@link String} to pad * @param len the target length * @param appendTo the {@link StringBuffer} to which to append the * padded {@link String}. */ private final void pad(final String toPad, final int len, final StringBuffer appendTo) { appendTo.append(toPad); for (int i = 0; i < (len - toPad.length()); i++, appendTo.append(' ')) { ; } } /** * Add the specified {@link Completor} to the list of handlers * for tab-completion. * * @param completor the {@link Completor} to add * @return true if it was successfully added */ public boolean addCompletor(final Completor completor) { return completors.add(completor); } /** * Remove the specified {@link Completor} from the list of handlers * for tab-completion. * * @param completor the {@link Completor} to remove * @return true if it was successfully removed */ public boolean removeCompletor(final Completor completor) { return completors.remove(completor); } /** * Returns an unmodifiable list of all the completors. */ public Collection getCompletors() { return Collections.unmodifiableList(completors); } /** * Erase the current line. * * @return false if we failed (e.g., the buffer was empty) */ final boolean resetLine() throws IOException { if (buf.cursor == 0) { return false; } backspaceAll(); return true; } /** * Move the cursor position to the specified absolute index. */ public final boolean setCursorPosition(final int position) throws IOException { return moveCursor(position - buf.cursor) != 0; } /** * Set the current buffer's content to the specified * {@link String}. The visual console will be modified * to show the current buffer. * * @param buffer the new contents of the buffer. */ private final void setBuffer(final String buffer) throws IOException { // don't bother modifying it if it is unchanged if (buffer.equals(buf.buffer.toString())) { return; } // obtain the difference between the current buffer and the new one int sameIndex = 0; for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1) && (i < l2); i++) { if (buffer.charAt(i) == buf.buffer.charAt(i)) { sameIndex++; } else { break; } } int diff = buf.buffer.length() - sameIndex; backspace(diff); // go back for the differences killLine(); // clear to the end of the line buf.buffer.setLength(sameIndex); // the new length putString(buffer.substring(sameIndex)); // append the differences } /** * Clear the line and redraw it. */ public final void redrawLine() throws IOException { printCharacter(RESET_LINE); flushConsole(); drawLine(); } /** * Output put the prompt + the current buffer */ public final void drawLine() throws IOException { if (prompt != null) { printString(prompt); } printString(buf.buffer.toString()); } /** * Output a platform-dependant newline. */ public final void printNewline() throws IOException { printString(CR); flushConsole(); } /** * Clear the buffer and add its contents to the history. * * @return the former contents of the buffer. */ final String finishBuffer() { String str = buf.buffer.toString(); // we only add it to the history if the buffer is not empty // and if mask is null, since having a mask typically means // the string was a password. We clear the mask after this call if (str.length() > 0) { if (mask == null && useHistory) { history.addToHistory(str); } else { mask = null; } } history.moveToEnd(); buf.buffer.setLength(0); buf.cursor = 0; return str; } /** * Write out the specified string to the buffer and the * output stream. */ public final void putString(final String str) throws IOException { buf.insert(str); printString(str); drawBuffer(); } /** * Output the specified string to the output stream (but not the * buffer). */ public final void printString(final String str) throws IOException { printCharacters(str.toCharArray()); } /** * Output the specified character, both to the buffer * and the output stream. */ private final void putChar(final int c, final boolean print) throws IOException { buf.insert((char) c); if (print) { // no masking... if (mask == null) { printCharacter(c); } // null mask: don't print anything... else if (mask.charValue() == 0) { ; } // otherwise print the mask... else { printCharacter(mask.charValue()); } drawBuffer(); } } /** * Redraw the rest of the buffer from the cursor onwards. This * is necessary for inserting text into the buffer. * * @param clear the number of characters to clear after the * end of the buffer */ private final void drawBuffer(final int clear) throws IOException { // debug ("drawBuffer: " + clear); char[] chars = buf.buffer.substring(buf.cursor).toCharArray(); printCharacters(chars); clearAhead(clear); back(chars.length); flushConsole(); } /** * Redraw the rest of the buffer from the cursor onwards. This * is necessary for inserting text into the buffer. */ private final void drawBuffer() throws IOException { drawBuffer(0); } /** * Clear ahead the specified number of characters * without moving the cursor. */ private final void clearAhead(final int num) throws IOException { if (num == 0) { return; } // debug ("clearAhead: " + num); // print blank extra characters printCharacters(' ', num); // we need to flush here so a "clever" console // doesn't just ignore the redundancy of a space followed by // a backspace. flushConsole(); // reset the visual cursor back(num); flushConsole(); } /** * Move the visual cursor backwards without modifying the * buffer cursor. */ private final void back(final int num) throws IOException { printCharacters(BACKSPACE, num); flushConsole(); } /** * Issue an audible keyboard bell, if * {@link #getBellEnabled} return true. */ public final void beep() throws IOException { if (!(getBellEnabled())) { return; } printCharacter(KEYBOARD_BELL); // need to flush so the console actually beeps flushConsole(); } /** * Output the specified character to the output stream * without manipulating the current buffer. */ private final void printCharacter(final int c) throws IOException { out.write(c); } /** * Output the specified characters to the output stream * without manipulating the current buffer. */ private final void printCharacters(final char[] c) throws IOException { out.write(c); } private final void printCharacters(final char c, final int num) throws IOException { if (num == 1) { printCharacter(c); } else { char[] chars = new char[num]; Arrays.fill(chars, c); printCharacters(chars); } } /** * Flush the console output stream. This is important for * printout out single characters (like a backspace or keyboard) * that we want the console to handle immedately. */ public final void flushConsole() throws IOException { out.flush(); } private final int backspaceAll() throws IOException { return backspace(Integer.MAX_VALUE); } /** * Issue <em>num</em> backspaces. * * @return the number of characters backed up */ private final int backspace(final int num) throws IOException { if (buf.cursor == 0) { return 0; } int count = 0; count = moveCursor(-1 * num) * -1; // debug ("Deleting from " + buf.cursor + " for " + count); buf.buffer.delete(buf.cursor, buf.cursor + count); drawBuffer(count); return count; } /** * Issue a backspace. * * @return true if successful */ public final boolean backspace() throws IOException { return backspace(1) == 1; } private final boolean moveToEnd() throws IOException { if (moveCursor(1) == 0) { return false; } while (moveCursor(1) != 0) { ; } return true; } /** * Delete the character at the current position and * redraw the remainder of the buffer. */ private final boolean deleteCurrentCharacter() throws IOException { buf.buffer.deleteCharAt(buf.cursor); drawBuffer(1); return true; } private final boolean previousWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { ; } while (!isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { ; } return true; } private final boolean nextWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(1) != 0)) { ; } while (!isDelimiter(buf.current()) && (moveCursor(1) != 0)) { ; } return true; } private final boolean deletePreviousWord() throws IOException { while (isDelimiter(buf.current()) && backspace()) { ; } while (!isDelimiter(buf.current()) && backspace()) { ; } return true; } /** * Move the cursor <i>where</i> characters. * * @param where if less than 0, move abs(<i>where</i>) to the left, * otherwise move <i>where</i> to the right. * * @return the number of spaces we moved */ private final int moveCursor(final int num) throws IOException { int where = num; if ((buf.cursor == 0) && (where < 0)) { return 0; } if ((buf.cursor == buf.buffer.length()) && (where > 0)) { return 0; } if ((buf.cursor + where) < 0) { where = -buf.cursor; } else if ((buf.cursor + where) > buf.buffer.length()) { where = buf.buffer.length() - buf.cursor; } moveInternal(where); return where; } /** * debug. * * @param str the message to issue. */ public static void debug(final String str) { if (debugger != null) { debugger.println(str); debugger.flush(); } } /** * Move the cursor <i>where</i> characters, withough checking * the current buffer. * * @see #where * * @param where the number of characters to move to the right or left. */ private final void moveInternal(final int where) throws IOException { // debug ("move cursor " + where + " (" // + buf.cursor + " => " + (buf.cursor + where) + ")"); buf.cursor += where; char c; if (where < 0) { c = BACKSPACE; } else if (buf.cursor == 0) { return; } else { c = buf.buffer.charAt(buf.cursor - 1); // draw replacement } // null character mask: don't output anything if (NULL_MASK.equals(mask)) { return; } printCharacters(c, Math.abs(where)); } /** * Read a character from the console. * * @return the character, or -1 if an EOF is received. */ public final int readVirtualKey() throws IOException { int c = terminal.readVirtualKey(in); if (debugger != null) { debug("keystroke: " + c + ""); } // clear any echo characters clearEcho(c); return c; } public final int readCharacter(final char[] allowed) throws IOException { // if we restrict to a limited set and the current character // is not in the set, then try again. char c; Arrays.sort(allowed); // always need to sort before binarySearch while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) == -1); return c; } public void setHistory(final History history) { this.history = history; } public History getHistory() { return this.history; } public void setCompletionHandler (final CompletionHandler completionHandler) { this.completionHandler = completionHandler; } public CompletionHandler getCompletionHandler() { return this.completionHandler; } /** * <p> * Set the echo character. For example, to have "*" entered * when a password is typed: * </p> * * <pre> * myConsoleReader.setEchoCharacter (new Character ('*')); * </pre> * * <p> * Setting the character to <pre>null</pre> will restore normal * character echoing. Setting the character to * <pre>new Character (0)</pre> will cause nothing to be echoed. * </p> * * @param echoCharacter the character to echo to the console in * place of the typed character. */ public void setEchoCharacter(final Character echoCharacter) { this.echoCharacter = echoCharacter; } /** * Returns the echo character. */ public Character getEchoCharacter() { return this.echoCharacter; } /** * No-op for exceptions we want to silently consume. */ private void consumeException(final Throwable e) { } /** * Checks to see if the specified character is a delimiter. We * consider a character a delimiter if it is anything but a letter or * digit. * * @param c the character to test * @return true if it is a delimiter */ private boolean isDelimiter(char c) { return !Character.isLetterOrDigit(c); } /** * Whether or not to add new commands to the history buffer. */ public void setUseHistory(boolean useHistory) { this.useHistory = useHistory; } /** * Whether or not to add new commands to the history buffer. */ public boolean getUseHistory() { return useHistory; } }
false
true
public String readLine(final String prompt, final Character mask) throws IOException { this.mask = mask; if (prompt != null) this.prompt = prompt; try { terminal.beforeReadLine(this, prompt, mask); if ((prompt != null) && (prompt.length() > 0)) { out.write(prompt); out.flush(); } // if the terminal is unsupported, just use plain-java reading if (!terminal.isSupported()) { return readLine(in); } while (true) { int[] next = readBinding(); if (next == null) { return null; } int c = next[0]; int code = next[1]; if (c == -1) { return null; } boolean success = true; switch (code) { case EXIT: // ctrl-d if (buf.buffer.length() == 0) { return null; } case COMPLETE: // tab success = complete(); break; case MOVE_TO_BEG: success = setCursorPosition(0); break; case KILL_LINE: // CTRL-K success = killLine(); break; case CLEAR_SCREEN: // CTRL-L success = clearScreen(); break; case KILL_LINE_PREV: // CTRL-U success = resetLine(); break; case NEWLINE: // enter printNewline(); // output newline return finishBuffer(); case DELETE_PREV_CHAR: // backspace success = backspace(); break; case MOVE_TO_END: success = moveToEnd(); break; case PREV_CHAR: success = moveCursor(-1) != 0; break; case NEXT_CHAR: success = moveCursor(1) != 0; break; case NEXT_HISTORY: success = moveHistory(true); break; case PREV_HISTORY: success = moveHistory(false); break; case REDISPLAY: break; case PASTE: success = paste(); break; case DELETE_PREV_WORD: success = deletePreviousWord(); break; case PREV_WORD: success = previousWord(); break; case NEXT_WORD: success = nextWord(); break; case UNKNOWN:default: putChar(c, true); } if (!(success)) { beep(); } flushConsole(); } } finally { terminal.afterReadLine(this, prompt, mask); } }
public String readLine(final String prompt, final Character mask) throws IOException { this.mask = mask; if (prompt != null) this.prompt = prompt; try { terminal.beforeReadLine(this, this.prompt, mask); if ((this.prompt != null) && (this.prompt.length() > 0)) { out.write(this.prompt); out.flush(); } // if the terminal is unsupported, just use plain-java reading if (!terminal.isSupported()) { return readLine(in); } while (true) { int[] next = readBinding(); if (next == null) { return null; } int c = next[0]; int code = next[1]; if (c == -1) { return null; } boolean success = true; switch (code) { case EXIT: // ctrl-d if (buf.buffer.length() == 0) { return null; } case COMPLETE: // tab success = complete(); break; case MOVE_TO_BEG: success = setCursorPosition(0); break; case KILL_LINE: // CTRL-K success = killLine(); break; case CLEAR_SCREEN: // CTRL-L success = clearScreen(); break; case KILL_LINE_PREV: // CTRL-U success = resetLine(); break; case NEWLINE: // enter printNewline(); // output newline return finishBuffer(); case DELETE_PREV_CHAR: // backspace success = backspace(); break; case MOVE_TO_END: success = moveToEnd(); break; case PREV_CHAR: success = moveCursor(-1) != 0; break; case NEXT_CHAR: success = moveCursor(1) != 0; break; case NEXT_HISTORY: success = moveHistory(true); break; case PREV_HISTORY: success = moveHistory(false); break; case REDISPLAY: break; case PASTE: success = paste(); break; case DELETE_PREV_WORD: success = deletePreviousWord(); break; case PREV_WORD: success = previousWord(); break; case NEXT_WORD: success = nextWord(); break; case UNKNOWN:default: putChar(c, true); } if (!(success)) { beep(); } flushConsole(); } } finally { terminal.afterReadLine(this, this.prompt, mask); } }
diff --git a/moskito-core/java/net/java/dev/moskito/core/timing/UpdateableWrapper.java b/moskito-core/java/net/java/dev/moskito/core/timing/UpdateableWrapper.java index 10db6c10..644da150 100644 --- a/moskito-core/java/net/java/dev/moskito/core/timing/UpdateableWrapper.java +++ b/moskito-core/java/net/java/dev/moskito/core/timing/UpdateableWrapper.java @@ -1,74 +1,75 @@ /* * $Id$ * * This file is part of the MoSKito software project * that is hosted at http://moskito.dev.java.net. * * All MoSKito files are distributed under MIT License: * * Copyright (c) 2006 The MoSKito Project Team. * * 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.java.dev.moskito.core.timing; import java.util.TimerTask; import org.apache.log4j.Logger; /** * This class implements an adapter to handle IUpdatable instances as TimerTask. * * @author lrosenberg */ final class UpdateableWrapper extends TimerTask { private static Logger log = Logger.getLogger(UpdateableWrapper.class); /** * This is the delegate that will be called. */ private IUpdateable delegate; /** * The constructor. * * @param aDelegate the delegate to use */ UpdateableWrapper(IUpdateable aDelegate){ delegate = aDelegate; } @Override public void run() { try{ delegate.update(); }catch(Exception e){ - log.warn("Delegate update failed on "+delegate, e); + if (log!=null) + log.warn("Delegate update failed on "+delegate, e); } } }
true
true
@Override public void run() { try{ delegate.update(); }catch(Exception e){ log.warn("Delegate update failed on "+delegate, e); } }
@Override public void run() { try{ delegate.update(); }catch(Exception e){ if (log!=null) log.warn("Delegate update failed on "+delegate, e); } }
diff --git a/src/play/modules/chronostamp/ChronostampEnhancer.java b/src/play/modules/chronostamp/ChronostampEnhancer.java index 82d85d8..78586bb 100644 --- a/src/play/modules/chronostamp/ChronostampEnhancer.java +++ b/src/play/modules/chronostamp/ChronostampEnhancer.java @@ -1,182 +1,182 @@ package play.modules.chronostamp; import javassist.CtClass; import javassist.CtField; import javassist.CtMethod; import javassist.NotFoundException; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.EnumMemberValue; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ConstPool; import javassist.bytecode.AttributeInfo; import javassist.bytecode.FieldInfo; import javassist.bytecode.MethodInfo; import play.classloading.ApplicationClasses.ApplicationClass; import play.classloading.enhancers.Enhancer; import play.Logger; import java.util.Date; public class ChronostampEnhancer extends Enhancer { @Override public void enhanceThisClass(ApplicationClass appClass) throws Exception { CtClass ctClass = makeClass(appClass); ConstPool constpool = ctClass.getClassFile().getConstPool(); AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); Annotation annot = null; String code = null; EnumMemberValue enumValue = null; // Only enhance model classes. if (!ctClass.subtypeOf(classPool.get("play.db.jpa.JPABase"))) { return; } // Only enhance model classes with Entity annotation. if (!hasAnnotation(ctClass, "javax.persistence.Entity")) { return; } // Skip enhance model classes if are annotated with @NoChronostamp if (hasAnnotation(ctClass, NoChronostamp.class.getName())) { return; } // Only enhance model classes without created_at and updated_at attributes for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getName().equals("created_at") || ctField.getName().equals("updated_at")) { return; } } // ----- Add created_at property ----- CtField created_at = CtField.make("private java.util.Date created_at = new java.util.Date();", ctClass); ctClass.addField(created_at); // ----- Add updated_at property ----- CtField updated_at = CtField.make("private java.util.Date updated_at = new java.util.Date(created_at.getTime());", ctClass); ctClass.addField(updated_at); // ----- Add annotation @Temporal(TemporalType.TIMESTAMP) to created_at and updated_at fields ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); - annot = new Annotation("javax.persistence.TemporalType", constpool); + annot = new Annotation("javax.persistence.Temporal", constpool); enumValue = new EnumMemberValue(constpool); enumValue.setType("javax.persistence.TemporalType"); enumValue.setValue("TIMESTAMP"); annot.addMemberValue("value", enumValue); attr.addAnnotation(annot); created_at.getFieldInfo().addAttribute(attr); updated_at.getFieldInfo().addAttribute(attr); /* // ----- Add onCreate() method ----- code = "public void onCreate() { " + "created_at = new java.util.Date(); " + "updated_at = new java.util.Date(created_at.getTime()); " + "}"; final CtMethod onCreate = CtMethod.make(code, ctClass); ctClass.addMethod(onCreate); // ----- Add annotation @PrePersist to onCreate() method ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.PrePersist", constpool); attr.addAnnotation(annot); onCreate.getMethodInfo().addAttribute(attr); */ // Check if there's a method annotated with @PreUpdate CtMethod methodWithPreUpdateAnnot = null; for (CtMethod ctMethod : ctClass.getDeclaredMethods()) { if (hasAnnotation(ctMethod, javax.persistence.PreUpdate.class.getName())) { methodWithPreUpdateAnnot = ctMethod; } } if (methodWithPreUpdateAnnot != null) { methodWithPreUpdateAnnot.insertBefore("updated_at = new java.util.Date();"); } else { // ----- Add onUpdate() method ----- code = "public void onUpdate() { " + "updated_at = new java.util.Date(); " + "}"; final CtMethod onUpdate = CtMethod.make(code, ctClass); ctClass.addMethod(onUpdate); // ----- Add annotation @PreUpdate to onUpdate() method ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.PreUpdate", constpool); attr.addAnnotation(annot); onUpdate.getMethodInfo().addAttribute(attr); } // ----- GETTERS ----- // ----- Add getCreated_at() method ----- code = "public java.util.Date getCreated_at() { " + "return this.created_at; }"; final CtMethod getCreated_at = CtMethod.make(code, ctClass); ctClass.addMethod(getCreated_at); // ----- Add getCreatedAt() method ----- code = "public java.util.Date getCreatedAt() { " + "return this.created_at; }"; final CtMethod getCreatedAt = CtMethod.make(code, ctClass); ctClass.addMethod(getCreatedAt); // ----- Add getUpdated_at() method ----- code = "public java.util.Date getUpdated_at() { " + "return this.updated_at; }"; final CtMethod getUpdated_at = CtMethod.make(code, ctClass); ctClass.addMethod(getUpdated_at); // ----- Add getUpdatedAt() method ----- code = "public java.util.Date getUpdatedAt() { " + "return this.updated_at; }"; final CtMethod getUpdatedAt = CtMethod.make(code, ctClass); ctClass.addMethod(getUpdatedAt); // Done - Enhance Class. appClass.enhancedByteCode = ctClass.toBytecode(); ctClass.defrost(); } /** * Test if a method has the provided annotation * @param ctMethod the javassist method representation * @param annotation fully qualified name of the annotation class eg."javax.persistence.Entity" * @return true if field has the annotation * @throws java.lang.ClassNotFoundException */ private boolean hasAnnotation(CtMethod ctMethod, String annotation) throws ClassNotFoundException { for (Object object : ctMethod.getAvailableAnnotations()) { java.lang.annotation.Annotation ann = (java.lang.annotation.Annotation) object; if (ann.annotationType().getName().equals(annotation)) { return true; } } return false; } }
true
true
public void enhanceThisClass(ApplicationClass appClass) throws Exception { CtClass ctClass = makeClass(appClass); ConstPool constpool = ctClass.getClassFile().getConstPool(); AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); Annotation annot = null; String code = null; EnumMemberValue enumValue = null; // Only enhance model classes. if (!ctClass.subtypeOf(classPool.get("play.db.jpa.JPABase"))) { return; } // Only enhance model classes with Entity annotation. if (!hasAnnotation(ctClass, "javax.persistence.Entity")) { return; } // Skip enhance model classes if are annotated with @NoChronostamp if (hasAnnotation(ctClass, NoChronostamp.class.getName())) { return; } // Only enhance model classes without created_at and updated_at attributes for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getName().equals("created_at") || ctField.getName().equals("updated_at")) { return; } } // ----- Add created_at property ----- CtField created_at = CtField.make("private java.util.Date created_at = new java.util.Date();", ctClass); ctClass.addField(created_at); // ----- Add updated_at property ----- CtField updated_at = CtField.make("private java.util.Date updated_at = new java.util.Date(created_at.getTime());", ctClass); ctClass.addField(updated_at); // ----- Add annotation @Temporal(TemporalType.TIMESTAMP) to created_at and updated_at fields ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.TemporalType", constpool); enumValue = new EnumMemberValue(constpool); enumValue.setType("javax.persistence.TemporalType"); enumValue.setValue("TIMESTAMP"); annot.addMemberValue("value", enumValue); attr.addAnnotation(annot); created_at.getFieldInfo().addAttribute(attr); updated_at.getFieldInfo().addAttribute(attr); /* // ----- Add onCreate() method ----- code = "public void onCreate() { " + "created_at = new java.util.Date(); " + "updated_at = new java.util.Date(created_at.getTime()); " + "}"; final CtMethod onCreate = CtMethod.make(code, ctClass); ctClass.addMethod(onCreate); // ----- Add annotation @PrePersist to onCreate() method ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.PrePersist", constpool); attr.addAnnotation(annot); onCreate.getMethodInfo().addAttribute(attr); */ // Check if there's a method annotated with @PreUpdate CtMethod methodWithPreUpdateAnnot = null; for (CtMethod ctMethod : ctClass.getDeclaredMethods()) { if (hasAnnotation(ctMethod, javax.persistence.PreUpdate.class.getName())) { methodWithPreUpdateAnnot = ctMethod; } } if (methodWithPreUpdateAnnot != null) { methodWithPreUpdateAnnot.insertBefore("updated_at = new java.util.Date();"); } else { // ----- Add onUpdate() method ----- code = "public void onUpdate() { " + "updated_at = new java.util.Date(); " + "}"; final CtMethod onUpdate = CtMethod.make(code, ctClass); ctClass.addMethod(onUpdate); // ----- Add annotation @PreUpdate to onUpdate() method ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.PreUpdate", constpool); attr.addAnnotation(annot); onUpdate.getMethodInfo().addAttribute(attr); } // ----- GETTERS ----- // ----- Add getCreated_at() method ----- code = "public java.util.Date getCreated_at() { " + "return this.created_at; }"; final CtMethod getCreated_at = CtMethod.make(code, ctClass); ctClass.addMethod(getCreated_at); // ----- Add getCreatedAt() method ----- code = "public java.util.Date getCreatedAt() { " + "return this.created_at; }"; final CtMethod getCreatedAt = CtMethod.make(code, ctClass); ctClass.addMethod(getCreatedAt); // ----- Add getUpdated_at() method ----- code = "public java.util.Date getUpdated_at() { " + "return this.updated_at; }"; final CtMethod getUpdated_at = CtMethod.make(code, ctClass); ctClass.addMethod(getUpdated_at); // ----- Add getUpdatedAt() method ----- code = "public java.util.Date getUpdatedAt() { " + "return this.updated_at; }"; final CtMethod getUpdatedAt = CtMethod.make(code, ctClass); ctClass.addMethod(getUpdatedAt); // Done - Enhance Class. appClass.enhancedByteCode = ctClass.toBytecode(); ctClass.defrost(); }
public void enhanceThisClass(ApplicationClass appClass) throws Exception { CtClass ctClass = makeClass(appClass); ConstPool constpool = ctClass.getClassFile().getConstPool(); AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); Annotation annot = null; String code = null; EnumMemberValue enumValue = null; // Only enhance model classes. if (!ctClass.subtypeOf(classPool.get("play.db.jpa.JPABase"))) { return; } // Only enhance model classes with Entity annotation. if (!hasAnnotation(ctClass, "javax.persistence.Entity")) { return; } // Skip enhance model classes if are annotated with @NoChronostamp if (hasAnnotation(ctClass, NoChronostamp.class.getName())) { return; } // Only enhance model classes without created_at and updated_at attributes for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getName().equals("created_at") || ctField.getName().equals("updated_at")) { return; } } // ----- Add created_at property ----- CtField created_at = CtField.make("private java.util.Date created_at = new java.util.Date();", ctClass); ctClass.addField(created_at); // ----- Add updated_at property ----- CtField updated_at = CtField.make("private java.util.Date updated_at = new java.util.Date(created_at.getTime());", ctClass); ctClass.addField(updated_at); // ----- Add annotation @Temporal(TemporalType.TIMESTAMP) to created_at and updated_at fields ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.Temporal", constpool); enumValue = new EnumMemberValue(constpool); enumValue.setType("javax.persistence.TemporalType"); enumValue.setValue("TIMESTAMP"); annot.addMemberValue("value", enumValue); attr.addAnnotation(annot); created_at.getFieldInfo().addAttribute(attr); updated_at.getFieldInfo().addAttribute(attr); /* // ----- Add onCreate() method ----- code = "public void onCreate() { " + "created_at = new java.util.Date(); " + "updated_at = new java.util.Date(created_at.getTime()); " + "}"; final CtMethod onCreate = CtMethod.make(code, ctClass); ctClass.addMethod(onCreate); // ----- Add annotation @PrePersist to onCreate() method ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.PrePersist", constpool); attr.addAnnotation(annot); onCreate.getMethodInfo().addAttribute(attr); */ // Check if there's a method annotated with @PreUpdate CtMethod methodWithPreUpdateAnnot = null; for (CtMethod ctMethod : ctClass.getDeclaredMethods()) { if (hasAnnotation(ctMethod, javax.persistence.PreUpdate.class.getName())) { methodWithPreUpdateAnnot = ctMethod; } } if (methodWithPreUpdateAnnot != null) { methodWithPreUpdateAnnot.insertBefore("updated_at = new java.util.Date();"); } else { // ----- Add onUpdate() method ----- code = "public void onUpdate() { " + "updated_at = new java.util.Date(); " + "}"; final CtMethod onUpdate = CtMethod.make(code, ctClass); ctClass.addMethod(onUpdate); // ----- Add annotation @PreUpdate to onUpdate() method ----- //attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); annot = new Annotation("javax.persistence.PreUpdate", constpool); attr.addAnnotation(annot); onUpdate.getMethodInfo().addAttribute(attr); } // ----- GETTERS ----- // ----- Add getCreated_at() method ----- code = "public java.util.Date getCreated_at() { " + "return this.created_at; }"; final CtMethod getCreated_at = CtMethod.make(code, ctClass); ctClass.addMethod(getCreated_at); // ----- Add getCreatedAt() method ----- code = "public java.util.Date getCreatedAt() { " + "return this.created_at; }"; final CtMethod getCreatedAt = CtMethod.make(code, ctClass); ctClass.addMethod(getCreatedAt); // ----- Add getUpdated_at() method ----- code = "public java.util.Date getUpdated_at() { " + "return this.updated_at; }"; final CtMethod getUpdated_at = CtMethod.make(code, ctClass); ctClass.addMethod(getUpdated_at); // ----- Add getUpdatedAt() method ----- code = "public java.util.Date getUpdatedAt() { " + "return this.updated_at; }"; final CtMethod getUpdatedAt = CtMethod.make(code, ctClass); ctClass.addMethod(getUpdatedAt); // Done - Enhance Class. appClass.enhancedByteCode = ctClass.toBytecode(); ctClass.defrost(); }
diff --git a/src/cs437/som/network/BasicPlanarSOM.java b/src/cs437/som/network/BasicPlanarSOM.java index 1f34b84..f525038 100644 --- a/src/cs437/som/network/BasicPlanarSOM.java +++ b/src/cs437/som/network/BasicPlanarSOM.java @@ -1,101 +1,101 @@ package cs437.som.network; import cs437.som.Dimension; import cs437.som.SOMError; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A basic self-organizing map where the neurons are arranged by their weights. * * An simple example usage: * * <code> * <pre> * private static final int iterations = 500; * * public static void main(String[] args) { * TrainableSelfOrganizingMap som = new BasicPlanarSOM(7, 2, iterations); * Random r = new SecureRandom(); * * for (int i = 0; i < iterations; i++) { * double[] in = {r.nextDouble() * 10, r.nextDouble() * 10}; * som.trainWith(in); * } * * // At this point, the SOM would be queried for it's BMU. * } * </pre> * </code> */ public class BasicPlanarSOM extends NetworkBase { /** * Create a new BasicPlanarSOM. * * @param neuronCount The number of neurons to employ. * @param inputVectorSize The input vector size. * @param expectedIterations The expected number of training iterations. */ public BasicPlanarSOM(int neuronCount, int inputVectorSize, int expectedIterations) { super(new Dimension(neuronCount, 1), inputVectorSize, expectedIterations); } @Override protected double neuronDistance(int neuron0, int neuron1) { double sum = 0.0; for (int i = 0; i < inputVectorSize; i++) { double difference = weightMatrix[neuron0][i] - weightMatrix[neuron1][i]; sum += difference * difference; } return Math.sqrt(sum); } @Override protected double neighborhoodWidth() { if (time < (expectedIterations / 5)) return 1.0 * (1.0 - (time / (double) expectedIterations)); return 0.0; } @Override public String toString() { return "BasicPlanarSOM{weightMatrix=" + (weightMatrix == null ? null : Arrays.toString(weightMatrix)) + '}'; } @Override public void write(OutputStreamWriter destination) throws IOException { destination.write(String.format("Map type: BasicPlanarSOM%n")); super.write(destination); destination.flush(); } /** * Read a BasicPlanarSOM from an input stream. * * @param input The stream to read from. This stream should be passed in * as soon as it is known to represent a BasicPlanarSOM. * @return A BasicPlanarSOM as represented by the contents of * {@code input}. * @throws IOException if something fails while reading the stream. */ public static BasicPlanarSOM read(BufferedReader input) throws IOException { SOMFileReader sfr = new SOMFileReader(); sfr.parse(input); - BasicPlanarSOM bhgsom = new BasicPlanarSOM( + BasicPlanarSOM bpsom = new BasicPlanarSOM( sfr.dimension.x, sfr.inputVectorSize, sfr.iterations); - bhgsom.weightMatrix = readWeightMatrix( + bpsom.weightMatrix = readWeightMatrix( input, sfr.dimension.area, sfr.inputVectorSize); - return bhgsom; + return bpsom; } }
false
true
public static BasicPlanarSOM read(BufferedReader input) throws IOException { SOMFileReader sfr = new SOMFileReader(); sfr.parse(input); BasicPlanarSOM bhgsom = new BasicPlanarSOM( sfr.dimension.x, sfr.inputVectorSize, sfr.iterations); bhgsom.weightMatrix = readWeightMatrix( input, sfr.dimension.area, sfr.inputVectorSize); return bhgsom; }
public static BasicPlanarSOM read(BufferedReader input) throws IOException { SOMFileReader sfr = new SOMFileReader(); sfr.parse(input); BasicPlanarSOM bpsom = new BasicPlanarSOM( sfr.dimension.x, sfr.inputVectorSize, sfr.iterations); bpsom.weightMatrix = readWeightMatrix( input, sfr.dimension.area, sfr.inputVectorSize); return bpsom; }
diff --git a/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java b/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java index bcac08b..8274a05 100644 --- a/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java +++ b/webapp/WEB-INF/classes/org/makumba/parade/access/DatabaseLogServlet.java @@ -1,490 +1,490 @@ package org.makumba.parade.access; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Date; import java.util.List; import java.util.logging.LogRecord; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.makumba.parade.init.InitServlet; import org.makumba.parade.init.RowProperties; import org.makumba.parade.model.ActionLog; import org.makumba.parade.model.Log; import org.makumba.parade.model.User; import org.makumba.parade.tools.PerThreadPrintStreamLogRecord; import org.makumba.parade.tools.TriggerFilter; import org.makumba.parade.view.TickerTapeData; import org.makumba.parade.view.TickerTapeServlet; /** * This servlet makes it possible to log events from various sources into the database. It persists two kinds of logs: * <ul> * <li>ActionLogs, generated at each access</li> * <li>Logs, which are representing one log "line" and link to the ActionLog which led to their generation</li> * </ul> * * TODO improve filtering * * @author Manuel Gay * */ public class DatabaseLogServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private Logger logger = Logger.getLogger(DatabaseLogServlet.class); private RowProperties rp; private ActionLogDTO lastCommit; private String lastCommitId; public void init(ServletConfig conf) { rp = new RowProperties(); } public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { // when we start tomcat we are not ready yet to log // we first need a Hibernate SessionFactory to be initalised // this happens only after the Initservlet was loaded req.removeAttribute("org.makumba.parade.servletSuccess"); if (InitServlet.getSessionFactory() == null) return; req.setAttribute("org.makumba.parade.servletSuccess", true); // retrieve the record guy Object record = req.getAttribute("org.makumba.parade.servletParam"); if (record == null) return; // first check if this should be logged at all if (record instanceof ActionLogDTO) { if (!shouldLog((ActionLogDTO) record)) return; } // open a new session, which we need to perform extraction Session s = null; try { s = InitServlet.getSessionFactory().openSession(); if (record instanceof ActionLogDTO) { handleActionLog(req, record, s); } else { handleLog(req, record, s); } } finally { // close the session in any case s.close(); } } catch (NullPointerException npe) { //throw(npe); PrintWriter p = new PrintWriter(new StringWriter()); npe.printStackTrace(p); logger.error("\n***********************************************************************\n" + "NPE in database log servlet. please tell developers!\n" + "error message is:\n" + p.toString() + "***********************************************************************"); } } private void handleActionLog(HttpServletRequest req, Object record, Session s) { ActionLogDTO log = (ActionLogDTO) record; // filter the log, generate additional information and give some meaning filterLog(log, s); // sometimes we just don't log (like for commits) if (log.getAction().equals("paradeCvsCommit")) return; // let's see if we have already someone. if not, we create one Transaction tx = s.beginTransaction(); ActionLog actionLog = null; if (log.getId() == null) { actionLog = new ActionLog(); } else { actionLog = (ActionLog) s.get(ActionLog.class, log.getId()); } log.populate(actionLog); s.saveOrUpdate(actionLog); tx.commit(); // if we didn't have a brand new actionLog (meaning, a log with some info) // we add the populated actionLog as an event to the tickertape // TODO refactor me if (log.getId() != null) { String row = (log.getParadecontext() == null || log.getParadecontext().equals("null")) ? ((log.getContext() == null || log .getContext().equals("null")) ? "parade2" : log.getContext()) : log.getParadecontext(); String actionText = ""; if (log.getAction() != null && !log.getAction().equals("null")) actionText = "user " + log.getUser() + " in row " + row + " did action: " + log.getAction(); TickerTapeData data = new TickerTapeData(actionText, "", log.getDate().toString()); TickerTapeServlet.addItem(data); } // finally we also need to update the ActionLog in the thread log.setId(actionLog.getId()); TriggerFilter.actionLog.set(log); } /** * Filter that does some "cosmetics" on the log and extracts meaning * * @param log * the original log to be altered */ private void filterLog(ActionLogDTO log, Session s) { String queryString = log.getQueryString(); String uri = log.getUrl(); if (uri == null) uri = ""; if (queryString == null) queryString = ""; if (log.getAction() == null) log.setAction(""); if(log.getParadecontext() == null) { log.setParadecontext(getParam("context", queryString)); } String actionType = "", op = "", params = "", display = "", path = "", file = ""; if (uri.indexOf("browse.jsp") > -1) actionType = "browseRow"; if (uri.indexOf("/servlet/browse") > -1) actionType = "browse"; if (uri.indexOf("File.do") > -1) actionType = "file"; if (uri.indexOf("File.do") > -1 && queryString.indexOf("browse&") > -1) actionType = "fileBrowse"; if (uri.indexOf("Cvs.do") > -1) actionType = "cvs"; op = getParam("op", queryString); params = getParam("params", queryString); display = getParam("display", queryString); path = getParam("path", queryString); file = getParam("file", queryString); if (op == null) op = ""; if (params == null) params = ""; if (display == null) display = ""; if (path == null) path = ""; if (file == null) file = ""; // browse actions if (actionType.equals("browseRow")) { log.setAction("browseRow"); } if (actionType.equals("browse") || actionType.equals("fileBrowse")) { log.setAction("browseDir"); log.setFile(nicePath(path, "")); } // view actions if (uri.endsWith(".jspx")) { log.setAction("view"); // fetch the webapp root in a hackish way String webapp = rp.getRowDefinitions().get(log.getParadecontext()).get("webapp"); log.setFile("/" + webapp + uri.substring(0, uri.length() - 1)); } // edit (open editor) if (actionType.equals("file") && op.equals("editFile")) { log.setAction("edit"); log.setFile(nicePath(path, file)); } // save if (actionType.equals("file") && op.equals("saveFile")) { log.setAction("save"); log.setFile(nicePath(path, file)); } // delete if (actionType.equals("file") && op.equals("deleteFile")) { log.setAction("delete"); log.setFile(nicePath(path, params)); } // CVS if (actionType.equals("cvs")) { if (op.equals("check")) { log.setAction("cvsCheck"); log.setFile("/" + params); } if (op.equals("update")) { log.setAction("cvsUpdateDirLocal"); log.setFile("/" + params); } if (op.equals("rupdate")) { log.setAction("cvsUpdateDirRecursive"); log.setFile("/" + params); } if (op.equals("commit")) { log.setAction("paradeCvsCommit"); String[] commitParams = getParamValues("params", queryString, null, 0); log.setFile(nicePath(commitParams[1], "")); // for some weird reason, commit gets logged twice (maybe because of struts?) // so since we don't want this, we do a check if(lastCommitId != null && lastCommitId.equals(log.getFile() + log.getQueryString())) { lastCommitId = null; // we ignore that log } else { lastCommit = log; } } if (op.equals("diff")) { log.setAction("cvsDiff"); - log.setAction("/" + file); + log.setFile("/" + file); } if (op.equals("add") || op.equals("addbin")) { log.setAction("cvsAdd"); log.setFile("/" + file); } if (op.equals("updatefile")) { log.setAction("cvsUpdateFile"); log.setFile("/" + file); } if (op.equals("overridefile")) { log.setAction("cvsOverrideFile"); log.setFile("/" + file); } if (op.equals("deletefile")) { log.setAction("cvsDeleteFile"); log.setFile("/" + file); } } // CVS commit (hook) if (log.getAction().equals("cvsCommitRepository")) { log.setAction("cvsCommit"); if (lastCommit != null && lastCommit.getFile() != null) { // the user commited through parade // we just check if it's the same file that has been commited through parade so we don't log it twice // (it will be logged anyway after this) // and we also add other useful info if (lastCommit.getFile().equals(log.getFile())) { lastCommitId = lastCommit.getFile()+lastCommit.getQueryString(); log.setQueryString(lastCommit.getQueryString() + log.getQueryString()); log.setContext(lastCommit.getContext()); log.setParadecontext(lastCommit.getParadecontext()); log.setUser(lastCommit.getUser()); lastCommit = null; } else { logger.error("***********************************************************************\n" + "Unrecognised parade commit. please tell developers!\n" + "***********************************************************************"); } } else { // this is an external commit that doesn't come thru parade // let's try to see if we know the user who did the commit Transaction tx = s.beginTransaction(); Query q = s.createQuery("from User u where u.cvsuser = ?"); q.setString(0, log.getUser()); List<User> results = q.list(); if(results.size() > 0) { User u = results.get(0); if (u != null) { log.setUser(u.getLogin()); } } tx.commit(); } } } private String nicePath(String path, String file) { try { path = path.indexOf("%") > -1 ? URLDecoder.decode(path, "UTF-8") : path; path = path.startsWith("/") ? "" : "/" + (path.endsWith("/") ? path.substring(0, path.length() - 1) : path); file = file.indexOf("%") > -1 ? URLDecoder.decode(file, "UTF-8") : file; file = file.startsWith("/") ? file : file.length() == 0 ? "" : "/" + file; } catch (UnsupportedEncodingException e) { // shouldn't happen } return path + file; } private String getParam(String paramName, String queryString) { int n = queryString.indexOf(paramName + "="); String param = null; if (n > -1) { param = queryString.substring(n + paramName.length() + 1); if (param.indexOf("&") > -1) { param = param.substring(0, param.indexOf("&")); } } return param; } private String[] getParamValues(String paramName, String queryString, String[] paramValues, int pos) { if (pos == 0) { paramValues = new String[5]; } int n = queryString.indexOf(paramName + "="); String param = null; if (n > -1) { param = queryString.substring(n + paramName.length() + 1); if (param.indexOf("&") > -1) { param = param.substring(0, param.indexOf("&")); } paramValues[pos] = param; String qs = queryString.substring(0, n) + queryString.substring(n + paramName.length() + 1 + param.length()); pos++; return getParamValues(paramName, qs, paramValues, pos); } return paramValues; } /** * Checks whether this access should be logged or not * * @param log * the DTO containing the log entry * @return <code>true</code> if this is worth logging, <code>false</code> otherwise */ private boolean shouldLog(ActionLogDTO log) { if (log.getUrl() != null && (log.getUrl().endsWith(".ico") || log.getUrl().endsWith(".css") || log.getUrl().endsWith(".gif") || log.getUrl().endsWith(".js") || log.getUrl().equals("/servlet/ticker") || log.getUrl().equals("/servlet/cvscommit/") || log.getUrl().equals("/tipOfTheDay.jsp") || log.getUrl().equals("/index.jsp") || log.getUrl().equals("/") || log.getUrl().startsWith("playground") || (log.getUrl().equals("/servlet/browse") && log.getQueryString().indexOf("display=header") > -1) || (log.getUrl().equals("/servlet/browse") && log.getQueryString().indexOf("display=tree") > -1) || (log.getUrl().equals("/servlet/browse") && log.getQueryString().indexOf("display=command") > -1) || (log.getUrl().equals("File.do") && log.getQueryString().indexOf("display=command&view=new") > -1) || log.getUrl().equals("/Command.do") || log.getUrl().startsWith("/scripts/codepress/")) || (log.getOrigin() != null && log.getOrigin().equals("tomcat"))) { return false; } return true; } private void handleLog(HttpServletRequest req, Object record, Session s) { // extract useful information from the record Log log = new Log(); ActionLog actionLog = retrieveActionLog(s); log.setActionLog(actionLog); // this is a java.util.logging.LogRecord if (record instanceof LogRecord) { LogRecord logrecord = (LogRecord) record; log.setDate(new Date(logrecord.getMillis())); log.setLevel(logrecord.getLevel().getName()); log.setMessage(logrecord.getMessage()); log.setOrigin("java.util.Logging"); // log.setThrowable(logrecord.getThrown()); } else if (record instanceof LoggingEvent) { LoggingEvent logevent = (LoggingEvent) record; log.setOrigin("log4j"); log.setDate(new Date(logevent.timeStamp)); log.setLevel(logevent.getLevel().toString()); log.setMessage(logevent.getRenderedMessage()); // if(logevent.getThrowableInformation() != null) // log.setThrowable(logevent.getThrowableInformation().getThrowable()); // else // log.setThrowable(null); } else if (record instanceof PerThreadPrintStreamLogRecord) { PerThreadPrintStreamLogRecord pRecord = (PerThreadPrintStreamLogRecord) record; log.setDate(pRecord.getDate()); log.setOrigin("stdout"); log.setLevel("INFO"); log.setMessage(pRecord.getMessage()); // log.setThrowable(null); } else if (record instanceof Object[]) { Object[] rec = (Object[]) record; log.setDate((Date) rec[0]); log.setOrigin("TriggerFilter"); log.setLevel("INFO"); log.setMessage((String) rec[1]); } Transaction tx = s.beginTransaction(); // write the guy to the db s.saveOrUpdate(log); tx.commit(); } private ActionLog retrieveActionLog(Session s) { ActionLogDTO actionLogDTO = TriggerFilter.actionLog.get(); ActionLog actionLog = new ActionLog(); actionLogDTO.populate(actionLog); // if the actionLog is there but not persisted, we persist it first if (actionLog.getId() == null) { Transaction tx = s.beginTransaction(); s.save(actionLog); tx.commit(); actionLogDTO.setId(actionLog.getId()); TriggerFilter.actionLog.set(actionLogDTO); } else { actionLog = (ActionLog) s.get(ActionLog.class, actionLogDTO.getId()); } return actionLog; } }
true
true
private void filterLog(ActionLogDTO log, Session s) { String queryString = log.getQueryString(); String uri = log.getUrl(); if (uri == null) uri = ""; if (queryString == null) queryString = ""; if (log.getAction() == null) log.setAction(""); if(log.getParadecontext() == null) { log.setParadecontext(getParam("context", queryString)); } String actionType = "", op = "", params = "", display = "", path = "", file = ""; if (uri.indexOf("browse.jsp") > -1) actionType = "browseRow"; if (uri.indexOf("/servlet/browse") > -1) actionType = "browse"; if (uri.indexOf("File.do") > -1) actionType = "file"; if (uri.indexOf("File.do") > -1 && queryString.indexOf("browse&") > -1) actionType = "fileBrowse"; if (uri.indexOf("Cvs.do") > -1) actionType = "cvs"; op = getParam("op", queryString); params = getParam("params", queryString); display = getParam("display", queryString); path = getParam("path", queryString); file = getParam("file", queryString); if (op == null) op = ""; if (params == null) params = ""; if (display == null) display = ""; if (path == null) path = ""; if (file == null) file = ""; // browse actions if (actionType.equals("browseRow")) { log.setAction("browseRow"); } if (actionType.equals("browse") || actionType.equals("fileBrowse")) { log.setAction("browseDir"); log.setFile(nicePath(path, "")); } // view actions if (uri.endsWith(".jspx")) { log.setAction("view"); // fetch the webapp root in a hackish way String webapp = rp.getRowDefinitions().get(log.getParadecontext()).get("webapp"); log.setFile("/" + webapp + uri.substring(0, uri.length() - 1)); } // edit (open editor) if (actionType.equals("file") && op.equals("editFile")) { log.setAction("edit"); log.setFile(nicePath(path, file)); } // save if (actionType.equals("file") && op.equals("saveFile")) { log.setAction("save"); log.setFile(nicePath(path, file)); } // delete if (actionType.equals("file") && op.equals("deleteFile")) { log.setAction("delete"); log.setFile(nicePath(path, params)); } // CVS if (actionType.equals("cvs")) { if (op.equals("check")) { log.setAction("cvsCheck"); log.setFile("/" + params); } if (op.equals("update")) { log.setAction("cvsUpdateDirLocal"); log.setFile("/" + params); } if (op.equals("rupdate")) { log.setAction("cvsUpdateDirRecursive"); log.setFile("/" + params); } if (op.equals("commit")) { log.setAction("paradeCvsCommit"); String[] commitParams = getParamValues("params", queryString, null, 0); log.setFile(nicePath(commitParams[1], "")); // for some weird reason, commit gets logged twice (maybe because of struts?) // so since we don't want this, we do a check if(lastCommitId != null && lastCommitId.equals(log.getFile() + log.getQueryString())) { lastCommitId = null; // we ignore that log } else { lastCommit = log; } } if (op.equals("diff")) { log.setAction("cvsDiff"); log.setAction("/" + file); } if (op.equals("add") || op.equals("addbin")) { log.setAction("cvsAdd"); log.setFile("/" + file); } if (op.equals("updatefile")) { log.setAction("cvsUpdateFile"); log.setFile("/" + file); } if (op.equals("overridefile")) { log.setAction("cvsOverrideFile"); log.setFile("/" + file); } if (op.equals("deletefile")) { log.setAction("cvsDeleteFile"); log.setFile("/" + file); } } // CVS commit (hook) if (log.getAction().equals("cvsCommitRepository")) { log.setAction("cvsCommit"); if (lastCommit != null && lastCommit.getFile() != null) { // the user commited through parade // we just check if it's the same file that has been commited through parade so we don't log it twice // (it will be logged anyway after this) // and we also add other useful info if (lastCommit.getFile().equals(log.getFile())) { lastCommitId = lastCommit.getFile()+lastCommit.getQueryString(); log.setQueryString(lastCommit.getQueryString() + log.getQueryString()); log.setContext(lastCommit.getContext()); log.setParadecontext(lastCommit.getParadecontext()); log.setUser(lastCommit.getUser()); lastCommit = null; } else { logger.error("***********************************************************************\n" + "Unrecognised parade commit. please tell developers!\n" + "***********************************************************************"); } } else { // this is an external commit that doesn't come thru parade // let's try to see if we know the user who did the commit Transaction tx = s.beginTransaction(); Query q = s.createQuery("from User u where u.cvsuser = ?"); q.setString(0, log.getUser()); List<User> results = q.list(); if(results.size() > 0) { User u = results.get(0); if (u != null) { log.setUser(u.getLogin()); } } tx.commit(); } } }
private void filterLog(ActionLogDTO log, Session s) { String queryString = log.getQueryString(); String uri = log.getUrl(); if (uri == null) uri = ""; if (queryString == null) queryString = ""; if (log.getAction() == null) log.setAction(""); if(log.getParadecontext() == null) { log.setParadecontext(getParam("context", queryString)); } String actionType = "", op = "", params = "", display = "", path = "", file = ""; if (uri.indexOf("browse.jsp") > -1) actionType = "browseRow"; if (uri.indexOf("/servlet/browse") > -1) actionType = "browse"; if (uri.indexOf("File.do") > -1) actionType = "file"; if (uri.indexOf("File.do") > -1 && queryString.indexOf("browse&") > -1) actionType = "fileBrowse"; if (uri.indexOf("Cvs.do") > -1) actionType = "cvs"; op = getParam("op", queryString); params = getParam("params", queryString); display = getParam("display", queryString); path = getParam("path", queryString); file = getParam("file", queryString); if (op == null) op = ""; if (params == null) params = ""; if (display == null) display = ""; if (path == null) path = ""; if (file == null) file = ""; // browse actions if (actionType.equals("browseRow")) { log.setAction("browseRow"); } if (actionType.equals("browse") || actionType.equals("fileBrowse")) { log.setAction("browseDir"); log.setFile(nicePath(path, "")); } // view actions if (uri.endsWith(".jspx")) { log.setAction("view"); // fetch the webapp root in a hackish way String webapp = rp.getRowDefinitions().get(log.getParadecontext()).get("webapp"); log.setFile("/" + webapp + uri.substring(0, uri.length() - 1)); } // edit (open editor) if (actionType.equals("file") && op.equals("editFile")) { log.setAction("edit"); log.setFile(nicePath(path, file)); } // save if (actionType.equals("file") && op.equals("saveFile")) { log.setAction("save"); log.setFile(nicePath(path, file)); } // delete if (actionType.equals("file") && op.equals("deleteFile")) { log.setAction("delete"); log.setFile(nicePath(path, params)); } // CVS if (actionType.equals("cvs")) { if (op.equals("check")) { log.setAction("cvsCheck"); log.setFile("/" + params); } if (op.equals("update")) { log.setAction("cvsUpdateDirLocal"); log.setFile("/" + params); } if (op.equals("rupdate")) { log.setAction("cvsUpdateDirRecursive"); log.setFile("/" + params); } if (op.equals("commit")) { log.setAction("paradeCvsCommit"); String[] commitParams = getParamValues("params", queryString, null, 0); log.setFile(nicePath(commitParams[1], "")); // for some weird reason, commit gets logged twice (maybe because of struts?) // so since we don't want this, we do a check if(lastCommitId != null && lastCommitId.equals(log.getFile() + log.getQueryString())) { lastCommitId = null; // we ignore that log } else { lastCommit = log; } } if (op.equals("diff")) { log.setAction("cvsDiff"); log.setFile("/" + file); } if (op.equals("add") || op.equals("addbin")) { log.setAction("cvsAdd"); log.setFile("/" + file); } if (op.equals("updatefile")) { log.setAction("cvsUpdateFile"); log.setFile("/" + file); } if (op.equals("overridefile")) { log.setAction("cvsOverrideFile"); log.setFile("/" + file); } if (op.equals("deletefile")) { log.setAction("cvsDeleteFile"); log.setFile("/" + file); } } // CVS commit (hook) if (log.getAction().equals("cvsCommitRepository")) { log.setAction("cvsCommit"); if (lastCommit != null && lastCommit.getFile() != null) { // the user commited through parade // we just check if it's the same file that has been commited through parade so we don't log it twice // (it will be logged anyway after this) // and we also add other useful info if (lastCommit.getFile().equals(log.getFile())) { lastCommitId = lastCommit.getFile()+lastCommit.getQueryString(); log.setQueryString(lastCommit.getQueryString() + log.getQueryString()); log.setContext(lastCommit.getContext()); log.setParadecontext(lastCommit.getParadecontext()); log.setUser(lastCommit.getUser()); lastCommit = null; } else { logger.error("***********************************************************************\n" + "Unrecognised parade commit. please tell developers!\n" + "***********************************************************************"); } } else { // this is an external commit that doesn't come thru parade // let's try to see if we know the user who did the commit Transaction tx = s.beginTransaction(); Query q = s.createQuery("from User u where u.cvsuser = ?"); q.setString(0, log.getUser()); List<User> results = q.list(); if(results.size() > 0) { User u = results.get(0); if (u != null) { log.setUser(u.getLogin()); } } tx.commit(); } } }
diff --git a/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java b/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java index 19b1a508c..7cfc44bd7 100644 --- a/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java +++ b/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java @@ -1,4603 +1,4604 @@ /* * 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.xerces.impl.xs; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.Vector; import javax.xml.XMLConstants; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.RevalidationHandler; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.dv.DatatypeException; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl; import org.apache.xerces.impl.validation.ConfigurableValidationState; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.impl.validation.ValidationState; import org.apache.xerces.impl.xs.identity.Field; import org.apache.xerces.impl.xs.identity.FieldActivator; import org.apache.xerces.impl.xs.identity.IdentityConstraint; import org.apache.xerces.impl.xs.identity.KeyRef; import org.apache.xerces.impl.xs.identity.Selector; import org.apache.xerces.impl.xs.identity.UniqueOrKey; import org.apache.xerces.impl.xs.identity.ValueStore; import org.apache.xerces.impl.xs.identity.XPathMatcher; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.CMNodeFactory; import org.apache.xerces.impl.xs.models.XSCMValidator; import org.apache.xerces.util.AugmentationsImpl; import org.apache.xerces.util.IntStack; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLAttributesImpl; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.util.URI.MalformedURIException; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xs.AttributePSVI; import org.apache.xerces.xs.ElementPSVI; import org.apache.xerces.xs.ShortList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSTypeDefinition; /** * The XML Schema validator. The validator implements a document * filter: receiving document events from the scanner; validating * the content and structure; augmenting the InfoSet, if applicable; * and notifying the parser of the information resulting from the * validation process. * <p> * This component requires the following features and properties from the * component manager that uses it: * <ul> * <li>http://xml.org/sax/features/validation</li> * <li>http://apache.org/xml/properties/internal/symbol-table</li> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * <li>http://apache.org/xml/properties/internal/entity-resolver</li> * </ul> * * @xerces.internal * * @author Sandy Gao IBM * @author Elena Litani IBM * @author Andy Clark IBM * @author Neeraj Bajaj, Sun Microsystems, inc. * @version $Id$ */ public class XMLSchemaValidator implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler, XSElementDeclHelper { // // Constants // private static final boolean DEBUG = false; // feature identifiers /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: validation. */ protected static final String SCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: schema full checking*/ protected static final String SCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; /** Feature identifier: dynamic validation. */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: send element default value via characters() */ protected static final String SCHEMA_ELEMENT_DEFAULT = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT; /** Feature identifier: augment PSVI */ protected static final String SCHEMA_AUGMENT_PSVI = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI; /** Feature identifier: whether to recognize java encoding names */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: standard uri conformant feature. */ protected static final String STANDARD_URI_CONFORMANT_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE; /** Feature: generate synthetic annotations */ protected static final String GENERATE_SYNTHETIC_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE; /** Feature identifier: validate annotations. */ protected static final String VALIDATE_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.VALIDATE_ANNOTATIONS_FEATURE; /** Feature identifier: honour all schemaLocations */ protected static final String HONOUR_ALL_SCHEMALOCATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.HONOUR_ALL_SCHEMALOCATIONS_FEATURE; /** Feature identifier: use grammar pool only */ protected static final String USE_GRAMMAR_POOL_ONLY = Constants.XERCES_FEATURE_PREFIX + Constants.USE_GRAMMAR_POOL_ONLY_FEATURE; /** Feature identifier: whether to continue parsing a schema after a fatal error is encountered */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; protected static final String PARSER_SETTINGS = Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; /** Feature identifier: namespace growth */ protected static final String NAMESPACE_GROWTH = Constants.XERCES_FEATURE_PREFIX + Constants.NAMESPACE_GROWTH_FEATURE; /** Feature identifier: tolerate duplicates */ protected static final String TOLERATE_DUPLICATES = Constants.XERCES_FEATURE_PREFIX + Constants.TOLERATE_DUPLICATES_FEATURE; /** Feature identifier: whether to ignore xsi:type attributes until a global element declaration is encountered */ protected static final String IGNORE_XSI_TYPE = Constants.XERCES_FEATURE_PREFIX + Constants.IGNORE_XSI_TYPE_FEATURE; /** Feature identifier: whether to ignore ID/IDREF errors */ protected static final String ID_IDREF_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.ID_IDREF_CHECKING_FEATURE; /** Feature identifier: whether to ignore unparsed entity errors */ protected static final String UNPARSED_ENTITY_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.UNPARSED_ENTITY_CHECKING_FEATURE; /** Feature identifier: whether to ignore identity constraint errors */ protected static final String IDENTITY_CONSTRAINT_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.IDC_CHECKING_FEATURE; // property identifiers /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ public static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: grammar pool. */ public static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; protected static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; /** Property identifier: JAXP schema language. */ protected static final String JAXP_SCHEMA_LANGUAGE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE; /** Property identifier: root type definition. */ protected static final String ROOT_TYPE_DEF = Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_TYPE_DEFINITION_PROPERTY; /** Property identifier: root element declaration. */ protected static final String ROOT_ELEMENT_DECL = Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_ELEMENT_DECLARATION_PROPERTY; /** Property identifier: Schema DV Factory */ protected static final String SCHEMA_DV_FACTORY = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY; // recognized features and properties /** Recognized features. */ private static final String[] RECOGNIZED_FEATURES = { VALIDATION, SCHEMA_VALIDATION, DYNAMIC_VALIDATION, SCHEMA_FULL_CHECKING, ALLOW_JAVA_ENCODINGS, CONTINUE_AFTER_FATAL_ERROR, STANDARD_URI_CONFORMANT_FEATURE, GENERATE_SYNTHETIC_ANNOTATIONS, VALIDATE_ANNOTATIONS, HONOUR_ALL_SCHEMALOCATIONS, USE_GRAMMAR_POOL_ONLY, IGNORE_XSI_TYPE, ID_IDREF_CHECKING, IDENTITY_CONSTRAINT_CHECKING, UNPARSED_ENTITY_CHECKING, NAMESPACE_GROWTH, TOLERATE_DUPLICATES }; /** Feature defaults. */ private static final Boolean[] FEATURE_DEFAULTS = { null, // NOTE: The following defaults are nulled out on purpose. // If they are set, then when the XML Schema validator // is constructed dynamically, these values may override // those set by the application. This goes against the // whole purpose of XMLComponent#getFeatureDefault but // it can't be helped in this case. -Ac // NOTE: Instead of adding default values here, add them (and // the corresponding recognized features) to the objects // that have an XMLSchemaValidator instance as a member, // such as the parser configurations. -PM null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, null, null, null, null, null, null, null, null, null, null }; /** Recognized properties. */ private static final String[] RECOGNIZED_PROPERTIES = { SYMBOL_TABLE, ERROR_REPORTER, ENTITY_RESOLVER, VALIDATION_MANAGER, SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, JAXP_SCHEMA_SOURCE, JAXP_SCHEMA_LANGUAGE, ROOT_TYPE_DEF, ROOT_ELEMENT_DECL, SCHEMA_DV_FACTORY, }; /** Property defaults. */ private static final Object[] PROPERTY_DEFAULTS = { null, null, null, null, null, null, null, null, null, null, null}; // this is the number of valuestores of each kind // we expect an element to have. It's almost // never > 1; so leave it at that. protected static final int ID_CONSTRAINT_NUM = 1; // xsi:* attribute declarations static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); // private static final Hashtable EMPTY_TABLE = new Hashtable(); // // Data // /** current PSVI element info */ protected ElementPSVImpl fCurrentPSVI = new ElementPSVImpl(); // since it is the responsibility of each component to an // Augmentations parameter if one is null, to save ourselves from // having to create this object continually, it is created here. // If it is not present in calls that we're passing on, we *must* // clear this before we introduce it into the pipeline. protected final AugmentationsImpl fAugmentations = new AugmentationsImpl(); // this is included for the convenience of handleEndElement protected XMLString fDefaultValue; // Validation features protected boolean fDynamicValidation = false; protected boolean fSchemaDynamicValidation = false; protected boolean fDoValidation = false; protected boolean fFullChecking = false; protected boolean fNormalizeData = true; protected boolean fSchemaElementDefault = true; protected boolean fAugPSVI = true; protected boolean fIdConstraint = false; protected boolean fUseGrammarPoolOnly = false; // Namespace growth feature protected boolean fNamespaceGrowth = false; /** Schema type: None, DTD, Schema */ private String fSchemaType = null; // to indicate whether we are in the scope of entity reference or CData protected boolean fEntityRef = false; protected boolean fInCDATA = false; // properties /** Symbol table. */ protected SymbolTable fSymbolTable; /** * While parsing a document, keep the location of the document. */ private XMLLocator fLocator; /** * A wrapper of the standard error reporter. We'll store all schema errors * in this wrapper object, so that we can get all errors (error codes) of * a specific element. This is useful for PSVI. */ protected final class XSIErrorReporter { // the error reporter property XMLErrorReporter fErrorReporter; // store error codes; starting position of the errors for each element; // number of element (depth); and whether to record error Vector fErrors = new Vector(); int[] fContext = new int[INITIAL_STACK_SIZE]; int fContextCount; // set the external error reporter, clear errors public void reset(XMLErrorReporter errorReporter) { fErrorReporter = errorReporter; fErrors.removeAllElements(); fContextCount = 0; } // should be called when starting process an element or an attribute. // store the starting position for the current context public void pushContext() { if (!fAugPSVI) { return; } // resize array if necessary if (fContextCount == fContext.length) { int newSize = fContextCount + INC_STACK_SIZE; int[] newArray = new int[newSize]; System.arraycopy(fContext, 0, newArray, 0, fContextCount); fContext = newArray; } fContext[fContextCount++] = fErrors.size(); } // should be called on endElement: get all errors of the current element public String[] popContext() { if (!fAugPSVI) { return null; } // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String) fErrors.elementAt(contextPos + i); } // remove errors of the current element fErrors.setSize(contextPos); return errors; } // should be called when an attribute is done: get all errors of // this attribute, but leave the errors to the containing element // also called after an element was strictly assessed. public String[] mergeContext() { if (!fAugPSVI) { return null; } // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String) fErrors.elementAt(contextPos + i); } // don't resize the vector: leave the errors for this attribute // to the containing element return errors; } public void reportError(String domain, String key, Object[] arguments, short severity) throws XNIException { String message = fErrorReporter.reportError(domain, key, arguments, severity); if (fAugPSVI) { fErrors.addElement(key); fErrors.addElement(message); } } // reportError(String,String,Object[],short) public void reportError( XMLLocator location, String domain, String key, Object[] arguments, short severity) throws XNIException { String message = fErrorReporter.reportError(location, domain, key, arguments, severity); if (fAugPSVI) { fErrors.addElement(key); fErrors.addElement(message); } } // reportError(XMLLocator,String,String,Object[],short) } /** Error reporter. */ protected final XSIErrorReporter fXSIErrorReporter = new XSIErrorReporter(); /** Entity resolver */ protected XMLEntityResolver fEntityResolver; // updated during reset protected ValidationManager fValidationManager = null; protected ConfigurableValidationState fValidationState = new ConfigurableValidationState(); protected XMLGrammarPool fGrammarPool; // schema location property values protected String fExternalSchemas = null; protected String fExternalNoNamespaceSchema = null; //JAXP Schema Source property protected Object fJaxpSchemaSource = null; /** Schema Grammar Description passed, to give a chance to application to supply the Grammar */ protected final XSDDescription fXSDDescription = new XSDDescription(); protected final Hashtable fLocationPairs = new Hashtable(); protected final Hashtable fExpandedLocationPairs = new Hashtable(); protected final ArrayList fUnparsedLocations = new ArrayList(); // handlers /** Document handler. */ protected XMLDocumentHandler fDocumentHandler; protected XMLDocumentSource fDocumentSource; // // XMLComponent methods // /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return (String[]) (RECOGNIZED_FEATURES.clone()); } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return (String[]) (RECOGNIZED_PROPERTIES.clone()); } // getRecognizedProperties():String[] /** * Sets the value of a property. This method is called by the component * manager any time after reset when a property changes value. * <p> * <strong>Note:</strong> Components should silently ignore properties * that do not affect the operation of the component. * * @param propertyId The property identifier. * @param value The value of the property. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { if (propertyId.equals(ROOT_TYPE_DEF)) { if (value == null) { fRootTypeQName = null; fRootTypeDefinition = null; } else if (value instanceof javax.xml.namespace.QName) { fRootTypeQName = (javax.xml.namespace.QName) value; fRootTypeDefinition = null; } else { fRootTypeDefinition = (XSTypeDefinition) value; fRootTypeQName = null; } } else if (propertyId.equals(ROOT_ELEMENT_DECL)) { if (value == null) { fRootElementDeclQName = null; fRootElementDeclaration = null; } else if (value instanceof javax.xml.namespace.QName) { fRootElementDeclQName = (javax.xml.namespace.QName) value; fRootElementDeclaration = null; } else { fRootElementDeclaration = (XSElementDecl) value; fRootElementDeclQName = null; } } } // setProperty(String,Object) /** * Returns the default state for a feature, or null if this * component does not want to report a default value for this * feature. * * @param featureId The feature identifier. * * @since Xerces 2.2.0 */ public Boolean getFeatureDefault(String featureId) { for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) { if (RECOGNIZED_FEATURES[i].equals(featureId)) { return FEATURE_DEFAULTS[i]; } } return null; } // getFeatureDefault(String):Boolean /** * Returns the default state for a property, or null if this * component does not want to report a default value for this * property. * * @param propertyId The property identifier. * * @since Xerces 2.2.0 */ public Object getPropertyDefault(String propertyId) { for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) { if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) { return PROPERTY_DEFAULTS[i]; } } return null; } // getPropertyDefault(String):Object // // XMLDocumentSource methods // /** Sets the document handler to receive information about the document. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; } // setDocumentHandler(XMLDocumentHandler) /** Returns the document handler */ public XMLDocumentHandler getDocumentHandler() { return fDocumentHandler; } // setDocumentHandler(XMLDocumentHandler) // // XMLDocumentHandler methods // /** Sets the document source */ public void setDocumentSource(XMLDocumentSource source) { fDocumentSource = source; } // setDocumentSource /** Returns the document source */ public XMLDocumentSource getDocumentSource() { return fDocumentSource; } // getDocumentSource /** * The start of the document. * * @param locator The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param namespaceContext * The namespace context in effect at the * start of this document. * This object represents the current context. * Implementors of this class are responsible * for copying the namespace bindings from the * the current context (and its parent contexts) * if that information is important. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument( XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { fValidationState.setNamespaceSupport(namespaceContext); fState4XsiType.setNamespaceSupport(namespaceContext); fState4ApplyDefault.setNamespaceSupport(namespaceContext); fLocator = locator; handleStartDocument(locator, encoding); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startDocument(locator, encoding, namespaceContext, augs); } } // startDocument(XMLLocator,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.xmlDecl(version, encoding, standalone, augs); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl( String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs); } } // doctypeDecl(String,String,String) /** * The start of an element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startElement(element, attributes, modifiedAugs); } } // startElement(QName,XMLAttributes, Augmentations) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // in the case where there is a {value constraint}, and the element // doesn't have any text content, change emptyElement call to // start + characters + end fDefaultValue = null; // fElementDepth == -2 indicates that the schema validator was removed // from the pipeline. then we don't need to call handleEndElement. if (fElementDepth != -2) modifiedAugs = handleEndElement(element, modifiedAugs); // call handlers if (fDocumentHandler != null) { if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.emptyElement(element, attributes, modifiedAugs); } else { fDocumentHandler.startElement(element, attributes, modifiedAugs); fDocumentHandler.characters(fDefaultValue, null); fDocumentHandler.endElement(element, modifiedAugs); } } } // emptyElement(QName,XMLAttributes, Augmentations) /** * Character content. * * @param text The content. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text, Augmentations augs) throws XNIException { text = handleCharacters(text); // call handlers if (fDocumentHandler != null) { if (fNormalizeData && fUnionType) { // for union types we can't normalize data // thus we only need to send augs information if any; // the normalized data for union will be send // after normalization is performed (at the endElement()) if (augs != null) fDocumentHandler.characters(fEmptyXMLStr, augs); } else { fDocumentHandler.characters(text, augs); } } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { handleIgnorableWhitespace(text); // call handlers if (fDocumentHandler != null) { fDocumentHandler.ignorableWhitespace(text, augs); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element, Augmentations augs) throws XNIException { // in the case where there is a {value constraint}, and the element // doesn't have any text content, add a characters call. fDefaultValue = null; Augmentations modifiedAugs = handleEndElement(element, augs); // call handlers if (fDocumentHandler != null) { if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.endElement(element, modifiedAugs); } else { fDocumentHandler.characters(fDefaultValue, null); fDocumentHandler.endElement(element, modifiedAugs); } } } // endElement(QName, Augmentations) /** * The start of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA(Augmentations augs) throws XNIException { // REVISIT: what should we do here if schema normalization is on?? fInCDATA = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startCDATA(augs); } } // startCDATA() /** * The end of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA(Augmentations augs) throws XNIException { // call handlers fInCDATA = false; if (fDocumentHandler != null) { fDocumentHandler.endCDATA(augs); } } // endCDATA() /** * The end of the document. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument(Augmentations augs) throws XNIException { handleEndDocument(); // call handlers if (fDocumentHandler != null) { fDocumentHandler.endDocument(augs); } fLocator = null; } // endDocument(Augmentations) // // DOMRevalidationHandler methods // public boolean characterData(String data, Augmentations augs) { fSawText = fSawText || data.length() > 0; // REVISIT: this methods basically duplicates implementation of // handleCharacters(). We should be able to reuse some code // if whitespace == -1 skip normalization, because it is a complexType // or a union type. if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data normalizeWhitespace(data, fWhiteSpace == XSSimpleType.WS_COLLAPSE); fBuffer.append(fNormalizedStr.ch, fNormalizedStr.offset, fNormalizedStr.length); } else { if (fAppendBuffer) fBuffer.append(data); } // When it's a complex type with element-only content, we need to // find out whether the content contains any non-whitespace character. boolean allWhiteSpace = true; if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { // data outside of element content for (int i = 0; i < data.length(); i++) { if (!XMLChar.isSpace(data.charAt(i))) { allWhiteSpace = false; fSawCharacters = true; break; } } } } return allWhiteSpace; } public void elementDefault(String data) { // no-op } // // XMLDocumentHandler and XMLDTDHandler methods // /** * This method notifies the start of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the general entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @exception XNIException Thrown by handler to signal an error. */ public void startGeneralEntity( String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { // REVISIT: what should happen if normalize_data_ is on?? fEntityRef = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startGeneralEntity(name, identifier, encoding, augs); } } // startEntity(String,String,String,String,String) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.textDecl(version, encoding, augs); } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.comment(text, augs); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.processingInstruction(target, data, augs); } } // processingInstruction(String,XMLString) /** * This method notifies the end of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param augs Additional information that may include infoset augmentations * * @exception XNIException * Thrown by handler to signal an error. */ public void endGeneralEntity(String name, Augmentations augs) throws XNIException { // call handlers fEntityRef = false; if (fDocumentHandler != null) { fDocumentHandler.endGeneralEntity(name, augs); } } // endEntity(String) // constants static final int INITIAL_STACK_SIZE = 8; static final int INC_STACK_SIZE = 8; // // Data // // Schema Normalization private static final boolean DEBUG_NORMALIZATION = false; // temporary empty string buffer. private final XMLString fEmptyXMLStr = new XMLString(null, 0, -1); // temporary character buffer, and empty string buffer. private static final int BUFFER_SIZE = 20; private final XMLString fNormalizedStr = new XMLString(); private boolean fFirstChunk = true; // got first chunk in characters() (SAX) private boolean fTrailing = false; // Previous chunk had a trailing space private short fWhiteSpace = -1; //whiteSpace: preserve/replace/collapse private boolean fUnionType = false; /** Schema grammar resolver. */ private final XSGrammarBucket fGrammarBucket = new XSGrammarBucket(); private final SubstitutionGroupHandler fSubGroupHandler = new SubstitutionGroupHandler(this); /** the DV usd to convert xsi:type to a QName */ // REVISIT: in new simple type design, make things in DVs static, // so that we can QNameDV.getCompiledForm() private final XSSimpleType fQNameDV = (XSSimpleType) SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME); private final CMNodeFactory nodeFactory = new CMNodeFactory(); /** used to build content models */ // REVISIT: create decl pool, and pass it to each traversers private final CMBuilder fCMBuilder = new CMBuilder(nodeFactory); // Schema grammar loader private final XMLSchemaLoader fSchemaLoader = new XMLSchemaLoader( fXSIErrorReporter.fErrorReporter, fGrammarBucket, fSubGroupHandler, fCMBuilder); // state /** String representation of the validation root. */ // REVISIT: what do we store here? QName, XPATH, some ID? use rawname now. private String fValidationRoot; /** Skip validation: anything below this level should be skipped */ private int fSkipValidationDepth; /** anything above this level has validation_attempted != full */ private int fNFullValidationDepth; /** anything above this level has validation_attempted != none */ private int fNNoneValidationDepth; /** Element depth: -2: validator not in pipeline; >= -1 current depth. */ private int fElementDepth; /** Seen sub elements. */ private boolean fSubElement; /** Seen sub elements stack. */ private boolean[] fSubElementStack = new boolean[INITIAL_STACK_SIZE]; /** Current element declaration. */ private XSElementDecl fCurrentElemDecl; /** Element decl stack. */ private XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE]; /** nil value of the current element */ private boolean fNil; /** nil value stack */ private boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE]; /** notation value of the current element */ private XSNotationDecl fNotation; /** notation stack */ private XSNotationDecl[] fNotationStack = new XSNotationDecl[INITIAL_STACK_SIZE]; /** Current type. */ private XSTypeDefinition fCurrentType; /** type stack. */ private XSTypeDefinition[] fTypeStack = new XSTypeDefinition[INITIAL_STACK_SIZE]; /** Current content model. */ private XSCMValidator fCurrentCM; /** Content model stack. */ private XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE]; /** the current state of the current content model */ private int[] fCurrCMState; /** stack to hold content model states */ private int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][]; /** whether the curret element is strictly assessed */ private boolean fStrictAssess = true; /** strict assess stack */ private boolean[] fStrictAssessStack = new boolean[INITIAL_STACK_SIZE]; /** Temporary string buffers. */ private final StringBuffer fBuffer = new StringBuffer(); /** Whether need to append characters to fBuffer */ private boolean fAppendBuffer = true; /** Did we see any character data? */ private boolean fSawText = false; /** stack to record if we saw character data */ private boolean[] fSawTextStack = new boolean[INITIAL_STACK_SIZE]; /** Did we see non-whitespace character data? */ private boolean fSawCharacters = false; /** Stack to record if we saw character data outside of element content*/ private boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE]; /** temporary qname */ private final QName fTempQName = new QName(); /** value of the "root-type-definition" property. */ private javax.xml.namespace.QName fRootTypeQName = null; private XSTypeDefinition fRootTypeDefinition = null; /** value of the "root-element-declaration" property. */ private javax.xml.namespace.QName fRootElementDeclQName = null; private XSElementDecl fRootElementDeclaration = null; private int fIgnoreXSITypeDepth; private boolean fIDCChecking; /** temporary validated info */ private ValidatedInfo fValidatedInfo = new ValidatedInfo(); // used to validate default/fixed values against xsi:type // only need to check facets, so we set extraChecking to false (in reset) private ValidationState fState4XsiType = new ValidationState(); // used to apply default/fixed values // only need to check id/idref/entity, so we set checkFacets to false private ValidationState fState4ApplyDefault = new ValidationState(); // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // // Constructors // /** Default constructor. */ public XMLSchemaValidator() { fState4XsiType.setExtraChecking(false); fState4ApplyDefault.setFacetChecking(false); } // <init>() /* * Resets the component. The component can query the component manager * about any features and properties that affect the operation of the * component. * * @param componentManager The component manager. * * @throws SAXException Thrown by component on finitialization error. * For example, if a feature or property is * required for the operation of the component, the * component manager may throw a * SAXNotRecognizedException or a * SAXNotSupportedException. */ public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { fIdConstraint = false; //reset XSDDescription fLocationPairs.clear(); fExpandedLocationPairs.clear(); // cleanup id table fValidationState.resetIDTables(); // reset schema loader fSchemaLoader.reset(componentManager); // initialize state fCurrentElemDecl = null; fCurrentCM = null; fCurrCMState = null; fSkipValidationDepth = -1; fNFullValidationDepth = -1; fNNoneValidationDepth = -1; fElementDepth = -1; fSubElement = false; fSchemaDynamicValidation = false; // datatype normalization fEntityRef = false; fInCDATA = false; fMatcherStack.clear(); // get error reporter fXSIErrorReporter.reset((XMLErrorReporter) componentManager.getProperty(ERROR_REPORTER)); boolean parser_settings; try { parser_settings = componentManager.getFeature(PARSER_SETTINGS); } catch (XMLConfigurationException e){ parser_settings = true; } if (!parser_settings) { // parser settings have not been changed fValidationManager.addValidationState(fValidationState); // the node limit on the SecurityManager may have changed so need to refresh. nodeFactory.reset(); // Re-parse external schema location properties. XMLSchemaLoader.processExternalHints( fExternalSchemas, fExternalNoNamespaceSchema, fLocationPairs, fXSIErrorReporter.fErrorReporter); return; } // pass the component manager to the factory.. nodeFactory.reset(componentManager); // get symbol table. if it's a new one, add symbols to it. SymbolTable symbolTable = (SymbolTable) componentManager.getProperty(SYMBOL_TABLE); if (symbolTable != fSymbolTable) { fSymbolTable = symbolTable; } try { fNamespaceGrowth = componentManager.getFeature(NAMESPACE_GROWTH); } catch (XMLConfigurationException e) { fNamespaceGrowth = false; } try { fDynamicValidation = componentManager.getFeature(DYNAMIC_VALIDATION); } catch (XMLConfigurationException e) { fDynamicValidation = false; } if (fDynamicValidation) { fDoValidation = true; } else { try { fDoValidation = componentManager.getFeature(VALIDATION); } catch (XMLConfigurationException e) { fDoValidation = false; } } if (fDoValidation) { try { fDoValidation = componentManager.getFeature(XMLSchemaValidator.SCHEMA_VALIDATION); } catch (XMLConfigurationException e) { } } try { fFullChecking = componentManager.getFeature(SCHEMA_FULL_CHECKING); } catch (XMLConfigurationException e) { fFullChecking = false; } try { fNormalizeData = componentManager.getFeature(NORMALIZE_DATA); } catch (XMLConfigurationException e) { fNormalizeData = false; } try { fSchemaElementDefault = componentManager.getFeature(SCHEMA_ELEMENT_DEFAULT); } catch (XMLConfigurationException e) { fSchemaElementDefault = false; } try { fAugPSVI = componentManager.getFeature(SCHEMA_AUGMENT_PSVI); } catch (XMLConfigurationException e) { fAugPSVI = true; } try { fSchemaType = (String) componentManager.getProperty( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE); } catch (XMLConfigurationException e) { fSchemaType = null; } try { fUseGrammarPoolOnly = componentManager.getFeature(USE_GRAMMAR_POOL_ONLY); } catch (XMLConfigurationException e) { fUseGrammarPoolOnly = false; } fEntityResolver = (XMLEntityResolver) componentManager.getProperty(ENTITY_MANAGER); fValidationManager = (ValidationManager) componentManager.getProperty(VALIDATION_MANAGER); fValidationManager.addValidationState(fValidationState); fValidationState.setSymbolTable(fSymbolTable); try { final Object rootType = componentManager.getProperty(ROOT_TYPE_DEF); if (rootType == null) { fRootTypeQName = null; fRootTypeDefinition = null; } else if (rootType instanceof javax.xml.namespace.QName) { fRootTypeQName = (javax.xml.namespace.QName) rootType; fRootTypeDefinition = null; } else { fRootTypeDefinition = (XSTypeDefinition) rootType; fRootTypeQName = null; } } catch (XMLConfigurationException e) { fRootTypeQName = null; fRootTypeDefinition = null; } try { final Object rootDecl = componentManager.getProperty(ROOT_ELEMENT_DECL); if (rootDecl == null) { fRootElementDeclQName = null; fRootElementDeclaration = null; } else if (rootDecl instanceof javax.xml.namespace.QName) { fRootElementDeclQName = (javax.xml.namespace.QName) rootDecl; fRootElementDeclaration = null; } else { fRootElementDeclaration = (XSElementDecl) rootDecl; fRootElementDeclQName = null; } } catch (XMLConfigurationException e) { fRootElementDeclQName = null; fRootElementDeclaration = null; } boolean ignoreXSIType; try { ignoreXSIType = componentManager.getFeature(IGNORE_XSI_TYPE); } catch (XMLConfigurationException e) { ignoreXSIType = false; } // An initial value of -1 means that the root element considers itself // below the depth where xsi:type stopped being ignored (which means that // xsi:type attributes will not be ignored for the entire document) fIgnoreXSITypeDepth = ignoreXSIType ? 0 : -1; try { fIDCChecking = componentManager.getFeature(IDENTITY_CONSTRAINT_CHECKING); } catch (XMLConfigurationException e) { fIDCChecking = true; } try { fValidationState.setIdIdrefChecking(componentManager.getFeature(ID_IDREF_CHECKING)); } catch (XMLConfigurationException e) { fValidationState.setIdIdrefChecking(true); } try { fValidationState.setUnparsedEntityChecking(componentManager.getFeature(UNPARSED_ENTITY_CHECKING)); } catch (XMLConfigurationException e) { fValidationState.setUnparsedEntityChecking(true); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNamespaceSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNamespaceSchema = null; } // store the external schema locations. they are set when reset is called, // so any other schemaLocation declaration for the same namespace will be // effectively ignored. becuase we choose to take first location hint // available for a particular namespace. XMLSchemaLoader.processExternalHints( fExternalSchemas, fExternalNoNamespaceSchema, fLocationPairs, fXSIErrorReporter.fErrorReporter); try { fJaxpSchemaSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE); } catch (XMLConfigurationException e) { fJaxpSchemaSource = null; } // clear grammars, and put the one for schema namespace there try { fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL); } catch (XMLConfigurationException e) { fGrammarPool = null; } fState4XsiType.setSymbolTable(symbolTable); fState4ApplyDefault.setSymbolTable(symbolTable); } // reset(XMLComponentManager) // // FieldActivator methods // /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.startValueScope(); } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field, int initialDepth) { ValueStore valueStore = fValueStoreCache.getValueStoreFor(field.getIdentityConstraint(), initialDepth); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // a utility method for Identity constraints private void activateSelectorFor(IdentityConstraint ic) { Selector selector = ic.getSelector(); FieldActivator activator = this; if (selector == null) return; XPathMatcher matcher = selector.createMatcher(activator, fElementDepth); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(); } // Implements XSElementDeclHelper interface public XSElementDecl getGlobalElementDecl(QName element) { final SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, null); if (sGrammar != null) { return sGrammar.getGlobalElementDecl(element.localpart); } return null; } // // Protected methods // /** ensure element stack capacity */ void ensureStackCapacity() { if (fElementDepth == fElemDeclStack.length) { int newSize = fElementDepth + INC_STACK_SIZE; boolean[] newArrayB = new boolean[newSize]; System.arraycopy(fSubElementStack, 0, newArrayB, 0, fElementDepth); fSubElementStack = newArrayB; XSElementDecl[] newArrayE = new XSElementDecl[newSize]; System.arraycopy(fElemDeclStack, 0, newArrayE, 0, fElementDepth); fElemDeclStack = newArrayE; newArrayB = new boolean[newSize]; System.arraycopy(fNilStack, 0, newArrayB, 0, fElementDepth); fNilStack = newArrayB; XSNotationDecl[] newArrayN = new XSNotationDecl[newSize]; System.arraycopy(fNotationStack, 0, newArrayN, 0, fElementDepth); fNotationStack = newArrayN; XSTypeDefinition[] newArrayT = new XSTypeDefinition[newSize]; System.arraycopy(fTypeStack, 0, newArrayT, 0, fElementDepth); fTypeStack = newArrayT; XSCMValidator[] newArrayC = new XSCMValidator[newSize]; System.arraycopy(fCMStack, 0, newArrayC, 0, fElementDepth); fCMStack = newArrayC; newArrayB = new boolean[newSize]; System.arraycopy(fSawTextStack, 0, newArrayB, 0, fElementDepth); fSawTextStack = newArrayB; newArrayB = new boolean[newSize]; System.arraycopy(fStringContent, 0, newArrayB, 0, fElementDepth); fStringContent = newArrayB; newArrayB = new boolean[newSize]; System.arraycopy(fStrictAssessStack, 0, newArrayB, 0, fElementDepth); fStrictAssessStack = newArrayB; int[][] newArrayIA = new int[newSize][]; System.arraycopy(fCMStateStack, 0, newArrayIA, 0, fElementDepth); fCMStateStack = newArrayIA; } } // ensureStackCapacity // handle start document void handleStartDocument(XMLLocator locator, String encoding) { if (fIDCChecking) { fValueStoreCache.startDocument(); } if (fAugPSVI) { fCurrentPSVI.fGrammars = null; fCurrentPSVI.fSchemaInformation = null; } } // handleStartDocument(XMLLocator,String) void handleEndDocument() { if (fIDCChecking) { fValueStoreCache.endDocument(); } } // handleEndDocument() // handle character contents // returns the normalized string if possible, otherwise the original string XMLString handleCharacters(XMLString text) { if (fSkipValidationDepth >= 0) return text; fSawText = fSawText || text.length > 0; // Note: data in EntityRef and CDATA is normalized as well // if whitespace == -1 skip normalization, because it is a complexType // or a union type. if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data normalizeWhitespace(text, fWhiteSpace == XSSimpleType.WS_COLLAPSE); text = fNormalizedStr; } if (fAppendBuffer) fBuffer.append(text.ch, text.offset, text.length); // When it's a complex type with element-only content, we need to // find out whether the content contains any non-whitespace character. if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { // data outside of element content for (int i = text.offset; i < text.offset + text.length; i++) { if (!XMLChar.isSpace(text.ch[i])) { fSawCharacters = true; break; } } } } return text; } // handleCharacters(XMLString) /** * Normalize whitespace in an XMLString according to the rules defined * in XML Schema specifications. * @param value The string to normalize. * @param collapse replace or collapse */ private void normalizeWhitespace(XMLString value, boolean collapse) { boolean skipSpace = collapse; boolean sawNonWS = false; boolean leading = false; boolean trailing = false; char c; int size = value.offset + value.length; // ensure the ch array is big enough if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < value.length + 1) { fNormalizedStr.ch = new char[value.length + 1]; } // don't include the leading ' ' for now. might include it later. fNormalizedStr.offset = 1; fNormalizedStr.length = 1; for (int i = value.offset; i < size; i++) { c = value.ch[i]; if (XMLChar.isSpace(c)) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.ch[fNormalizedStr.length++] = ' '; skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = true; } } else { fNormalizedStr.ch[fNormalizedStr.length++] = c; skipSpace = false; sawNonWS = true; } } if (skipSpace) { if (fNormalizedStr.length > 1) { // if we finished on a space trim it but also record it fNormalizedStr.length--; trailing = true; } else if (leading && !fFirstChunk) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = true; } } if (fNormalizedStr.length > 1) { if (!fFirstChunk && (fWhiteSpace == XSSimpleType.WS_COLLAPSE)) { if (fTrailing) { // previous chunk ended on whitespace // insert whitespace fNormalizedStr.offset = 0; fNormalizedStr.ch[0] = ' '; } else if (leading) { // previous chunk ended on character, // this chunk starts with whitespace fNormalizedStr.offset = 0; fNormalizedStr.ch[0] = ' '; } } } // The length includes the leading ' '. Now removing it. fNormalizedStr.length -= fNormalizedStr.offset; fTrailing = trailing; if (trailing || sawNonWS) fFirstChunk = false; } private void normalizeWhitespace(String value, boolean collapse) { boolean skipSpace = collapse; char c; int size = value.length(); // ensure the ch array is big enough if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < size) { fNormalizedStr.ch = new char[size]; } fNormalizedStr.offset = 0; fNormalizedStr.length = 0; for (int i = 0; i < size; i++) { c = value.charAt(i); if (XMLChar.isSpace(c)) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.ch[fNormalizedStr.length++] = ' '; skipSpace = collapse; } } else { fNormalizedStr.ch[fNormalizedStr.length++] = c; skipSpace = false; } } if (skipSpace) { if (fNormalizedStr.length != 0) // if we finished on a space trim it but also record it fNormalizedStr.length--; } } // handle ignorable whitespace void handleIgnorableWhitespace(XMLString text) { if (fSkipValidationDepth >= 0) return; // REVISIT: the same process needs to be performed as handleCharacters. // only it's simpler here: we know all characters are whitespaces. } // handleIgnorableWhitespace(XMLString) /** Handle element. */ Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); + String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { - reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); + reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { - reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); + reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.fAnyType; fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.fAnyType; else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } return augs; } // handleStartElement(QName,XMLAttributes,boolean) /** * Handle end element. If there is not text content, and there is a * {value constraint} on the corresponding element decl, then * set the fDefaultValue XMLString representing the default value. */ Augmentations handleEndElement(QName element, Augmentations augs) { if (DEBUG) { System.out.println("==>handleEndElement:" + element); } // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { // set the partial validation depth to the depth of parent fNFullValidationDepth = fSkipValidationDepth - 1; fSkipValidationDepth = -1; fElementDepth--; fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; } else { fElementDepth--; } // PSVI: validation attempted: // use default values in psvi item for // validation attempted, validity, and error codes // check extra schema constraints on root element if (fElementDepth == -1 && fFullChecking && !fUseGrammarPoolOnly) { XSConstraints.fullSchemaChecking( fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // now validate the content of the element processElementContent(element); if (fIDCChecking) { // Element Locally Valid (Element) // 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (fCurrentElemDecl == null) { matcher.endElement(element, fCurrentType, false, fValidatedInfo.actualValue, fValidatedInfo.actualValueType, fValidatedInfo.itemValueTypes); } else { matcher.endElement( element, fCurrentType, fCurrentElemDecl.getNillable(), fDefaultValue == null ? fValidatedInfo.actualValue : fCurrentElemDecl.fDefault.actualValue, fDefaultValue == null ? fValidatedInfo.actualValueType : fCurrentElemDecl.fDefault.actualValueType, fDefaultValue == null ? fValidatedInfo.itemValueTypes : fCurrentElemDecl.fDefault.itemValueTypes); } } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher) matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) { fValueStoreCache.transplant(id, selMatcher.getInitialDepth()); } } } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher) matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth()); if (values != null) // nothing to do if nothing matched! values.endDocumentFragment(); } } } fValueStoreCache.endElement(); } // Check if we should modify the xsi:type ignore depth // This check is independent of whether this is the validation root, // and should be done before the element depth is decremented. if (fElementDepth < fIgnoreXSITypeDepth) { fIgnoreXSITypeDepth--; } SchemaGrammar[] grammars = null; // have we reached the end tag of the validation root? if (fElementDepth == 0) { // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4). String invIdRef = fValidationState.checkIDRefID(); fValidationState.resetIDTables(); if (invIdRef != null) { reportSchemaError("cvc-id.1", new Object[] { invIdRef }); } // check extra schema constraints if (fFullChecking && !fUseGrammarPoolOnly) { XSConstraints.fullSchemaChecking( fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } grammars = fGrammarBucket.getGrammars(); // return the final set of grammars validator ended up with if (fGrammarPool != null) { // Set grammars as immutable for (int k=0; k < grammars.length; k++) { grammars[k].setImmutable(true); } fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars); } augs = endElementPSVI(true, grammars, augs); } else { augs = endElementPSVI(false, grammars, augs); // decrease element depth and restore states fElementDepth--; // get the states for the parent element. fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; // We should have a stack for whitespace value, and pop it up here. // But when fWhiteSpace != -1, and we see a sub-element, it must be // an error (at least for Schema 1.0). So for valid documents, the // only value we are going to push/pop in the stack is -1. // Here we just mimic the effect of popping -1. -SG fWhiteSpace = -1; // Same for append buffer. Simple types and elements with fixed // value constraint don't allow sub-elements. -SG fAppendBuffer = false; // same here. fUnionType = false; } return augs; } // handleEndElement(QName,boolean)*/ final Augmentations endElementPSVI( boolean root, SchemaGrammar[] grammars, Augmentations augs) { if (fAugPSVI) { augs = getEmptyAugs(augs); // the 5 properties sent on startElement calls fCurrentPSVI.fDeclaration = this.fCurrentElemDecl; fCurrentPSVI.fTypeDecl = this.fCurrentType; fCurrentPSVI.fNotation = this.fNotation; fCurrentPSVI.fValidationContext = this.fValidationRoot; fCurrentPSVI.fNil = this.fNil; // PSVI: validation attempted // nothing below or at the same level has none or partial // (which means this level is strictly assessed, and all chidren // are full), so this one has full if (fElementDepth > fNFullValidationDepth) { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_FULL; } // nothing below or at the same level has full or partial // (which means this level is not strictly assessed, and all chidren // are none), so this one has none else if (fElementDepth > fNNoneValidationDepth) { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_NONE; } // otherwise partial, and anything above this level will be partial else { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_PARTIAL; } // this guarantees that depth settings do not cross-over between sibling nodes if (fNFullValidationDepth == fElementDepth) { fNFullValidationDepth = fElementDepth - 1; } if (fNNoneValidationDepth == fElementDepth) { fNNoneValidationDepth = fElementDepth - 1; } if (fDefaultValue != null) fCurrentPSVI.fSpecified = true; fCurrentPSVI.fValue.copyFrom(fValidatedInfo); if (fStrictAssess) { // get all errors for the current element, its attribute, // and subelements (if they were strictly assessed). // any error would make this element invalid. // and we merge these errors to the parent element. String[] errors = fXSIErrorReporter.mergeContext(); // PSVI: error codes fCurrentPSVI.fErrors = errors; // PSVI: validity fCurrentPSVI.fValidity = (errors == null) ? ElementPSVI.VALIDITY_VALID : ElementPSVI.VALIDITY_INVALID; } else { // PSVI: validity fCurrentPSVI.fValidity = ElementPSVI.VALIDITY_NOTKNOWN; // Discard the current context: ignore any error happened within // the sub-elements/attributes of this element, because those // errors won't affect the validity of the parent elements. fXSIErrorReporter.popContext(); } if (root) { // store [schema information] in the PSVI fCurrentPSVI.fGrammars = grammars; fCurrentPSVI.fSchemaInformation = null; } } return augs; } Augmentations getEmptyAugs(Augmentations augs) { if (augs == null) { augs = fAugmentations; augs.removeAllItems(); } augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); fCurrentPSVI.reset(); return augs; } void storeLocations(String sLocation, String nsLocation) { if (sLocation != null) { if (!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs, fLocator == null ? null : fLocator.getExpandedSystemId())) { // error! fXSIErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "SchemaLocation", new Object[] { sLocation }, XMLErrorReporter.SEVERITY_WARNING); } } if (nsLocation != null) { XMLSchemaLoader.LocationArray la = ((XMLSchemaLoader.LocationArray) fLocationPairs.get(XMLSymbols.EMPTY_STRING)); if (la == null) { la = new XMLSchemaLoader.LocationArray(); fLocationPairs.put(XMLSymbols.EMPTY_STRING, la); } if (fLocator != null) { try { nsLocation = XMLEntityManager.expandSystemId(nsLocation, fLocator.getExpandedSystemId(), false); } catch (MalformedURIException e) { } } la.addLocation(nsLocation); } } //storeLocations //this is the function where logic of retrieving grammar is written , parser first tries to get the grammar from //the local pool, if not in local pool, it gives chance to application to be able to retrieve the grammar, then it //tries to parse the grammar using location hints from the give namespace. SchemaGrammar findSchemaGrammar( short contextType, String namespace, QName enclosingElement, QName triggeringComponent, XMLAttributes attributes) { SchemaGrammar grammar = null; //get the grammar from local pool... grammar = fGrammarBucket.getGrammar(namespace); if (grammar == null) { fXSDDescription.setNamespace(namespace); if (fGrammarPool != null) { grammar = (SchemaGrammar) fGrammarPool.retrieveGrammar(fXSDDescription); if (grammar != null) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar(grammar, true, fNamespaceGrowth)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "GrammarConflict", null, XMLErrorReporter.SEVERITY_WARNING); grammar = null; } } } } if (!fUseGrammarPoolOnly && (grammar == null || (fNamespaceGrowth && !hasSchemaComponent(grammar, contextType, triggeringComponent)))) { fXSDDescription.reset(); fXSDDescription.fContextType = contextType; fXSDDescription.setNamespace(namespace); fXSDDescription.fEnclosedElementName = enclosingElement; fXSDDescription.fTriggeringComponent = triggeringComponent; fXSDDescription.fAttributes = attributes; if (fLocator != null) { fXSDDescription.setBaseSystemId(fLocator.getExpandedSystemId()); } Hashtable locationPairs = fLocationPairs; Object locationArray = locationPairs.get(namespace == null ? XMLSymbols.EMPTY_STRING : namespace); if (locationArray != null) { String[] temp = ((XMLSchemaLoader.LocationArray) locationArray).getLocationArray(); if (temp.length != 0) { setLocationHints(fXSDDescription, temp, grammar); } } if (grammar == null || fXSDDescription.fLocationHints != null) { boolean toParseSchema = true; if (grammar != null) { // use location hints instead locationPairs = EMPTY_TABLE; } // try to parse the grammar using location hints from that namespace.. try { XMLInputSource xis = XMLSchemaLoader.resolveDocument( fXSDDescription, locationPairs, fEntityResolver); if (grammar != null && fNamespaceGrowth) { try { // if we are dealing with a different schema location, then include the new schema // into the existing grammar if (grammar.getDocumentLocations().contains(XMLEntityManager.expandSystemId(xis.getSystemId(), xis.getBaseSystemId(), false))) { toParseSchema = false; } } catch (MalformedURIException e) { } } if (toParseSchema) { grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs); } } catch (IOException ex) { final String [] locationHints = fXSDDescription.getLocationHints(); fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "schema_reference.4", new Object[] { locationHints != null ? locationHints[0] : XMLSymbols.EMPTY_STRING }, XMLErrorReporter.SEVERITY_WARNING, ex); } } } return grammar; } //findSchemaGrammar private boolean hasSchemaComponent(SchemaGrammar grammar, short contextType, QName triggeringComponent) { if (grammar != null && triggeringComponent != null) { String localName = triggeringComponent.localpart; if (localName != null && localName.length() > 0) { switch (contextType) { case XSDDescription.CONTEXT_ELEMENT: return grammar.getElementDeclaration(localName) != null; case XSDDescription.CONTEXT_ATTRIBUTE: return grammar.getAttributeDeclaration(localName) != null; case XSDDescription.CONTEXT_XSITYPE: return grammar.getTypeDefinition(localName) != null; } } } return false; } private void setLocationHints(XSDDescription desc, String[] locations, SchemaGrammar grammar) { int length = locations.length; if (grammar == null) { fXSDDescription.fLocationHints = new String[length]; System.arraycopy(locations, 0, fXSDDescription.fLocationHints, 0, length); } else { setLocationHints(desc, locations, grammar.getDocumentLocations()); } } private void setLocationHints(XSDDescription desc, String[] locations, StringList docLocations) { int length = locations.length; String[] hints = new String[length]; int counter = 0; for (int i=0; i<length; i++) { if (!docLocations.contains(locations[i])) { hints[counter++] = locations[i]; } } if (counter > 0) { if (counter == length) { fXSDDescription.fLocationHints = hints; } else { fXSDDescription.fLocationHints = new String[counter]; System.arraycopy(hints, 0, fXSDDescription.fLocationHints, 0, counter); } } } XSTypeDefinition getAndCheckXsiType(QName element, String xsiType, XMLAttributes attributes) { // This method also deals with clause 1.2.1.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // Element Locally Valid (Element) // 4 If there is an attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is type, then all of the following must be true: // 4.1 The normalized value of that attribute information item must be valid with respect to the built-in QName simple type, as defined by String Valid (3.14.4); QName typeName = null; try { typeName = (QName) fQNameDV.validate(xsiType, fValidationState, null); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError( "cvc-elt.4.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_TYPE, xsiType }); return null; } // 4.2 The local name and namespace name (as defined in QName Interpretation (3.15.3)), of the actual value of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (3.15.4) XSTypeDefinition type = null; // if the namespace is schema namespace, first try built-in types if (typeName.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) { type = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(typeName.localpart); } // if it's not schema built-in types, then try to get a grammar if (type == null) { //try to find schema grammar by different means.... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_XSITYPE, typeName.uri, element, typeName, attributes); if (grammar != null) type = grammar.getGlobalTypeDecl(typeName.localpart); } // still couldn't find the type, report an error if (type == null) { reportSchemaError("cvc-elt.4.2", new Object[] { element.rawname, xsiType }); return null; } // if there is no current type, set this one as current. // and we don't need to do extra checking if (fCurrentType != null) { short block = XSConstants.DERIVATION_NONE; // 4.3 The local type definition must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (3.14.6) (if it is a simple type definition). // Note: It's possible to have fCurrentType be non-null and fCurrentElemDecl // be null, if the current type is set using the property "root-type-definition". // In that case, we don't disallow any substitutions. -PM if (fCurrentElemDecl != null) { block = fCurrentElemDecl.fBlock; } if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { block |= ((XSComplexTypeDecl) fCurrentType).fBlock; } if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block)) { reportSchemaError( "cvc-elt.4.3", new Object[] { element.rawname, xsiType, fCurrentType.getName()}); } } return type; } //getAndCheckXsiType boolean getXsiNil(QName element, String xsiNil) { // Element Locally Valid (Element) // 3 The appropriate case among the following must be true: // 3.1 If {nillable} is false, then there must be no attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is nil. if (fCurrentElemDecl != null && !fCurrentElemDecl.getNillable()) { reportSchemaError( "cvc-elt.3.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } // 3.2 If {nillable} is true and there is such an attribute information item and its actual value is true , then all of the following must be true: // 3.2.2 There must be no fixed {value constraint}. else { String value = XMLChar.trim(xsiNil); if (value.equals(SchemaSymbols.ATTVAL_TRUE) || value.equals(SchemaSymbols.ATTVAL_TRUE_1)) { if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { reportSchemaError( "cvc-elt.3.2.2", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } return true; } } return false; } void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { if (DEBUG) { System.out.println("==>processAttributes: " + attributes.getLength()); } // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); Augmentations augs = null; AttributePSVImpl attrPSVI = null; boolean isSimple = fCurrentType == null || fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE; XSObjectList attrUses = null; int useCount = 0; XSWildcardDecl attrWildcard = null; if (!isSimple) { attrUses = attrGrp.getAttributeUses(); useCount = attrUses.getLength(); attrWildcard = attrGrp.fAttributeWC; } // Element Locally Valid (Complex Type) // 3 For each attribute information item in the element information item's [attributes] excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation, the appropriate case among the following must be true: // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (DEBUG) { System.out.println("==>process attribute: " + fTempQName); } if (fAugPSVI || fIdConstraint) { augs = attributes.getAugmentations(index); attrPSVI = (AttributePSVImpl) augs.getItem(Constants.ATTRIBUTE_PSVI); if (attrPSVI != null) { attrPSVI.reset(); } else { attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); } // PSVI attribute: validation context attrPSVI.fValidationContext = fValidationRoot; } // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those // whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and // whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. // for the 4 xsi attributes, get appropriate decl, and validate if (fTempQName.uri == SchemaSymbols.URI_XSI) { XSAttributeDecl attrDecl = null; if (fTempQName.localpart == SchemaSymbols.XSI_TYPE) { attrDecl = XSI_TYPE; } else if (fTempQName.localpart == SchemaSymbols.XSI_NIL) { attrDecl = XSI_NIL; } else if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION) { attrDecl = XSI_SCHEMALOCATION; } else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION) { attrDecl = XSI_NONAMESPACESCHEMALOCATION; } if (attrDecl != null) { processOneAttribute(element, attributes, index, attrDecl, null, attrPSVI); continue; } } // for namespace attributes, no_validation/unknow_validity if (fTempQName.rawname == XMLSymbols.PREFIX_XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // simple type doesn't allow any other attributes if (isSimple) { reportSchemaError( "cvc-type.3.1.1", new Object[] { element.rawname, fTempQName.rawname }); continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUseImpl currUse = null, oneUse; for (int i = 0; i < useCount; i++) { oneUse = (XSAttributeUseImpl) attrUses.item(i); if (oneUse.fAttrDecl.fName == fTempQName.localpart && oneUse.fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = oneUse; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be valid with respect to it as defined in Item Valid (Wildcard) (3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); if (attrWildcard == null || !attrWildcard.allowNamespace(fTempQName.uri)) { // so this attribute is not allowed reportSchemaError( "cvc-complex-type.3.2.2", new Object[] { element.rawname, fTempQName.rawname }); // We have seen an attribute that was not declared fNFullValidationDepth = fElementDepth; continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if processContents is skip if (attrWildcard.fProcessContents == XSWildcardDecl.PC_SKIP) continue; //try to find grammar by different means... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_ATTRIBUTE, fTempQName.uri, element, fTempQName, attributes); if (grammar != null) { currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); } // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { reportSchemaError( "cvc-complex-type.3.2.2", new Object[] { element.rawname, fTempQName.rawname }); } // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose validation resulted in a context-determined declaration of mustFind or no context-determined declaration at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in wild IDs. if (currDecl.fType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE && ((XSSimpleType) currDecl.fType).isIDType()) { if (wildcardIDName != null) { reportSchemaError( "cvc-complex-type.5.1", new Object[] { element.rawname, currDecl.fName, wildcardIDName }); } else wildcardIDName = currDecl.fName; } } } processOneAttribute(element, attributes, index, currDecl, currUse, attrPSVI); } // end of for (all attributes) // 5.2 If wild IDs is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. if (!isSimple && attrGrp.fIDAttrName != null && wildcardIDName != null) { reportSchemaError( "cvc-complex-type.5.2", new Object[] { element.rawname, wildcardIDName, attrGrp.fIDAttrName }); } } //processAttributes void processOneAttribute( QName element, XMLAttributes attributes, int index, XSAttributeDecl currDecl, XSAttributeUseImpl currUse, AttributePSVImpl attrPSVI) { String attrValue = attributes.getValue(index); fXSIErrorReporter.pushContext(); // Attribute Locally Valid // For an attribute information item to be locally valid with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be absent (see Missing Sub-components (5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's normalized value must be locally valid with respect to that {type definition} as per String Valid (3.14.4). // get simple type XSSimpleType attDV = currDecl.fType; Object actualValue = null; try { actualValue = attDV.validate(attrValue, fValidationState, fValidatedInfo); // store the normalized value if (fNormalizeData) { attributes.setValue(index, fValidatedInfo.normalizedValue); } // PSVI: element notation if (attDV.getVariety() == XSSimpleType.VARIETY_ATOMIC && attDV.getPrimitiveKind() == XSSimpleType.PRIMITIVE_NOTATION) { QName qName = (QName) actualValue; SchemaGrammar grammar = fGrammarBucket.getGrammar(qName.uri); //REVISIT: is it possible for the notation to be in different namespace than the attribute //with which it is associated, CHECK !! <fof n1:att1 = "n2:notation1" ..> // should we give chance to the application to be able to retrieve a grammar - nb //REVISIT: what would be the triggering component here.. if it is attribute value that // triggered the loading of grammar ?? -nb if (grammar != null) { fNotation = grammar.getGlobalNotationDecl(qName.localpart); } } } catch (InvalidDatatypeValueException idve) { reportSchemaError(idve.getKey(), idve.getArgs()); reportSchemaError( "cvc-attribute.3", new Object[] { element.rawname, fTempQName.rawname, attrValue, (attDV instanceof XSSimpleTypeDecl) ? ((XSSimpleTypeDecl) attDV).getTypeName() : attDV.getName()}); } // get the value constraint from use or decl // 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (actualValue != null && currDecl.getConstraintType() == XSConstants.VC_FIXED) { if (!ValidatedInfo.isComparable(fValidatedInfo, currDecl.fDefault) || !actualValue.equals(currDecl.fDefault.actualValue)) { reportSchemaError( "cvc-attribute.4", new Object[] { element.rawname, fTempQName.rawname, attrValue, currDecl.fDefault.stringValue()}); } } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an absent {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be valid with respect to that attribute use as per Attribute Locally Valid (Use) (3.5.4). In this case the {attribute declaration} of that attribute use is the context-determined declaration for the attribute information item with respect to Schema-Validity Assessment (Attribute) (3.2.4) and Assessment Outcome (Attribute) (3.2.5). if (actualValue != null && currUse != null && currUse.fConstraintType == XSConstants.VC_FIXED) { if (!ValidatedInfo.isComparable(fValidatedInfo, currUse.fDefault) || !actualValue.equals(currUse.fDefault.actualValue)) { reportSchemaError( "cvc-complex-type.3.1", new Object[] { element.rawname, fTempQName.rawname, attrValue, currUse.fDefault.stringValue()}); } } if (fIdConstraint) { attrPSVI.fValue.copyFrom(fValidatedInfo); } if (fAugPSVI) { // PSVI: attribute declaration attrPSVI.fDeclaration = currDecl; // PSVI: attribute type attrPSVI.fTypeDecl = attDV; // PSVI: attribute normalized value // NOTE: we always store the normalized value, even if it's invlid, // because it might still be useful to the user. But when the it's // not valid, the normalized value is not trustable. attrPSVI.fValue.copyFrom(fValidatedInfo); // PSVI: validation attempted: attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; // We have seen an attribute that was declared. fNNoneValidationDepth = fElementDepth; String[] errors = fXSIErrorReporter.mergeContext(); // PSVI: error codes attrPSVI.fErrors = errors; // PSVI: validity attrPSVI.fValidity = (errors == null) ? AttributePSVI.VALIDITY_VALID : AttributePSVI.VALIDITY_INVALID; } } void addDefaultAttributes( QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // REVISIT: should we check prohibited attributes? // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) // if (DEBUG) { System.out.println("==>addDefaultAttributes: " + element); } XSObjectList attrUses = attrGrp.getAttributeUses(); int useCount = attrUses.getLength(); XSAttributeUseImpl currUse; XSAttributeDecl currDecl; short constType; ValidatedInfo defaultValue; boolean isSpecified; QName attName; // for each attribute use for (int i = 0; i < useCount; i++) { currUse = (XSAttributeUseImpl) attrUses.item(i); currDecl = currUse.fAttrDecl; // get value constraint constType = currUse.fConstraintType; defaultValue = currUse.fDefault; if (constType == XSConstants.VC_NONE) { constType = currDecl.getConstraintType(); defaultValue = currDecl.fDefault; } // whether this attribute is specified isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null; // Element Locally Valid (Complex Type) // 4 The {attribute declaration} of each attribute use in the {attribute uses} whose // {required} is true matches one of the attribute information items in the element // information item's [attributes] as per clause 3.1 above. if (currUse.fUse == SchemaSymbols.USE_REQUIRED) { if (!isSpecified) reportSchemaError( "cvc-complex-type.4", new Object[] { element.rawname, currDecl.fName }); } // if the attribute is not specified, then apply the value constraint if (!isSpecified && constType != XSConstants.VC_NONE) { attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace); String normalized = (defaultValue != null) ? defaultValue.stringValue() : ""; int attrIndex; if (attributes instanceof XMLAttributesImpl) { XMLAttributesImpl attrs = (XMLAttributesImpl) attributes; attrIndex = attrs.getLength(); attrs.addAttributeNS(attName, "CDATA", normalized); } else { attrIndex = attributes.addAttribute(attName, "CDATA", normalized); } if (fAugPSVI) { // PSVI: attribute is "schema" specified Augmentations augs = attributes.getAugmentations(attrIndex); AttributePSVImpl attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); attrPSVI.fDeclaration = currDecl; attrPSVI.fTypeDecl = currDecl.fType; attrPSVI.fValue.copyFrom(defaultValue); attrPSVI.fValidationContext = fValidationRoot; attrPSVI.fValidity = AttributePSVI.VALIDITY_VALID; attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; attrPSVI.fSpecified = true; } } } // for } // addDefaultAttributes /** * If there is not text content, and there is a * {value constraint} on the corresponding element decl, then return * an XMLString representing the default value. */ void processElementContent(QName element) { // 1 If the item is ?valid? with respect to an element declaration as per Element Locally Valid (Element) (?3.3.4) and the {value constraint} is present, but clause 3.2 of Element Locally Valid (Element) (?3.3.4) above is not satisfied and the item has no element or character information item [children], then schema. Furthermore, the post-schema-validation infoset has the canonical lexical representation of the {value constraint} value as the item's [schema normalized value] property. if (fCurrentElemDecl != null && fCurrentElemDecl.fDefault != null && !fSawText && !fSubElement && !fNil) { String strv = fCurrentElemDecl.fDefault.stringValue(); int bufLen = strv.length(); if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) { fNormalizedStr.ch = new char[bufLen]; } strv.getChars(0, bufLen, fNormalizedStr.ch, 0); fNormalizedStr.offset = 0; fNormalizedStr.length = bufLen; fDefaultValue = fNormalizedStr; } // fixed values are handled later, after xsi:type determined. fValidatedInfo.normalizedValue = null; // Element Locally Valid (Element) // 3.2.1 The element information item must have no character or element information item [children]. if (fNil) { if (fSubElement || fSawText) { reportSchemaError( "cvc-elt.3.2.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } } this.fValidatedInfo.reset(); // 5 The appropriate case among the following must be true: // 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() != XSConstants.VC_NONE && !fSubElement && !fSawText && !fNil) { // 5.1.1 If the actual type definition is a local type definition then the canonical lexical representation of the {value constraint} value must be a valid default for the actual type definition as defined in Element Default Valid (Immediate) (3.3.6). if (fCurrentType != fCurrentElemDecl.fType) { //REVISIT:we should pass ValidatedInfo here. if (XSConstraints .ElementDefaultValidImmediate( fCurrentType, fCurrentElemDecl.fDefault.stringValue(), fState4XsiType, null) == null) reportSchemaError( "cvc-elt.5.1.1", new Object[] { element.rawname, fCurrentType.getName(), fCurrentElemDecl.fDefault.stringValue()}); } // 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its normalized value must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). // REVISIT: don't use toString, but validateActualValue instead // use the fState4ApplyDefault elementLocallyValidType(element, fCurrentElemDecl.fDefault.stringValue()); } else { // The following method call also deal with clause 1.2.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true: // 5.2.1 The element information item must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). Object actualValue = elementLocallyValidType(element, fBuffer); // 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED && !fNil) { String content = fBuffer.toString(); // 5.2.2.1 The element information item must have no element information item [children]. if (fSubElement) reportSchemaError("cvc-elt.5.2.2.1", new Object[] { element.rawname }); // 5.2.2.2 The appropriate case among the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; // 5.2.2.2.1 If the {content type} of the actual type definition is mixed, then the initial value of the item must match the canonical lexical representation of the {value constraint} value. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // REVISIT: how to get the initial value, does whiteSpace count? if (!fCurrentElemDecl.fDefault.normalizedValue.equals(content)) reportSchemaError( "cvc-elt.5.2.2.2.1", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue }); } // 5.2.2.2.2 If the {content type} of the actual type definition is a simple type definition, then the actual value of the item must match the canonical lexical representation of the {value constraint} value. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (actualValue != null && (!ValidatedInfo.isComparable(fValidatedInfo, fCurrentElemDecl.fDefault) || !actualValue.equals(fCurrentElemDecl.fDefault.actualValue))) { reportSchemaError( "cvc-elt.5.2.2.2.2", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.stringValue()}); } } } else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { if (actualValue != null && (!ValidatedInfo.isComparable(fValidatedInfo, fCurrentElemDecl.fDefault) || !actualValue.equals(fCurrentElemDecl.fDefault.actualValue))) { // REVISIT: the spec didn't mention this case: fixed // value with simple type reportSchemaError( "cvc-elt.5.2.2.2.2", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.stringValue()}); } } } } if (fDefaultValue == null && fNormalizeData && fDocumentHandler != null && fUnionType) { // for union types we need to send data because we delayed sending // this data when we received it in the characters() call. String content = fValidatedInfo.normalizedValue; if (content == null) content = fBuffer.toString(); int bufLen = content.length(); if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) { fNormalizedStr.ch = new char[bufLen]; } content.getChars(0, bufLen, fNormalizedStr.ch, 0); fNormalizedStr.offset = 0; fNormalizedStr.length = bufLen; fDocumentHandler.characters(fNormalizedStr, null); } } // processElementContent Object elementLocallyValidType(QName element, Object textContent) { if (fCurrentType == null) return null; Object retValue = null; // Element Locally Valid (Type) // 3 The appropriate case among the following must be true: // 3.1 If the type definition is a simple type definition, then all of the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { // 3.1.2 The element information item must have no element information item [children]. if (fSubElement) reportSchemaError("cvc-type.3.1.2", new Object[] { element.rawname }); // 3.1.3 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the normalized value must be valid with respect to the type definition as defined by String Valid (3.14.4). if (!fNil) { XSSimpleType dv = (XSSimpleType) fCurrentType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } retValue = dv.validate(textContent, fValidationState, fValidatedInfo); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError( "cvc-type.3.1.3", new Object[] { element.rawname, textContent }); } } } else { // 3.2 If the type definition is a complex type definition, then the element information item must be valid with respect to the type definition as per Element Locally Valid (Complex Type) (3.4.4); retValue = elementLocallyValidComplexType(element, textContent); } return retValue; } // elementLocallyValidType Object elementLocallyValidComplexType(QName element, Object textContent) { Object actualValue = null; XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; // Element Locally Valid (Complex Type) // For an element information item to be locally valid with respect to a complex type definition all of the following must be true: // 1 {abstract} is false. // 2 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the appropriate case among the following must be true: if (!fNil) { // 2.1 If the {content type} is empty, then the element information item has no character or element information item [children]. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY && (fSubElement || fSawText)) { reportSchemaError("cvc-complex-type.2.1", new Object[] { element.rawname }); } // 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the normalized value of the element information item is valid with respect to that simple type definition as defined by String Valid (3.14.4). else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (fSubElement) reportSchemaError("cvc-complex-type.2.2", new Object[] { element.rawname }); XSSimpleType dv = ctype.fXSSimpleType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } actualValue = dv.validate(textContent, fValidationState, fValidatedInfo); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-complex-type.2.2", new Object[] { element.rawname }); } // REVISIT: eventually, this method should return the same actualValue as elementLocallyValidType... // obviously it'll return null when the content is complex. } // 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)]. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { if (fSawCharacters) { reportSchemaError("cvc-complex-type.2.3", new Object[] { element.rawname }); } } // 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is valid with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (3.9.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT || ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // if the current state is a valid state, check whether // it's one of the final states. if (DEBUG) { System.out.println(fCurrCMState); } if (fCurrCMState[0] >= 0 && !fCurrentCM.endContentModel(fCurrCMState)) { String expected = expectedStr(fCurrentCM.whatCanGoHere(fCurrCMState)); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.j", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.i", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } else { reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected }); } } } } return actualValue; } // elementLocallyValidComplexType void processRootTypeQName(final javax.xml.namespace.QName rootTypeQName) { String rootTypeNamespace = rootTypeQName.getNamespaceURI(); if (rootTypeNamespace != null && rootTypeNamespace.equals(XMLConstants.NULL_NS_URI)) { rootTypeNamespace = null; } if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(rootTypeNamespace)) { fCurrentType = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(rootTypeQName.getLocalPart()); } else { final SchemaGrammar grammarForRootType = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, rootTypeNamespace, null, null, null); if (grammarForRootType != null) { fCurrentType = grammarForRootType.getGlobalTypeDecl(rootTypeQName.getLocalPart()); } } if (fCurrentType == null) { String typeName = (rootTypeQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ? rootTypeQName.getLocalPart() : rootTypeQName.getPrefix()+":"+rootTypeQName.getLocalPart(); reportSchemaError("cvc-type.1", new Object[] {typeName}); } } // processRootTypeQName void processRootElementDeclQName(final javax.xml.namespace.QName rootElementDeclQName, final QName element) { String rootElementDeclNamespace = rootElementDeclQName.getNamespaceURI(); if (rootElementDeclNamespace != null && rootElementDeclNamespace.equals(XMLConstants.NULL_NS_URI)) { rootElementDeclNamespace = null; } final SchemaGrammar grammarForRootElement = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, rootElementDeclNamespace, null, null, null); if (grammarForRootElement != null) { fCurrentElemDecl = grammarForRootElement.getGlobalElementDecl(rootElementDeclQName.getLocalPart()); } if (fCurrentElemDecl == null) { String declName = (rootElementDeclQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ? rootElementDeclQName.getLocalPart() : rootElementDeclQName.getPrefix()+":"+rootElementDeclQName.getLocalPart(); reportSchemaError("cvc-elt.1.a", new Object[] {declName}); } else { checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } } // processRootElementDeclQName void checkElementMatchesRootElementDecl(final XSElementDecl rootElementDecl, final QName element) { // Report an error if the name of the element does // not match the name of the specified element declaration. if (element.localpart != rootElementDecl.fName || element.uri != rootElementDecl.fTargetNamespace) { reportSchemaError("cvc-elt.1.b", new Object[] {element.rawname, rootElementDecl.fName}); } } // checkElementMatchesRootElementDecl void reportSchemaError(String key, Object[] arguments) { if (fDoValidation) fXSIErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, key, arguments, XMLErrorReporter.SEVERITY_ERROR); } private String expectedStr(Vector expected) { StringBuffer ret = new StringBuffer("{"); int size = expected.size(); for (int i = 0; i < size; i++) { if (i > 0) ret.append(", "); ret.append(expected.elementAt(i).toString()); } ret.append('}'); return ret.toString(); } /**********************************/ // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // // Data // /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // // Constructors // public XPathMatcherStack() { } // <init>() // // Public methods // /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // // Private methods // /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // // Data // /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; protected int fFieldCount = 0; protected Field[] fFields = null; /** current data */ protected Object[] fLocalValues = null; protected short[] fLocalValueTypes = null; protected ShortList[] fLocalItemValueTypes = null; /** Current data value count. */ protected int fValuesCount; /** global data */ public final Vector fValues = new Vector(); public ShortVector fValueTypes = null; public Vector fItemValueTypes = null; private boolean fUseValueTypeVector = false; private int fValueTypesLength = 0; private short fValueType = 0; private boolean fUseItemValueTypeVector = false; private int fItemValueTypesLength = 0; private ShortList fItemValueType = null; /** buffer for error messages */ final StringBuffer fTempBuffer = new StringBuffer(); // // Constructors // /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint) { fIdentityConstraint = identityConstraint; fFieldCount = fIdentityConstraint.getFieldCount(); fFields = new Field[fFieldCount]; fLocalValues = new Object[fFieldCount]; fLocalValueTypes = new short[fFieldCount]; fLocalItemValueTypes = new ShortList[fFieldCount]; for (int i = 0; i < fFieldCount; i++) { fFields[i] = fIdentityConstraint.getFieldAt(i); } } // <init>(IdentityConstraint) // // Public methods // // destroys this ValueStore; useful when, for instance, a // locally-scoped ID constraint is involved. public void clear() { fValuesCount = 0; fUseValueTypeVector = false; fValueTypesLength = 0; fValueType = 0; fUseItemValueTypeVector = false; fItemValueTypesLength = 0; fItemValueType = null; fValues.setSize(0); if (fValueTypes != null) { fValueTypes.clear(); } if (fItemValueTypes != null) { fItemValueTypes.setSize(0); } } // end clear():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValues.size(); i++) { fValues.addElement(newVal.fValues.elementAt(i)); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() { fValuesCount = 0; for (int i = 0; i < fFieldCount; i++) { fLocalValues[i] = null; fLocalValueTypes[i] = 0; fLocalItemValueTypes[i] = null; } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() { if (fValuesCount == 0) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "AbsentKeyValue"; String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { eName, cName }); } return; } // Validation Rule: Identity-constraint Satisfied // 4.2 If the {identity-constraint category} is key, then all of the following must be true: // 4.2.1 The target node set and the qualified node set are equal, that is, every member of the // target node set is also a member of the qualified node set and vice versa. // // If the IDC is a key check whether we have all the fields. if (fValuesCount != fFieldCount) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "KeyNotEnoughValues"; UniqueOrKey key = (UniqueOrKey) fIdentityConstraint; String eName = fIdentityConstraint.getElementName(); String cName = key.getIdentityConstraintName(); reportSchemaError(code, new Object[] { eName, cName }); } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() { } // endDocument() // // ValueStore methods // /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportError(String key, Object[] args) { reportSchemaError(key, args); } // reportError(String,Object[]) /** * Adds the specified value to the value store. * * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. * @param mayMatch a flag indiciating whether the field may be matched. * @param actualValue The value to add. * @param valueType Type of the value to add. * @param itemValueType If the value is a list, a list of types for each of the values in the list. */ public void addValue(Field field, boolean mayMatch, Object actualValue, short valueType, ShortList itemValueType) { int i; for (i = fFieldCount - 1; i > -1; i--) { if (fFields[i] == field) { break; } } // do we even know this field? if (i == -1) { String code = "UnknownField"; String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { field.toString(), eName, cName }); return; } if (!mayMatch) { String code = "FieldMultipleMatch"; String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { field.toString(), cName }); } else { fValuesCount++; } fLocalValues[i] = actualValue; fLocalValueTypes[i] = valueType; fLocalItemValueTypes[i] = itemValueType; if (fValuesCount == fFieldCount) { checkDuplicateValues(); // store values for (i = 0; i < fFieldCount; i++) { fValues.addElement(fLocalValues[i]); addValueType(fLocalValueTypes[i]); addItemValueType(fLocalItemValueTypes[i]); } } } // addValue(String,Field) /** * Returns true if this value store contains the locally scoped value stores */ public boolean contains() { // REVISIT: we can improve performance by using hash codes, instead of // traversing global vector that could be quite large. int next = 0; final int size = fValues.size(); LOOP : for (int i = 0; i < size; i = next) { next = i + fFieldCount; for (int j = 0; j < fFieldCount; j++) { Object value1 = fLocalValues[j]; Object value2 = fValues.elementAt(i); short valueType1 = fLocalValueTypes[j]; short valueType2 = getValueTypeAt(i); if (value1 == null || value2 == null || valueType1 != valueType2 || !(value1.equals(value2))) { continue LOOP; } else if(valueType1 == XSConstants.LIST_DT || valueType1 == XSConstants.LISTOFUNION_DT) { ShortList list1 = fLocalItemValueTypes[j]; ShortList list2 = getItemValueTypeAt(i); if(list1 == null || list2 == null || !list1.equals(list2)) continue LOOP; } i++; } // found it return true; } // didn't find it return false; } // contains():boolean /** * Returns -1 if this value store contains the specified * values, otherwise the index of the first field in the * key sequence. */ public int contains(ValueStoreBase vsb) { final Vector values = vsb.fValues; final int size1 = values.size(); if (fFieldCount <= 1) { for (int i = 0; i < size1; ++i) { short val = vsb.getValueTypeAt(i); if (!valueTypeContains(val) || !fValues.contains(values.elementAt(i))) { return i; } else if(val == XSConstants.LIST_DT || val == XSConstants.LISTOFUNION_DT) { ShortList list1 = vsb.getItemValueTypeAt(i); if (!itemValueTypeContains(list1)) { return i; } } } } /** Handle n-tuples. **/ else { final int size2 = fValues.size(); /** Iterate over each set of fields. **/ OUTER: for (int i = 0; i < size1; i += fFieldCount) { /** Check whether this set is contained in the value store. **/ INNER: for (int j = 0; j < size2; j += fFieldCount) { for (int k = 0; k < fFieldCount; ++k) { final Object value1 = values.elementAt(i+k); final Object value2 = fValues.elementAt(j+k); final short valueType1 = vsb.getValueTypeAt(i+k); final short valueType2 = getValueTypeAt(j+k); if (value1 != value2 && (valueType1 != valueType2 || value1 == null || !value1.equals(value2))) { continue INNER; } else if(valueType1 == XSConstants.LIST_DT || valueType1 == XSConstants.LISTOFUNION_DT) { ShortList list1 = vsb.getItemValueTypeAt(i+k); ShortList list2 = getItemValueTypeAt(j+k); if (list1 == null || list2 == null || !list1.equals(list2)) { continue INNER; } } } continue OUTER; } return i; } } return -1; } // contains(Vector):Object // // Protected methods // protected void checkDuplicateValues() { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(Object[] values) { // no values int size = values.length; if (size == 0) { return ""; } fTempBuffer.setLength(0); // construct value string for (int i = 0; i < size; i++) { if (i > 0) { fTempBuffer.append(','); } fTempBuffer.append(values[i]); } return fTempBuffer.toString(); } // toString(Object[]):String /** Returns a string of the specified values. */ protected String toString(Vector values, int start, int length) { // no values if (length == 0) { return ""; } // one value if (length == 1) { return String.valueOf(values.elementAt(start)); } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < length; i++) { if (i > 0) { str.append(','); } str.append(values.elementAt(start + i)); } return str.toString(); } // toString(Vector,int,int):String // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String // // Private methods // private void addValueType(short type) { if (fUseValueTypeVector) { fValueTypes.add(type); } else if (fValueTypesLength++ == 0) { fValueType = type; } else if (fValueType != type) { fUseValueTypeVector = true; if (fValueTypes == null) { fValueTypes = new ShortVector(fValueTypesLength * 2); } for (int i = 1; i < fValueTypesLength; ++i) { fValueTypes.add(fValueType); } fValueTypes.add(type); } } private short getValueTypeAt(int index) { if (fUseValueTypeVector) { return fValueTypes.valueAt(index); } return fValueType; } private boolean valueTypeContains(short value) { if (fUseValueTypeVector) { return fValueTypes.contains(value); } return fValueType == value; } private void addItemValueType(ShortList itemValueType) { if (fUseItemValueTypeVector) { fItemValueTypes.add(itemValueType); } else if (fItemValueTypesLength++ == 0) { fItemValueType = itemValueType; } else if (!(fItemValueType == itemValueType || (fItemValueType != null && fItemValueType.equals(itemValueType)))) { fUseItemValueTypeVector = true; if (fItemValueTypes == null) { fItemValueTypes = new Vector(fItemValueTypesLength * 2); } for (int i = 1; i < fItemValueTypesLength; ++i) { fItemValueTypes.add(fItemValueType); } fItemValueTypes.add(itemValueType); } } private ShortList getItemValueTypeAt(int index) { if (fUseItemValueTypeVector) { return (ShortList) fItemValueTypes.elementAt(index); } return fItemValueType; } private boolean itemValueTypeContains(ShortList value) { if (fUseItemValueTypeVector) { return fItemValueTypes.contains(value); } return fItemValueType == value || (fItemValueType != null && fItemValueType.equals(value)); } } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // // Constructors // /** Constructs a unique value store. */ public UniqueValueStore(UniqueOrKey unique) { super(unique); } // <init>(Unique) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. */ protected void checkDuplicateValues() { // is this value as a group duplicated? if (contains()) { String code = "DuplicateUnique"; String value = toString(fLocalValues); String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { value, eName, cName }); } } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // // Constructors // /** Constructs a key value store. */ public KeyValueStore(UniqueOrKey key) { super(key); } // <init>(Key) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. */ protected void checkDuplicateValues() { if (contains()) { String code = "DuplicateKey"; String value = toString(fLocalValues); String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { value, eName, cName }); } } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // // Data // /** Key value store. */ protected ValueStoreBase fKeyValueStore; // // Constructors // /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) { super(keyRef); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // // ValueStoreBase methods // // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment() { // do all the necessary management... super.endDocumentFragment(); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase) fValueStoreCache.fGlobalIDConstraintMap.get( ((KeyRef) fIdentityConstraint).getKey()); if (fKeyValueStore == null) { // report error String code = "KeyRefOutOfScope"; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[] { value }); return; } int errorIndex = fKeyValueStore.contains(this); if (errorIndex != -1) { String code = "KeyNotFound"; String values = toString(fValues, errorIndex, fFieldCount); String element = fIdentityConstraint.getElementName(); String name = fIdentityConstraint.getName(); reportSchemaError(code, new Object[] { name, values, element }); } } // endDocumentFragment() /** End document. */ public void endDocument() { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // // Data // final LocalIDKey fLocalId = new LocalIDKey(); // values stores /** stores all global Values stores. */ protected final ArrayList fValueStores = new ArrayList(); /** * Values stores associated to specific identity constraints. * This hashtable maps IdentityConstraints and * the 0-based element on which their selectors first matched to * a corresponding ValueStore. This should take care * of all cases, including where ID constraints with * descendant-or-self axes occur on recursively-defined * elements. */ protected final HashMap fIdentityConstraint2ValueStoreMap = new HashMap(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., when it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // // The fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endElement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final HashMap fGlobalIDConstraintMap = new HashMap(); // // Constructors // /** Default constructor. */ public ValueStoreCache() { } // <init>() // // Public methods // /** Resets the identity constraint cache. */ public void startDocument() { fValueStores.clear(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { // only clone the map when there are elements if (fGlobalIDConstraintMap.size() > 0) fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); else fGlobalMapStack.push(null); fGlobalIDConstraintMap.clear(); } // startElement(void) /** endElement(): merges contents of fGlobalIDConstraintMap with the * top of fGlobalMapStack into fGlobalIDConstraintMap. */ public void endElement() { if (fGlobalMapStack.isEmpty()) { return; // must be an invalid doc! } HashMap oldMap = (HashMap) fGlobalMapStack.pop(); // return if there is no element if (oldMap == null) { return; } Iterator entries = oldMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IdentityConstraint id = (IdentityConstraint) entry.getKey(); ValueStoreBase oldVal = (ValueStoreBase) entry.getValue(); if (oldVal != null) { ValueStoreBase currVal = (ValueStoreBase) fGlobalIDConstraintMap.get(id); if (currVal == null) { fGlobalIDConstraintMap.put(id, oldVal); } else if (currVal != oldVal) { currVal.append(oldVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XSElementDecl eDecl, FieldActivator activator) { // initialize value stores for unique fields IdentityConstraint[] icArray = eDecl.fIDConstraints; int icCount = eDecl.fIDCPos; for (int i = 0; i < icCount; i++) { switch (icArray[i].getCategory()) { case (IdentityConstraint.IC_UNIQUE) : // initialize value stores for unique fields UniqueOrKey unique = (UniqueOrKey) icArray[i]; LocalIDKey toHash = new LocalIDKey(unique, fElementDepth); UniqueValueStore uniqueValueStore = (UniqueValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (uniqueValueStore == null) { uniqueValueStore = new UniqueValueStore(unique); fIdentityConstraint2ValueStoreMap.put(toHash, uniqueValueStore); } else { uniqueValueStore.clear(); } fValueStores.add(uniqueValueStore); activateSelectorFor(icArray[i]); break; case (IdentityConstraint.IC_KEY) : // initialize value stores for key fields UniqueOrKey key = (UniqueOrKey) icArray[i]; toHash = new LocalIDKey(key, fElementDepth); KeyValueStore keyValueStore = (KeyValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (keyValueStore == null) { keyValueStore = new KeyValueStore(key); fIdentityConstraint2ValueStoreMap.put(toHash, keyValueStore); } else { keyValueStore.clear(); } fValueStores.add(keyValueStore); activateSelectorFor(icArray[i]); break; case (IdentityConstraint.IC_KEYREF) : // initialize value stores for keyRef fields KeyRef keyRef = (KeyRef) icArray[i]; toHash = new LocalIDKey(keyRef, fElementDepth); KeyRefValueStore keyRefValueStore = (KeyRefValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (keyRefValueStore == null) { keyRefValueStore = new KeyRefValueStore(keyRef, null); fIdentityConstraint2ValueStoreMap.put(toHash, keyRefValueStore); } else { keyRefValueStore.clear(); } fValueStores.add(keyRefValueStore); activateSelectorFor(icArray[i]); break; } } } // initValueStoresFor(XSElementDecl) /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id, int initialDepth) { fLocalId.fDepth = initialDepth; fLocalId.fId = id; return (ValueStoreBase) fIdentityConstraint2ValueStoreMap.get(fLocalId); } // getValueStoreFor(IdentityConstraint, int):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { return (ValueStoreBase) fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id, int initialDepth) { fLocalId.fDepth = initialDepth; fLocalId.fId = id; ValueStoreBase newVals = (ValueStoreBase) fIdentityConstraint2ValueStoreMap.get(fLocalId); if (id.getCategory() == IdentityConstraint.IC_KEYREF) return; ValueStoreBase currVals = (ValueStoreBase) fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() { int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase) fValueStores.get(i); valueStore.endDocument(); } } // endDocument() // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // the purpose of this class is to enable IdentityConstraint,int // pairs to be used easily as keys in Hashtables. protected static final class LocalIDKey { public IdentityConstraint fId; public int fDepth; public LocalIDKey() { } public LocalIDKey(IdentityConstraint id, int depth) { fId = id; fDepth = depth; } // init(IdentityConstraint, int) // object method public int hashCode() { return fId.hashCode() + fDepth; } public boolean equals(Object localIDKey) { if (localIDKey instanceof LocalIDKey) { LocalIDKey lIDKey = (LocalIDKey) localIDKey; return (lIDKey.fId == fId && lIDKey.fDepth == fDepth); } return false; } } // class LocalIDKey /** * A simple vector for <code>short</code>s. */ protected static final class ShortVector { // // Data // /** Current length. */ private int fLength; /** Data. */ private short[] fData; // // Constructors // public ShortVector() {} public ShortVector(int initialCapacity) { fData = new short[initialCapacity]; } // // Public methods // /** Returns the length of the vector. */ public int length() { return fLength; } /** Adds the value to the vector. */ public void add(short value) { ensureCapacity(fLength + 1); fData[fLength++] = value; } /** Returns the short value at the specified position in the vector. */ public short valueAt(int position) { return fData[position]; } /** Clears the vector. */ public void clear() { fLength = 0; } /** Returns whether the short is contained in the vector. */ public boolean contains(short value) { for (int i = 0; i < fLength; ++i) { if (fData[i] == value) { return true; } } return false; } // // Private methods // /** Ensures capacity. */ private void ensureCapacity(int size) { if (fData == null) { fData = new short[8]; } else if (fData.length <= size) { short[] newdata = new short[fData.length * 2]; System.arraycopy(fData, 0, newdata, 0, fData.length); fData = newdata; } } } } // class SchemaValidator
false
true
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { element.rawname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.fAnyType; fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.fAnyType; else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } return augs; } // handleStartElement(QName,XMLAttributes,boolean)
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.fAnyType; fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.fAnyType; else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } return augs; } // handleStartElement(QName,XMLAttributes,boolean)
diff --git a/example/src/com/slidingmenu/example/BaseActivity.java b/example/src/com/slidingmenu/example/BaseActivity.java index 999407d..4e1f7c4 100644 --- a/example/src/com/slidingmenu/example/BaseActivity.java +++ b/example/src/com/slidingmenu/example/BaseActivity.java @@ -1,70 +1,74 @@ package com.slidingmenu.example; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.support.v4.view.ViewPager; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.slidingmenu.lib.SlidingMenu; import com.slidingmenu.lib.app.SlidingFragmentActivity; public class BaseActivity extends SlidingFragmentActivity { private int mTitleRes; protected ListFragment mFrag; public BaseActivity(int titleRes) { mTitleRes = titleRes; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(mTitleRes); // set the Behind View setBehindContentView(R.layout.menu_frame); - FragmentTransaction t = this.getSupportFragmentManager().beginTransaction(); - mFrag = new SampleListFragment(); - t.replace(R.id.menu_frame, mFrag); - t.commit(); + if (savedInstanceState == null) { + FragmentTransaction t = this.getSupportFragmentManager().beginTransaction(); + mFrag = new SampleListFragment(); + t.replace(R.id.menu_frame, mFrag); + t.commit(); + } else { + mFrag = (ListFragment)this.getSupportFragmentManager().findFragmentById(R.id.menu_frame); + } // customize the SlidingMenu SlidingMenu sm = getSlidingMenu(); sm.setShadowWidthRes(R.dimen.shadow_width); sm.setShadowDrawable(R.drawable.shadow); sm.setBehindOffsetRes(R.dimen.slidingmenu_offset); sm.setFadeDegree(0.35f); sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: toggle(); return true; case R.id.github: Util.goToGitHub(this); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.main, menu); return true; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(mTitleRes); // set the Behind View setBehindContentView(R.layout.menu_frame); FragmentTransaction t = this.getSupportFragmentManager().beginTransaction(); mFrag = new SampleListFragment(); t.replace(R.id.menu_frame, mFrag); t.commit(); // customize the SlidingMenu SlidingMenu sm = getSlidingMenu(); sm.setShadowWidthRes(R.dimen.shadow_width); sm.setShadowDrawable(R.drawable.shadow); sm.setBehindOffsetRes(R.dimen.slidingmenu_offset); sm.setFadeDegree(0.35f); sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); getSupportActionBar().setDisplayHomeAsUpEnabled(true); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(mTitleRes); // set the Behind View setBehindContentView(R.layout.menu_frame); if (savedInstanceState == null) { FragmentTransaction t = this.getSupportFragmentManager().beginTransaction(); mFrag = new SampleListFragment(); t.replace(R.id.menu_frame, mFrag); t.commit(); } else { mFrag = (ListFragment)this.getSupportFragmentManager().findFragmentById(R.id.menu_frame); } // customize the SlidingMenu SlidingMenu sm = getSlidingMenu(); sm.setShadowWidthRes(R.dimen.shadow_width); sm.setShadowDrawable(R.drawable.shadow); sm.setBehindOffsetRes(R.dimen.slidingmenu_offset); sm.setFadeDegree(0.35f); sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); getSupportActionBar().setDisplayHomeAsUpEnabled(true); }
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/export/utils/exported/XPathBuilder.java b/CubicTestPlugin/src/main/java/org/cubictest/export/utils/exported/XPathBuilder.java index 3ee12b29..82942538 100644 --- a/CubicTestPlugin/src/main/java/org/cubictest/export/utils/exported/XPathBuilder.java +++ b/CubicTestPlugin/src/main/java/org/cubictest/export/utils/exported/XPathBuilder.java @@ -1,327 +1,332 @@ /******************************************************************************* * Copyright (c) 2005, 2008 Stein K. Skytteren and Christian Schwarz * 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: * Stein K. Skytteren and Christian Schwarz - initial API and implementation *******************************************************************************/ package org.cubictest.export.utils.exported; import static org.cubictest.model.IdentifierType.CHECKED; import static org.cubictest.model.IdentifierType.ELEMENT_NAME; import static org.cubictest.model.IdentifierType.FRAME_TYPE; import static org.cubictest.model.IdentifierType.INDEX; import static org.cubictest.model.IdentifierType.LABEL; import static org.cubictest.model.IdentifierType.MULTISELECT; import static org.cubictest.model.IdentifierType.SELECTED; import org.apache.commons.lang.StringUtils; import org.cubictest.export.exceptions.ExporterException; import org.cubictest.model.IActionElement; import org.cubictest.model.Identifier; import org.cubictest.model.IdentifierType; import org.cubictest.model.Image; import org.cubictest.model.Link; import org.cubictest.model.Moderator; import org.cubictest.model.PageElement; import org.cubictest.model.Text; import org.cubictest.model.context.AbstractContext; import org.cubictest.model.context.Frame; import org.cubictest.model.formElement.Button; import org.cubictest.model.formElement.Checkbox; import org.cubictest.model.formElement.Option; import org.cubictest.model.formElement.Password; import org.cubictest.model.formElement.RadioButton; import org.cubictest.model.formElement.Select; import org.cubictest.model.formElement.TextArea; import org.cubictest.model.formElement.TextField; /** * Class for building XPaths based on page elements and its surrounding contexts. * * @author Christian Schwarz * */ public class XPathBuilder { public static final String TEXTFIELD_ATTRIBUTES = "[@type='text' or not(@type)]"; public static String getXPath(IActionElement element) { return getXPath(element, false); } /** * Get the string that represents the Selenium locator-string for the element. * @param element * @param useNamespace * @return */ public static String getXPath(IActionElement element, boolean useNamespace) { PageElement pe = (PageElement) element; PredicateSeperator predicateSeperator = new PredicateSeperator(); String predicates = getIndexAssertion(pe, predicateSeperator) + getLabelAssertion(pe, predicateSeperator, useNamespace) + getAttributeAssertions(pe, predicateSeperator); if (StringUtils.isBlank(predicates)) { return getElementType(pe); } return (useNamespace ? "x:" : "") + getElementType(pe) + "[" + predicates + "]"; } /** * Get string to assert the index of the element (if ID present). */ private static String getIndexAssertion(PageElement pe, PredicateSeperator predicateSeperator) { String result = predicateSeperator.getStartString(); //Start with index attribute (if it exists) to make XPath correct: Identifier id = pe.getIdentifier(INDEX); if (id != null && id.isNotIndifferent()) { String value = pe.getIdentifier(INDEX).getValue(); String operator = "="; if (value.startsWith("<=") || value.startsWith(">=")) { operator = value.substring(0, 2); value = value.substring(2); } else if (value.startsWith("<") || value.startsWith(">")) { operator = value.substring(0, 1); value = value.substring(1); } int index = Integer.parseInt(value); result += "position()" + operator + index; } if (result.equals(predicateSeperator.getStartString())) { return ""; } else { predicateSeperator.setNeedsSeparator(true); return result; } } private static String getLabelAssertion(PageElement pe, PredicateSeperator predicateSeperator, boolean useNamespace) { String result = predicateSeperator.getStartString(); Identifier id = pe.getIdentifier(LABEL); if (id != null && id.isNotIndifferent()) { if (pe instanceof Text) { result += "contains(normalize-space(.), '" + id.getValue() + "')"; } else if (pe instanceof Link || pe instanceof Option) { result += getPageValueCheck(id, "normalize-space(text())"); } else if (pe instanceof Button) { result += getIdentifierCondition(id); } else { //get first element that has "id" attribute equal to the "for" attribute of label with the specified text: String labelCondition = getPageValueCheck(id, "normalize-space(text())"); result += "@id" + getStringComparisonOperator(id) + "(//" + (useNamespace ? "x:" : "") + "label[" + labelCondition + "]/@for)"; } } if (result.equals(predicateSeperator.getStartString())) { return ""; } else { predicateSeperator.setNeedsSeparator(true); return result; } } /** * Get string to assert for all the page elements Identifier/HTML attribute values. * E.g. [@id="someId"] */ private static String getAttributeAssertions(PageElement pe, PredicateSeperator predicateSeperator) { String result = predicateSeperator.getStartString(); int i = 0; for (Identifier id : pe.getNonIndifferentIdentifierts()) { IdentifierType type = id.getType(); if (type.equals(LABEL) || type.equals(INDEX) || type.equals(ELEMENT_NAME) || type.equals(FRAME_TYPE)) { //label are not HTML attributes, index and element name are handled elsewhere continue; } if (i > 0) { result += " and "; } result += getIdentifierCondition(id); i++; } if (result.equals(predicateSeperator.getStartString())) { return ""; } else { predicateSeperator.setNeedsSeparator(true); return result; } } private static String getIdentifierCondition(Identifier id) { String result = ""; if (id.getType().equals(CHECKED) || id.getType().equals(SELECTED) || id.getType().equals(MULTISELECT)) { //idType with no value if (id.getProbability() > 0) { result += "@" + ExportUtils.getHtmlIdType(id)+ "=''"; } else { result += "not(@" + ExportUtils.getHtmlIdType(id) + ")"; } } else { //normal ID type (name, value) String attr = getAttributeToCheck(id); result += getPageValueCheck(id, attr); } return result; } /** * Check a page value against an identifier * @param id the identifier * @param pageValue the XPath fragement for which page value to check * @return */ private static String getPageValueCheck(Identifier id, String pageValue) { String result = ""; String comparisonOperator = getStringComparisonOperator(id); if (id.getModerator().equals(Moderator.EQUAL)) { //normal equal check result += pageValue + comparisonOperator + "'" + id.getValue() + "'"; } else { String prefixOperator = getPrefixComparisonOperator(id); if (id.getModerator().equals(Moderator.BEGIN)) { result += "substring(" + pageValue + ", 0, string-length('" + id.getValue() + "') + 1) " + comparisonOperator + " '" + id.getValue() + "'"; } else if (id.getModerator().equals(Moderator.CONTAIN)) { result += prefixOperator + "(contains(" + pageValue + ", " + "'" + id.getValue() + "'))"; } else if (id.getModerator().equals(Moderator.END)) { result += "substring(" + pageValue + ", string-length(" + pageValue + ") - string-length(" + "'" + id.getValue() +"')" + " + 1, string-length('" + id.getValue() + "')) " + comparisonOperator + " '" + id.getValue() + "'"; } } return result; } private static String getAttributeToCheck(Identifier id) { return "@" + ExportUtils.getHtmlIdType(id); } private static String getPrefixComparisonOperator(Identifier id) { if (id.getProbability() < 0) { return "not"; } return ""; } private static String getStringComparisonOperator(Identifier id) { if (id.getProbability() < 0) { return "!="; } return "="; } /** * Get the HTML element type for the page element. * @param pe * @return */ private static String getElementType(PageElement pe) { if (pe instanceof Select) return "select"; if (pe instanceof Option) return "option"; if (pe instanceof Button) return "input[@type='button' or @type='submit' or @type='image' or @type='reset']"; if (pe instanceof TextField) return "input" + TEXTFIELD_ATTRIBUTES; if (pe instanceof Password) return "input[@type='password']"; if (pe instanceof Checkbox) return "input[@type='checkbox']"; if (pe instanceof RadioButton) return "input[@type='radio']"; if (pe instanceof Link) return "a"; if (pe instanceof Image) return "img"; if (pe instanceof Text) return "*"; if (pe instanceof TextArea) return "textarea"; if (pe instanceof Frame){ if(pe.getIdentifier(IdentifierType.FRAME_TYPE).getProbability() >0){ - if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) + if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) { return "iframe"; - else + } else { return "frame"; - }else if(pe.getIdentifier(IdentifierType.FRAME_TYPE).getProbability() < 0){ - if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) + } + } + else if(pe.getIdentifier(IdentifierType.FRAME_TYPE).getProbability() < 0){ + if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) { return "frame"; - else + } else { return "iframe"; - } - }else + } + } + else { return "*"; + } + } if (pe instanceof AbstractContext) { Identifier elementName = pe.getIdentifier(ELEMENT_NAME); if (elementName != null && StringUtils.isNotBlank(elementName.getValue())) { return elementName.getValue(); } else { return "*"; } } throw new ExporterException("Unknown element type: " + pe); } static class PredicateSeperator { private boolean needsSeparator = false; public void setNeedsSeparator(boolean needsSeparator) { this.needsSeparator = needsSeparator; } public String getStartString() { if (needsSeparator) { return " and "; } return ""; } } }
false
true
private static String getElementType(PageElement pe) { if (pe instanceof Select) return "select"; if (pe instanceof Option) return "option"; if (pe instanceof Button) return "input[@type='button' or @type='submit' or @type='image' or @type='reset']"; if (pe instanceof TextField) return "input" + TEXTFIELD_ATTRIBUTES; if (pe instanceof Password) return "input[@type='password']"; if (pe instanceof Checkbox) return "input[@type='checkbox']"; if (pe instanceof RadioButton) return "input[@type='radio']"; if (pe instanceof Link) return "a"; if (pe instanceof Image) return "img"; if (pe instanceof Text) return "*"; if (pe instanceof TextArea) return "textarea"; if (pe instanceof Frame){ if(pe.getIdentifier(IdentifierType.FRAME_TYPE).getProbability() >0){ if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) return "iframe"; else return "frame"; }else if(pe.getIdentifier(IdentifierType.FRAME_TYPE).getProbability() < 0){ if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) return "frame"; else return "iframe"; } }else return "*"; if (pe instanceof AbstractContext) { Identifier elementName = pe.getIdentifier(ELEMENT_NAME); if (elementName != null && StringUtils.isNotBlank(elementName.getValue())) { return elementName.getValue(); } else { return "*"; } } throw new ExporterException("Unknown element type: " + pe); }
private static String getElementType(PageElement pe) { if (pe instanceof Select) return "select"; if (pe instanceof Option) return "option"; if (pe instanceof Button) return "input[@type='button' or @type='submit' or @type='image' or @type='reset']"; if (pe instanceof TextField) return "input" + TEXTFIELD_ATTRIBUTES; if (pe instanceof Password) return "input[@type='password']"; if (pe instanceof Checkbox) return "input[@type='checkbox']"; if (pe instanceof RadioButton) return "input[@type='radio']"; if (pe instanceof Link) return "a"; if (pe instanceof Image) return "img"; if (pe instanceof Text) return "*"; if (pe instanceof TextArea) return "textarea"; if (pe instanceof Frame){ if(pe.getIdentifier(IdentifierType.FRAME_TYPE).getProbability() >0){ if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) { return "iframe"; } else { return "frame"; } } else if(pe.getIdentifier(IdentifierType.FRAME_TYPE).getProbability() < 0){ if ("iframe".equals(pe.getIdentifier(IdentifierType.FRAME_TYPE).getValue())) { return "frame"; } else { return "iframe"; } } else { return "*"; } } if (pe instanceof AbstractContext) { Identifier elementName = pe.getIdentifier(ELEMENT_NAME); if (elementName != null && StringUtils.isNotBlank(elementName.getValue())) { return elementName.getValue(); } else { return "*"; } } throw new ExporterException("Unknown element type: " + pe); }
diff --git a/ffxieq/src/com/github/kanata3249/ffxieq/EquipmentSet.java b/ffxieq/src/com/github/kanata3249/ffxieq/EquipmentSet.java index 7a2b821..3bdd37e 100644 --- a/ffxieq/src/com/github/kanata3249/ffxieq/EquipmentSet.java +++ b/ffxieq/src/com/github/kanata3249/ffxieq/EquipmentSet.java @@ -1,378 +1,381 @@ /* Copyright 2011 kanata3249 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.github.kanata3249.ffxieq; import java.io.Serializable; import java.util.ArrayList; import com.github.kanata3249.ffxi.status.*; public class EquipmentSet extends StatusModifier implements Serializable { private static final long serialVersionUID = 1L; public static final int MAINWEAPON = 0; public static final int SUBWEAPON = 1; public static final int HEAD = 2; public static final int BODY = 3; public static final int HANDS = 4; public static final int LEGS = 5; public static final int FEET = 6; public static final int BACK = 7; public static final int NECK = 8; public static final int WAIST = 9; public static final int RING1 = 10; public static final int RING2 = 11; public static final int EAR1 = 12; public static final int EAR2 = 13; public static final int RANGE = 14; public static final int ANMO = 15; public static final int EQUIPMENT_NUM = 16; private Equipment[] mEquipments; private transient ArrayList<Combination> mCombinations; private transient boolean mNotModified; public EquipmentSet () { super(); mEquipments = new Equipment[EQUIPMENT_NUM]; mNotModified = false; } // IStatus public StatusValue getStatus(JobLevelAndRace level, StatusType type) { StatusValue total = new StatusValue(0, 0); parseDescriptions(); if (mCombinations != null) { for (int i = 0; i < mCombinations.size(); i++) { Combination combi; combi = mCombinations.get(i); combi.parseDescription(); total.add(combi.getStatus(level, type)); } } if (mEquipments[HEAD] != null) total.add(mEquipments[HEAD].getStatus(level, type)); if (mEquipments[BODY] != null) total.add(mEquipments[BODY].getStatus(level, type)); if (mEquipments[HANDS] != null) total.add(mEquipments[HANDS].getStatus(level, type)); if (mEquipments[LEGS] != null) total.add(mEquipments[LEGS].getStatus(level, type)); if (mEquipments[FEET] != null) total.add(mEquipments[FEET].getStatus(level, type)); if (mEquipments[BACK] != null) total.add(mEquipments[BACK].getStatus(level, type)); if (mEquipments[NECK] != null) total.add(mEquipments[NECK].getStatus(level, type)); if (mEquipments[WAIST] != null) total.add(mEquipments[WAIST].getStatus(level, type)); if (mEquipments[RING1] != null) total.add(mEquipments[RING1].getStatus(level, type)); if (mEquipments[RING2] != null) total.add(mEquipments[RING2].getStatus(level, type)); if (mEquipments[EAR1] != null) total.add(mEquipments[EAR1].getStatus(level, type)); if (mEquipments[EAR2] != null) total.add(mEquipments[EAR2].getStatus(level, type)); switch(type) { case D: case Delay: if (mEquipments[MAINWEAPON] != null) { if (mEquipments[MAINWEAPON].getWeaponType() == StatusType.SKILL_HANDTOHAND) { total.setAdditional(mEquipments[MAINWEAPON].getStatus(level, type).getAdditional()); } else { total.setValue(mEquipments[MAINWEAPON].getStatus(level, type).getAdditional()); } } break; case DSub: if (mEquipments[SUBWEAPON] != null) { total.setValue(mEquipments[SUBWEAPON].getStatus(level, StatusType.D).getAdditional()); } break; case DelaySub: if (mEquipments[SUBWEAPON] != null) { total.setValue(mEquipments[SUBWEAPON].getStatus(level, StatusType.Delay).getAdditional()); } break; case DRange: if (mEquipments[RANGE] != null) { total.setValue(mEquipments[RANGE].getStatus(level, StatusType.D).getAdditional()); if (mEquipments[ANMO] != null) total.setAdditional(mEquipments[ANMO].getStatus(level, StatusType.D).getAdditional()); } else if (mEquipments[ANMO] != null) total.setValue(mEquipments[ANMO].getStatus(level, StatusType.D).getAdditional()); break; case DelayRange: if (mEquipments[RANGE] != null) { total.setValue(mEquipments[RANGE].getStatus(level, StatusType.Delay).getAdditional()); if (mEquipments[ANMO] != null) total.setAdditional(mEquipments[ANMO].getStatus(level, StatusType.Delay).getAdditional()); } else if (mEquipments[ANMO] != null) total.setValue(mEquipments[ANMO].getStatus(level, StatusType.Delay).getAdditional()); break; default: if (mEquipments[MAINWEAPON] != null) total.add(mEquipments[MAINWEAPON].getStatus(level, type)); if (mEquipments[SUBWEAPON] != null) total.add(mEquipments[SUBWEAPON].getStatus(level, type)); if (mEquipments[RANGE] != null) total.add(mEquipments[RANGE].getStatus(level, type)); if (mEquipments[ANMO] != null) total.add(mEquipments[ANMO].getStatus(level, type)); } return total; } public Equipment getEquipment(int part) { return mEquipments[part]; } public void setEquipment(int part, long id, long augId) { mEquipments[part] = Dao.instantiateEquipment(id, augId); mNotModified = false; } public boolean reloadEquipments() { boolean updated = false; for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null) { mEquipments[i] = Dao.instantiateEquipment(mEquipments[i].getId(), mEquipments[i].getAugId()); updated = true; mNotModified = false; } } if (updated) { parseDescriptions(); if (mCombinations != null) { for (int i = 0; i < mCombinations.size(); i++) { Combination combi; combi = mCombinations.get(i); combi.parseDescription(); } } } return updated; } public long[] reloadEquipmentsForUpdatingDatabase() { boolean updated = false; long result[] = new long[mEquipments.length + 1]; for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null) { Equipment eq = Dao.instantiateEquipment(mEquipments[i].getId(), mEquipments[i].getAugId()); if (eq == null || !eq.getName().equals(mEquipments[i].getName())) { // find eq = Dao.findEquipment(mEquipments[i].getName(), mEquipments[i].getLevel(), mEquipments[i].getPart(), mEquipments[i].getWeapon()); if (eq != null) { mEquipments[i] = eq; updated = true; result[i] = -1; } else { result[i] = mEquipments[i].getId(); } } else { result[i] = -1; } } else { result[i] = -1; } } if (updated) { mNotModified = false; parseDescriptions(); if (mCombinations != null) { for (int i = 0; i < mCombinations.size(); i++) { Combination combi; combi = mCombinations.get(i); combi.parseDescription(); } } } result[EQUIPMENT_NUM] = updated ? 1 : 0; return result; } public boolean reloadAugmentsIfChangesThere() { boolean updated = false; for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null) { if (mEquipments[i].getAugId() >= 0) { Equipment eq = Dao.instantiateEquipment(mEquipments[i].getId(), mEquipments[i].getAugId()); if (mEquipments[i].getId() != eq.getId()) { updated = true; mEquipments[i] = eq; } } } } if (updated) { parseDescriptions(); if (mCombinations != null) { for (int i = 0; i < mCombinations.size(); i++) { Combination combi; combi = mCombinations.get(i); combi.parseDescription(); } } } return updated; } public SortedStringList getUnknownTokens() { SortedStringList unknownTokens = new SortedStringList(); for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null) { unknownTokens.mergeList(mEquipments[i].getUnknownTokens()); } } if (mCombinations != null) { for (int i = 0; i < mCombinations.size(); i++) { unknownTokens.mergeList(mCombinations.get(i).getUnknownTokens()); } } return unknownTokens; } private void parseDescriptions() { boolean updated; int notequiped; if (mNotModified) return; mNotModified = false; updated = false; notequiped = 0; for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null) { updated = mEquipments[i].parseDescription() || updated; mEquipments[i].removeCombinationToken(); mEquipments[i].removeAugmentCommentFromUnknownToken(); } else { notequiped++; } } - if (notequiped == mEquipments.length) { - mCombinations = null; + if (notequiped > 0) { + if (notequiped == mEquipments.length) + mCombinations = null; + else + updated = true; } if (updated) { // check combination boolean used[] = new boolean[EQUIPMENT_NUM]; mCombinations = new ArrayList<Combination>(); for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null && used[i] == false) { long combiID; int numMatches; Combination combi; combiID = mEquipments[i].getCombinationID(); if (combiID > 0) { numMatches = 1; for (int ii = i + 1; ii < mEquipments.length; ii++) { if (mEquipments[ii] != null && used[ii] == false && mEquipments[ii].getCombinationID() == combiID) { numMatches++; } } if (numMatches > 1) { // instantiate combi = Dao.instantiateCombination(combiID, numMatches); if (combi != null) { mCombinations.add(combi); for (int ii = i; ii < mEquipments.length; ii++) { if (mEquipments[ii] != null && used[ii] == false && mEquipments[ii].getCombinationID() == combiID) { used[ii] = true; } } } } } else { used[i] = true; } } else { used[i] = true; } } // Check all combination they are not used... int maxCombi = 0; int parts[]; // check free parts. for (int i = 0; i < mEquipments.length; i++) { if (used[i] == false) { maxCombi++; } } parts = new int[maxCombi]; for (int n = 0, i = 0; i < mEquipments.length; i++) { if (used[i] == false) { parts[n++] = i; } } if (maxCombi > 1) { for (int match = maxCombi; match > 1; match--) { for (int n = 3; n < (1 << maxCombi); n++) { /* Number 3 is first value that has two bits. */ int bits = 0; // count bits for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { if (used[parts[i]] == false) { bits++; } } } if (bits == match) { // check this combination String names[] = new String[match]; int ii = 0; for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { if (used[parts[i]] == false) { names[ii++] = mEquipments[parts[i]].getName(); } } } // instantiate Combination combi = Dao.searchCombination(names); if (combi != null) { mCombinations.add(combi); for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { used[parts[i]] = true; } } } } } } } } } }
true
true
private void parseDescriptions() { boolean updated; int notequiped; if (mNotModified) return; mNotModified = false; updated = false; notequiped = 0; for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null) { updated = mEquipments[i].parseDescription() || updated; mEquipments[i].removeCombinationToken(); mEquipments[i].removeAugmentCommentFromUnknownToken(); } else { notequiped++; } } if (notequiped == mEquipments.length) { mCombinations = null; } if (updated) { // check combination boolean used[] = new boolean[EQUIPMENT_NUM]; mCombinations = new ArrayList<Combination>(); for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null && used[i] == false) { long combiID; int numMatches; Combination combi; combiID = mEquipments[i].getCombinationID(); if (combiID > 0) { numMatches = 1; for (int ii = i + 1; ii < mEquipments.length; ii++) { if (mEquipments[ii] != null && used[ii] == false && mEquipments[ii].getCombinationID() == combiID) { numMatches++; } } if (numMatches > 1) { // instantiate combi = Dao.instantiateCombination(combiID, numMatches); if (combi != null) { mCombinations.add(combi); for (int ii = i; ii < mEquipments.length; ii++) { if (mEquipments[ii] != null && used[ii] == false && mEquipments[ii].getCombinationID() == combiID) { used[ii] = true; } } } } } else { used[i] = true; } } else { used[i] = true; } } // Check all combination they are not used... int maxCombi = 0; int parts[]; // check free parts. for (int i = 0; i < mEquipments.length; i++) { if (used[i] == false) { maxCombi++; } } parts = new int[maxCombi]; for (int n = 0, i = 0; i < mEquipments.length; i++) { if (used[i] == false) { parts[n++] = i; } } if (maxCombi > 1) { for (int match = maxCombi; match > 1; match--) { for (int n = 3; n < (1 << maxCombi); n++) { /* Number 3 is first value that has two bits. */ int bits = 0; // count bits for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { if (used[parts[i]] == false) { bits++; } } } if (bits == match) { // check this combination String names[] = new String[match]; int ii = 0; for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { if (used[parts[i]] == false) { names[ii++] = mEquipments[parts[i]].getName(); } } } // instantiate Combination combi = Dao.searchCombination(names); if (combi != null) { mCombinations.add(combi); for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { used[parts[i]] = true; } } } } } } } } }
private void parseDescriptions() { boolean updated; int notequiped; if (mNotModified) return; mNotModified = false; updated = false; notequiped = 0; for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null) { updated = mEquipments[i].parseDescription() || updated; mEquipments[i].removeCombinationToken(); mEquipments[i].removeAugmentCommentFromUnknownToken(); } else { notequiped++; } } if (notequiped > 0) { if (notequiped == mEquipments.length) mCombinations = null; else updated = true; } if (updated) { // check combination boolean used[] = new boolean[EQUIPMENT_NUM]; mCombinations = new ArrayList<Combination>(); for (int i = 0; i < mEquipments.length; i++) { if (mEquipments[i] != null && used[i] == false) { long combiID; int numMatches; Combination combi; combiID = mEquipments[i].getCombinationID(); if (combiID > 0) { numMatches = 1; for (int ii = i + 1; ii < mEquipments.length; ii++) { if (mEquipments[ii] != null && used[ii] == false && mEquipments[ii].getCombinationID() == combiID) { numMatches++; } } if (numMatches > 1) { // instantiate combi = Dao.instantiateCombination(combiID, numMatches); if (combi != null) { mCombinations.add(combi); for (int ii = i; ii < mEquipments.length; ii++) { if (mEquipments[ii] != null && used[ii] == false && mEquipments[ii].getCombinationID() == combiID) { used[ii] = true; } } } } } else { used[i] = true; } } else { used[i] = true; } } // Check all combination they are not used... int maxCombi = 0; int parts[]; // check free parts. for (int i = 0; i < mEquipments.length; i++) { if (used[i] == false) { maxCombi++; } } parts = new int[maxCombi]; for (int n = 0, i = 0; i < mEquipments.length; i++) { if (used[i] == false) { parts[n++] = i; } } if (maxCombi > 1) { for (int match = maxCombi; match > 1; match--) { for (int n = 3; n < (1 << maxCombi); n++) { /* Number 3 is first value that has two bits. */ int bits = 0; // count bits for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { if (used[parts[i]] == false) { bits++; } } } if (bits == match) { // check this combination String names[] = new String[match]; int ii = 0; for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { if (used[parts[i]] == false) { names[ii++] = mEquipments[parts[i]].getName(); } } } // instantiate Combination combi = Dao.searchCombination(names); if (combi != null) { mCombinations.add(combi); for (int i = 0; i < maxCombi; i++) { if ((n & (1 << i)) != 0) { used[parts[i]] = true; } } } } } } } } }
diff --git a/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java b/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java index 7ccf9ff2a3..9047d05f57 100644 --- a/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java +++ b/plugins/org.bonitasoft.studio.engine/src/org/bonitasoft/studio/engine/export/switcher/FlowElementSwitch.java @@ -1,769 +1,769 @@ /** * Copyright (C) 2012 BonitaSoft S.A. * BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2.0 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.studio.engine.export.switcher; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import org.bonitasoft.engine.bpm.flownode.GatewayType; import org.bonitasoft.engine.bpm.flownode.TaskPriority; import org.bonitasoft.engine.bpm.flownode.TimerType; import org.bonitasoft.engine.bpm.process.impl.ActivityDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.AutomaticTaskDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.BoundaryEventDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.CallActivityBuilder; import org.bonitasoft.engine.bpm.process.impl.CatchMessageEventTriggerDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.EndEventDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.FlowElementBuilder; import org.bonitasoft.engine.bpm.process.impl.GatewayDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.IntermediateCatchEventDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.IntermediateThrowEventDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.MultiInstanceLoopCharacteristicsBuilder; import org.bonitasoft.engine.bpm.process.impl.ProcessDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.ReceiveTaskDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.SendTaskDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.StartEventDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.SubProcessDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.ThrowMessageEventTriggerBuilder; import org.bonitasoft.engine.bpm.process.impl.UserFilterDefinitionBuilder; import org.bonitasoft.engine.bpm.process.impl.UserTaskDefinitionBuilder; import org.bonitasoft.engine.expression.ExpressionBuilder; import org.bonitasoft.engine.expression.ExpressionInterpreter; import org.bonitasoft.engine.expression.ExpressionType; import org.bonitasoft.engine.expression.InvalidExpressionException; import org.bonitasoft.engine.operation.LeftOperandBuilder; import org.bonitasoft.engine.operation.OperationBuilder; import org.bonitasoft.engine.operation.OperatorType; import org.bonitasoft.studio.common.ExpressionConstants; import org.bonitasoft.studio.common.TimerUtil; import org.bonitasoft.studio.common.emf.tools.ModelHelper; import org.bonitasoft.studio.common.log.BonitaStudioLog; import org.bonitasoft.studio.engine.export.EngineExpressionUtil; import org.bonitasoft.studio.model.connectorconfiguration.ConnectorParameter; import org.bonitasoft.studio.model.expression.AbstractExpression; import org.bonitasoft.studio.model.expression.Expression; import org.bonitasoft.studio.model.expression.ListExpression; import org.bonitasoft.studio.model.expression.Operation; import org.bonitasoft.studio.model.process.AbstractCatchMessageEvent; import org.bonitasoft.studio.model.process.AbstractTimerEvent; import org.bonitasoft.studio.model.process.Activity; import org.bonitasoft.studio.model.process.ActorFilter; import org.bonitasoft.studio.model.process.BoundaryEvent; import org.bonitasoft.studio.model.process.BoundaryMessageEvent; import org.bonitasoft.studio.model.process.BoundarySignalEvent; import org.bonitasoft.studio.model.process.BoundaryTimerEvent; import org.bonitasoft.studio.model.process.CallActivity; import org.bonitasoft.studio.model.process.Connection; import org.bonitasoft.studio.model.process.Data; import org.bonitasoft.studio.model.process.Element; import org.bonitasoft.studio.model.process.EndErrorEvent; import org.bonitasoft.studio.model.process.EndEvent; import org.bonitasoft.studio.model.process.EndMessageEvent; import org.bonitasoft.studio.model.process.EndSignalEvent; import org.bonitasoft.studio.model.process.EndTerminatedEvent; import org.bonitasoft.studio.model.process.FlowElement; import org.bonitasoft.studio.model.process.InputMapping; import org.bonitasoft.studio.model.process.IntermediateCatchMessageEvent; import org.bonitasoft.studio.model.process.IntermediateCatchSignalEvent; import org.bonitasoft.studio.model.process.IntermediateCatchTimerEvent; import org.bonitasoft.studio.model.process.IntermediateErrorCatchEvent; import org.bonitasoft.studio.model.process.IntermediateThrowMessageEvent; import org.bonitasoft.studio.model.process.IntermediateThrowSignalEvent; import org.bonitasoft.studio.model.process.Lane; import org.bonitasoft.studio.model.process.Message; import org.bonitasoft.studio.model.process.MultiInstantiation; import org.bonitasoft.studio.model.process.NonInterruptingBoundaryTimerEvent; import org.bonitasoft.studio.model.process.OperationContainer; import org.bonitasoft.studio.model.process.OutputMapping; import org.bonitasoft.studio.model.process.Pool; import org.bonitasoft.studio.model.process.ProcessPackage; import org.bonitasoft.studio.model.process.ReceiveTask; import org.bonitasoft.studio.model.process.SearchIndex; import org.bonitasoft.studio.model.process.SendTask; import org.bonitasoft.studio.model.process.SourceElement; import org.bonitasoft.studio.model.process.StartErrorEvent; import org.bonitasoft.studio.model.process.StartEvent; import org.bonitasoft.studio.model.process.StartMessageEvent; import org.bonitasoft.studio.model.process.StartSignalEvent; import org.bonitasoft.studio.model.process.StartTimerEvent; import org.bonitasoft.studio.model.process.SubProcessEvent; import org.bonitasoft.studio.model.process.Task; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.EcoreUtil; /** * @author Romain Bioteau * */ public class FlowElementSwitch extends AbstractSwitch { private FlowElementBuilder builder; public FlowElementSwitch(FlowElementBuilder processBuilder,Set<EObject> eObjectNotExported){ super(eObjectNotExported) ; this.builder = processBuilder; } @Override public Element caseSubProcessEvent(SubProcessEvent subProcessEvent) { final SubProcessDefinitionBuilder subProcessBuilder = builder.addSubProcess(subProcessEvent.getName(), true).getSubProcessBuilder(); final FlowElementSwitch subProcessSwitch = new FlowElementSwitch(subProcessBuilder, eObjectNotExported); List<FlowElement> flowElements = ModelHelper.getAllItemsOfType(subProcessEvent, ProcessPackage.Literals.FLOW_ELEMENT); for (FlowElement flowElement : flowElements) { if(!eObjectNotExported.contains(flowElement)){ subProcessSwitch.doSwitch(flowElement); } } List<SourceElement> sourceElements = ModelHelper.getAllItemsOfType(subProcessEvent, ProcessPackage.Literals.SOURCE_ELEMENT); SequenceFlowSwitch sequenceFlowSwitch = new SequenceFlowSwitch(subProcessBuilder) ; for (SourceElement sourceElement : sourceElements) { for (Connection connection : sourceElement.getOutgoing()) { sequenceFlowSwitch.doSwitch(connection); } } return subProcessEvent; } @Override public Activity caseActivity(final Activity activity) { AutomaticTaskDefinitionBuilder taskBuilder = builder.addAutomaticTask(activity.getName()); handleCommonActivity(activity, taskBuilder); return activity; } @Override public Element caseSendTask(SendTask senTask) { org.bonitasoft.engine.expression.Expression targetProcess = null; String messageName = null; Message message = null; - if(senTask.getEvents().isEmpty()){ + if(!senTask.getEvents().isEmpty()){ message = senTask.getEvents().get(0); targetProcess = EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetProcessExpression()); } final SendTaskDefinitionBuilder taskBuilder = ((ProcessDefinitionBuilder)builder).addSendTask(senTask.getName(), messageName, targetProcess); if(message != null){ taskBuilder.setTargetFlowNode(EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetElementExpression())); if(message.getMessageContent() != null){ for(ListExpression row : message.getMessageContent().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; org.bonitasoft.studio.model.expression.Expression idExp = col.get(0); org.bonitasoft.studio.model.expression.Expression messageContentExp = col.get(1) ; if(col.size()==2){ if (idExp.getContent()!=null && !idExp.getContent().isEmpty() && messageContentExp.getContent()!=null && !messageContentExp.getContent().isEmpty()){ taskBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ; } } } } if(message.getCorrelation() != null){ for(ListExpression row : message.getCorrelation().getCorrelationAssociation().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; if(col.size() == 2){ org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0); org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1); if(correlationKeyExp.getContent() != null && !correlationKeyExp.getContent().isEmpty() && valueExpression.getContent() != null && !valueExpression.getContent().isEmpty()){ taskBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ; } } } } } handleCommonActivity(senTask, taskBuilder); return senTask; } @Override public Element caseReceiveTask(ReceiveTask receiveTask) { String messageName = receiveTask.getEvent(); final ReceiveTaskDefinitionBuilder taskBuilder = builder.addReceiveTask(receiveTask.getName(), messageName); if(messageName != null){ for(Operation operation : receiveTask.getMessageContent()){ taskBuilder.addOperation(EngineExpressionUtil.createOperationForMessageContent(operation)) ; } if(receiveTask.getCorrelation() != null){ for(ListExpression row : receiveTask.getCorrelation().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; if(col.size() == 2){ org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0); org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1); if(correlationKeyExp.getContent() != null && !correlationKeyExp.getContent().isEmpty() && valueExpression.getContent() != null && !valueExpression.getContent().isEmpty()){ taskBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ; } } } } } handleCommonActivity(receiveTask, taskBuilder); return receiveTask; } @Override public FlowElement caseStartMessageEvent(StartMessageEvent object) { StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(object.getName()) ; String message = object.getEvent() ; if(message != null){ CatchMessageEventTriggerDefinitionBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message) ; for(Operation operation : object.getMessageContent()){ triggerBuilder.addOperation(EngineExpressionUtil.createOperationForMessageContent(operation)) ; } } addDescription(eventBuilder, object.getDocumentation()) ; return object; } @Override public FlowElement caseIntermediateCatchMessageEvent(IntermediateCatchMessageEvent object) { IntermediateCatchEventDefinitionBuilder eventBuilder = builder.addIntermediateCatchEvent(object.getName()) ; String message = object.getEvent() ; if(message != null){ CatchMessageEventTriggerDefinitionBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message) ; addMessageContent(object, triggerBuilder); addMessageCorrelation(object, triggerBuilder); } addDescription(eventBuilder, object.getDocumentation()) ; return object; } private void addMessageContent(AbstractCatchMessageEvent messageEvent, CatchMessageEventTriggerDefinitionBuilder triggerBuilder) { for(Operation operation : messageEvent.getMessageContent()){ triggerBuilder.addOperation(EngineExpressionUtil.createOperationForMessageContent(operation)) ; } } private void addMessageCorrelation(AbstractCatchMessageEvent messageEvent, CatchMessageEventTriggerDefinitionBuilder triggerBuilder){ if(messageEvent.getCorrelation() != null){ for(ListExpression row : messageEvent.getCorrelation().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; if(col.size() == 2){ org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0); org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1); if(correlationKeyExp.getContent() != null && !correlationKeyExp.getContent().isEmpty() && valueExpression.getContent() != null && !valueExpression.getContent().isEmpty()){ triggerBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ; } } } } } @Override public FlowElement caseIntermediateThrowMessageEvent(IntermediateThrowMessageEvent object) { IntermediateThrowEventDefinitionBuilder eventBuilder = builder.addIntermediateThrowEvent(object.getName()) ; for(Message message : object.getEvents()){ ThrowMessageEventTriggerBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message.getName(),EngineExpressionUtil.createExpression(message.getTargetProcessExpression()),EngineExpressionUtil.createExpression(message.getTargetElementExpression())) ; if(message.getMessageContent() != null){ addThrowMessageContent(message, triggerBuilder); } if(message.getCorrelation() != null){ addThrowMessageCorrelation(message, triggerBuilder); } } addDescription(eventBuilder, object.getDocumentation()) ; return object; } protected void addThrowMessageCorrelation(Message message, ThrowMessageEventTriggerBuilder triggerBuilder) { for(ListExpression row : message.getCorrelation().getCorrelationAssociation().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; if(col.size() == 2){ org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0); org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1); if(correlationKeyExp.getContent() != null && !correlationKeyExp.getContent().isEmpty() && valueExpression.getContent() != null && !valueExpression.getContent().isEmpty()){ triggerBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ; } } } } protected void addThrowMessageContent(Message message, ThrowMessageEventTriggerBuilder triggerBuilder) { for(ListExpression row : message.getMessageContent().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; org.bonitasoft.studio.model.expression.Expression idExp = col.get(0); org.bonitasoft.studio.model.expression.Expression messageContentExp = col.get(1) ; if(col.size()==2){ if (idExp.getContent()!=null && !idExp.getContent().isEmpty() && messageContentExp.getContent()!=null && !messageContentExp.getContent().isEmpty()){ triggerBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ; } } } } @Override public FlowElement caseEndMessageEvent(EndMessageEvent object) { EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(object.getName()) ; for(Message message : object.getEvents()){ ThrowMessageEventTriggerBuilder triggerBuilder = eventBuilder.addMessageEventTrigger(message.getName(),EngineExpressionUtil.createExpression(message.getTargetProcessExpression()),EngineExpressionUtil.createExpression(message.getTargetElementExpression())) ; if(message.getMessageContent() != null){ for(ListExpression row : message.getMessageContent().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; if(col.size()==2){ org.bonitasoft.studio.model.expression.Expression idExp=col.get(0); org.bonitasoft.studio.model.expression.Expression messageContentExp =col.get(1); if (idExp.getContent()!=null && !idExp.getContent().isEmpty() && messageContentExp.getContent()!=null && !messageContentExp.getContent().isEmpty()){ triggerBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ; } } } } if(message.getCorrelation() != null){ addThrowMessageCorrelation(message, triggerBuilder); } } addDescription(eventBuilder, object.getDocumentation()) ; return object; } @Override public Element caseStartSignalEvent(StartSignalEvent object) { StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(object.getName()) ; String signal = object.getSignalCode() ; if(signal != null){ eventBuilder.addSignalEventTrigger(signal) ; } addDescription(eventBuilder, object.getDocumentation()) ; return object; } @Override public EndSignalEvent caseEndSignalEvent(EndSignalEvent object) { EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(object.getName()) ; String signalCode = object.getSignalCode() ; if(signalCode != null){ eventBuilder.addSignalEventTrigger(signalCode) ; } addDescription(eventBuilder, object.getDocumentation()) ; return object; } @Override public IntermediateCatchSignalEvent caseIntermediateCatchSignalEvent(IntermediateCatchSignalEvent object) { IntermediateCatchEventDefinitionBuilder eventBuilder = builder.addIntermediateCatchEvent(object.getName()) ; String signal = object.getSignalCode() ; if(signal != null){ eventBuilder.addSignalEventTrigger(signal) ; } addDescription(eventBuilder, object.getDocumentation()) ; return object; } @Override public IntermediateThrowSignalEvent caseIntermediateThrowSignalEvent(IntermediateThrowSignalEvent object) { IntermediateThrowEventDefinitionBuilder eventBuilder = builder.addIntermediateThrowEvent(object.getName()) ; String signal = object.getSignalCode() ; if(signal != null){ eventBuilder.addSignalEventTrigger(signal) ; } addDescription(eventBuilder, object.getDocumentation()) ; return object; } @Override public CallActivity caseCallActivity(CallActivity object) { Expression version = object.getCalledActivityVersion() ; if(version == null || version.getContent() == null || version.getContent().trim().isEmpty()){ version = null ; //latest version will be used by the engine } final CallActivityBuilder activityBuilder = builder.addCallActivity(object.getName(), EngineExpressionUtil.createExpression(object.getCalledActivityName()), EngineExpressionUtil.createExpression(version)) ; for(InputMapping mapping : object.getInputMappings()){ final OperationBuilder opBuilder = new OperationBuilder(); opBuilder.createNewInstance(); opBuilder.setRightOperand(EngineExpressionUtil.createVariableExpression(mapping.getProcessSource())); final LeftOperandBuilder builder = new LeftOperandBuilder() ; builder.createNewInstance() ; builder.setName(mapping.getSubprocessTarget()) ; opBuilder.setLeftOperand(builder.done()); opBuilder.setType(OperatorType.ASSIGNMENT); activityBuilder.addDataInputOperation(opBuilder.done()); } for(OutputMapping mapping : object.getOutputMappings()){ final OperationBuilder opBuilder = new OperationBuilder(); opBuilder.createNewInstance(); final Data d = EcoreUtil.copy(mapping.getProcessTarget()); d.setName(mapping.getSubprocessSource()); opBuilder.setRightOperand(EngineExpressionUtil.createVariableExpression(d)); final LeftOperandBuilder builder = new LeftOperandBuilder() ; builder.createNewInstance() ; builder.setName(mapping.getProcessTarget().getName()) ; opBuilder.setLeftOperand(builder.done()); opBuilder.setType(OperatorType.ASSIGNMENT); activityBuilder.addDataOutputOperation(opBuilder.done()); } handleCommonActivity(object, activityBuilder) ; return object ; } @Override public Task caseTask(final Task task) { String actor = null; ActorFilter filter = null ; if(!task.getFilters().isEmpty()){ filter = task.getFilters().get(0) ; } if(task.isOverrideActorsOfTheLane()){ if (task.getActor() != null) { actor = task.getActor().getName(); } }else{ final Lane lane = ModelHelper.getParentLane(task) ; if(lane != null && lane.getActor() != null){ actor = lane.getActor().getName(); } if(task.getFilters().isEmpty() && !lane.getFilters().isEmpty()){ filter = lane.getFilters().get(0) ; } } final UserTaskDefinitionBuilder taskBuilder = builder.addUserTask(task.getName(), actor); handleCommonActivity(task, taskBuilder) ; taskBuilder.addPriority(TaskPriority.values()[task.getPriority()].name()) ; addExpectedDuration(taskBuilder,task) ; if(filter != null){ final UserFilterDefinitionBuilder filterBuilder = taskBuilder.addUserFilter(filter.getName(), filter.getDefinitionId(),filter.getDefinitionVersion()) ; for(ConnectorParameter parameter : filter.getConfiguration().getParameters()){ filterBuilder.addInput(parameter.getKey(), EngineExpressionUtil.createExpression(parameter.getExpression())) ; } } return task; } @Override public StartEvent caseStartEvent(final StartEvent startEvent) { StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(startEvent.getName()); addDescription(eventBuilder, startEvent.getDocumentation()) ; return startEvent; } @Override public FlowElement caseStartTimerEvent(final StartTimerEvent startTimer) { StartEventDefinitionBuilder startTimerBuilder = builder.addStartEvent(startTimer.getName()); if(ModelHelper.isInEvenementialSubProcessPool(startTimer)){ TimerType timerType = getTimerType(startTimer); if(timerType != null){ startTimerBuilder.addTimerEventTriggerDefinition(timerType, EngineExpressionUtil.createExpression(startTimer.getCondition())); } }else{ ExpressionBuilder expressionBuilder = new ExpressionBuilder().createNewInstance(startTimer.getName()+"_startCondition"); expressionBuilder.setContent(TimerUtil.getTimerExpressionContent(startTimer)); if(TimerUtil.isCycle(startTimer)){ if(TimerUtil.isScript(startTimer)){ expressionBuilder.setExpressionType(ExpressionType.TYPE_READ_ONLY_SCRIPT.name()); expressionBuilder.setInterpreter(ExpressionInterpreter.GROOVY.name()); expressionBuilder.setReturnType(Date.class.getName()); }else{ expressionBuilder.setExpressionType(ExpressionType.TYPE_CONSTANT.name()); expressionBuilder.setReturnType(String.class.getName()); } try { startTimerBuilder.addTimerEventTriggerDefinition(TimerType.CYCLE, expressionBuilder.done()); } catch (InvalidExpressionException e) { throw new RuntimeException(e); } }else{ expressionBuilder.setExpressionType(ExpressionType.TYPE_READ_ONLY_SCRIPT.name()); expressionBuilder.setInterpreter(ExpressionInterpreter.GROOVY.name()); expressionBuilder.setReturnType(Date.class.getName()); try { startTimerBuilder.addTimerEventTriggerDefinition(TimerType.DATE, expressionBuilder.done()); } catch (InvalidExpressionException e) { throw new RuntimeException(e); } } } addDescription(startTimerBuilder, startTimer.getDocumentation()) ; return startTimer; } @Override public FlowElement caseIntermediateCatchTimerEvent(IntermediateCatchTimerEvent timer) { IntermediateCatchEventDefinitionBuilder timerBuilder = builder.addIntermediateCatchEvent(timer.getName()); TimerType timerType = getTimerType(timer); if(timerType != null){ timerBuilder.addTimerEventTriggerDefinition(timerType, EngineExpressionUtil.createExpression(timer.getCondition())); } addDescription(timerBuilder, timer.getDocumentation()) ; return timer; } private TimerType getTimerType(AbstractTimerEvent timer) { if(TimerUtil.isDuration(timer)){ return TimerType.DURATION; }else{ final String timerConditionReturnType = timer.getCondition().getReturnType(); try { if(Number.class.isAssignableFrom(Class.forName(timerConditionReturnType))){ return TimerType.DURATION; }else if(Date.class.getName().equals(timerConditionReturnType)){ return TimerType.DATE; } } catch (ClassNotFoundException e) { BonitaStudioLog.error(e); } } BonitaStudioLog.error("Timer type can't be defined for timer "+timer.getName()+". You might use a wrong return type. ", "org.bonitasoft.studio.engine"); return null; } @Override public FlowElement caseEndEvent(final EndEvent endEvent) { final EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(endEvent.getName()); addDescription(eventBuilder, endEvent.getDocumentation()) ; return endEvent; } @Override public Element caseStartErrorEvent(StartErrorEvent startErrorEvent) { StartEventDefinitionBuilder eventBuilder = builder.addStartEvent(startErrorEvent.getName()); eventBuilder.addErrorEventTrigger(startErrorEvent.getErrorCode()); addDescription(eventBuilder, startErrorEvent.getDocumentation()) ; return startErrorEvent; } @Override public Element caseEndErrorEvent(EndErrorEvent endErrorEvent) { EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(endErrorEvent.getName()); eventBuilder.addErrorEventTrigger(endErrorEvent.getErrorCode()); addDescription(eventBuilder, endErrorEvent.getDocumentation()) ; return endErrorEvent; } @Override public FlowElement caseEndTerminatedEvent(final EndTerminatedEvent endTerminatedEvent) { EndEventDefinitionBuilder eventBuilder = builder.addEndEvent(endTerminatedEvent.getName()); eventBuilder.addTerminateEventTrigger(); addDescription(eventBuilder, endTerminatedEvent.getDocumentation()) ; return endTerminatedEvent; } @Override public FlowElement caseANDGateway(final org.bonitasoft.studio.model.process.ANDGateway gateway) { builder.addGateway(gateway.getName(), GatewayType.PARALLEL); // addDescription(gatewayBuilder, gateway.getDocumentation()) ; return gateway; } @Override public FlowElement caseInclusiveGateway(final org.bonitasoft.studio.model.process.InclusiveGateway gateway) { builder.addGateway(gateway.getName(), GatewayType.INCLUSIVE); return gateway; } @Override public FlowElement caseXORGateway(final org.bonitasoft.studio.model.process.XORGateway gateway) { final GatewayDefinitionBuilder gatewayBuilder = builder.addGateway(gateway.getName(), GatewayType.EXCLUSIVE); // addDescription(gatewayBuilder, gateway.getDocumentation()) ; return gateway; } protected void handleCommonActivity(final Activity activity, ActivityDefinitionBuilder taskBuilder) { addData(taskBuilder, activity); addOperation(taskBuilder, activity) ; addLoop(taskBuilder,activity) ; addConnector(taskBuilder,activity) ; addKPIBinding(taskBuilder, activity); addDisplayTitle(taskBuilder, activity) ; addDescription(taskBuilder, activity.getDocumentation()) ; addDisplayDescription(taskBuilder,activity) ; addDisplayDescriptionAfterCompletion(taskBuilder,activity) ; addMultiInstantiation(taskBuilder,activity); addBoundaryEvents(taskBuilder, activity); addDescription(taskBuilder, activity.getDocumentation()); } private void addBoundaryEvents(ActivityDefinitionBuilder taskBuilder, Activity activity) { for(BoundaryEvent boundaryEvent :activity.getBoundaryIntermediateEvents()){ BoundaryEventDefinitionBuilder boundaryEventBuilder = taskBuilder.addBoundaryEvent(boundaryEvent.getName(),!(boundaryEvent instanceof NonInterruptingBoundaryTimerEvent)); if(boundaryEvent instanceof IntermediateErrorCatchEvent){ String errorCode = ((IntermediateErrorCatchEvent) boundaryEvent).getErrorCode(); if(errorCode != null && errorCode.trim().isEmpty()){ errorCode = null; } boundaryEventBuilder.addErrorEventTrigger(errorCode); } else if(boundaryEvent instanceof BoundaryMessageEvent){ CatchMessageEventTriggerDefinitionBuilder catchMessageEventTriggerDefinitionBuilder = boundaryEventBuilder.addMessageEventTrigger(((BoundaryMessageEvent) boundaryEvent).getEvent()); addMessageContent((BoundaryMessageEvent)boundaryEvent, catchMessageEventTriggerDefinitionBuilder); } else if(boundaryEvent instanceof BoundaryTimerEvent){ TimerType timerType = getTimerType((BoundaryTimerEvent) boundaryEvent); if(timerType != null){ boundaryEventBuilder.addTimerEventTriggerDefinition(timerType, EngineExpressionUtil.createExpression(((AbstractTimerEvent) boundaryEvent).getCondition())); } } else if(boundaryEvent instanceof BoundarySignalEvent){ boundaryEventBuilder.addSignalEventTrigger(((BoundarySignalEvent) boundaryEvent).getSignalCode()); } } } protected void addMultiInstantiation( ActivityDefinitionBuilder taskBuilder , final Activity activity) { if(activity.isIsMultiInstance()){ final MultiInstantiation multiInstantiation = activity.getMultiInstantiation(); final Expression completionCondition = multiInstantiation.getCompletionCondition(); if(multiInstantiation.isUseCardinality()){ final Expression cardinality = multiInstantiation.getCardinality(); if(cardinality != null && cardinality.getContent() != null && !cardinality.getContent().isEmpty()){ MultiInstanceLoopCharacteristicsBuilder multiInstanceBuilder = taskBuilder.addMultiInstance(multiInstantiation.isSequential(), EngineExpressionUtil.createExpression(cardinality)); if(completionCondition != null && completionCondition.getContent() != null && !completionCondition.getContent().isEmpty()){ multiInstanceBuilder.addCompletionCondition(EngineExpressionUtil.createExpression(completionCondition)); } } } else { final Data collectionDataToMultiInstantiate = multiInstantiation.getCollectionDataToMultiInstantiate(); if(collectionDataToMultiInstantiate != null){ MultiInstanceLoopCharacteristicsBuilder multiInstanceBuilder = taskBuilder.addMultiInstance(multiInstantiation.isSequential(), collectionDataToMultiInstantiate.getName()); if(completionCondition != null && completionCondition.getContent() != null && !completionCondition.getContent().isEmpty()){ multiInstanceBuilder.addCompletionCondition(EngineExpressionUtil.createExpression(completionCondition)); } final Data inputData = multiInstantiation.getInputData(); if(inputData != null){ multiInstanceBuilder.addDataInputItemRef(inputData.getName()); } final Data outputData = multiInstantiation.getOutputData(); if(outputData != null) { multiInstanceBuilder.addDataOutputItemRef(outputData.getName()); } Data listDataContainingOutputResults = multiInstantiation.getListDataContainingOutputResults(); if(listDataContainingOutputResults != null){ multiInstanceBuilder.addLoopDataOutputRef(listDataContainingOutputResults.getName()); } } } } } protected void addExpectedDuration(UserTaskDefinitionBuilder taskBuilder, Task task) { final String duration = task.getDuration() ; if(duration != null && !duration.isEmpty()){ try{ taskBuilder.addExpectedDuration(Long.parseLong(duration)) ; }catch (NumberFormatException e) { BonitaStudioLog.error(e) ; } } } protected void addDisplayDescription(ActivityDefinitionBuilder builder, FlowElement flowElement) { org.bonitasoft.engine.expression.Expression exp = EngineExpressionUtil.createExpression(flowElement.getDynamicDescription()) ; if(exp != null){ builder.addDisplayDescription(exp) ; } } protected void addDisplayDescriptionAfterCompletion(ActivityDefinitionBuilder builder, FlowElement flowElement){ org.bonitasoft.engine.expression.Expression exp = EngineExpressionUtil.createExpression(flowElement.getStepSummary()) ; if(exp != null){ builder.addDisplayDescriptionAfterCompletion(exp) ; } } protected void addDisplayTitle(ActivityDefinitionBuilder builder, FlowElement flowElement) { org.bonitasoft.engine.expression.Expression exp = EngineExpressionUtil.createExpression(flowElement.getDynamicLabel()) ; if(exp != null){ builder.addDisplayName(exp) ; } } protected void addOperation(ActivityDefinitionBuilder builder,OperationContainer activity) { for(Operation operation : activity.getOperations()){ String inputType = null ; if(!operation.getOperator().getInputTypes().isEmpty()){ inputType = operation.getOperator().getInputTypes().get(0) ; } if(operation.getLeftOperand() != null && operation.getLeftOperand().getContent() != null && operation.getRightOperand() != null && operation.getRightOperand().getContent() != null){ if (ExpressionConstants.SEARCH_INDEX_TYPE.equals(operation.getLeftOperand().getType())){ // get the pool to get the list of searchIndex list Pool pool = null; if(activity.eContainer() instanceof Pool){ pool = (Pool) activity.eContainer(); }else if(activity.eContainer().eContainer() instanceof Pool){ pool = (Pool) activity.eContainer().eContainer(); } // get the searchIndex list List<SearchIndex> searchIndexList = new ArrayList<SearchIndex>(); if(pool!=null){ searchIndexList = pool.getSearchIndexes(); } int idx=1; for(SearchIndex searchIdx : searchIndexList){ // get the related searchIndex to set the operation if(searchIdx.getName().getContent().equals(operation.getLeftOperand().getName())){ builder.addOperation(EngineExpressionUtil.createLeftOperandIndex(idx), OperatorType.STRING_INDEX, null, null, EngineExpressionUtil.createExpression(operation.getRightOperand())); break; } idx++; } } else { builder.addOperation(EngineExpressionUtil.createLeftOperand(operation.getLeftOperand()), OperatorType.valueOf(operation.getOperator().getType()), operation.getOperator().getExpression(),inputType, EngineExpressionUtil.createExpression(operation.getRightOperand())) ; } } } } protected void addLoop(ActivityDefinitionBuilder builder,Activity activity) { if(activity.getIsLoop()){ if(activity.getLoopCondition() != null){ builder.addLoop(activity.getTestBefore(), EngineExpressionUtil.createExpression(activity.getLoopCondition()), EngineExpressionUtil.createExpression(activity.getLoopMaximum())) ; } } } }
true
true
public Element caseSendTask(SendTask senTask) { org.bonitasoft.engine.expression.Expression targetProcess = null; String messageName = null; Message message = null; if(senTask.getEvents().isEmpty()){ message = senTask.getEvents().get(0); targetProcess = EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetProcessExpression()); } final SendTaskDefinitionBuilder taskBuilder = ((ProcessDefinitionBuilder)builder).addSendTask(senTask.getName(), messageName, targetProcess); if(message != null){ taskBuilder.setTargetFlowNode(EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetElementExpression())); if(message.getMessageContent() != null){ for(ListExpression row : message.getMessageContent().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; org.bonitasoft.studio.model.expression.Expression idExp = col.get(0); org.bonitasoft.studio.model.expression.Expression messageContentExp = col.get(1) ; if(col.size()==2){ if (idExp.getContent()!=null && !idExp.getContent().isEmpty() && messageContentExp.getContent()!=null && !messageContentExp.getContent().isEmpty()){ taskBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ; } } } } if(message.getCorrelation() != null){ for(ListExpression row : message.getCorrelation().getCorrelationAssociation().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; if(col.size() == 2){ org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0); org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1); if(correlationKeyExp.getContent() != null && !correlationKeyExp.getContent().isEmpty() && valueExpression.getContent() != null && !valueExpression.getContent().isEmpty()){ taskBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ; } } } } } handleCommonActivity(senTask, taskBuilder); return senTask; }
public Element caseSendTask(SendTask senTask) { org.bonitasoft.engine.expression.Expression targetProcess = null; String messageName = null; Message message = null; if(!senTask.getEvents().isEmpty()){ message = senTask.getEvents().get(0); targetProcess = EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetProcessExpression()); } final SendTaskDefinitionBuilder taskBuilder = ((ProcessDefinitionBuilder)builder).addSendTask(senTask.getName(), messageName, targetProcess); if(message != null){ taskBuilder.setTargetFlowNode(EngineExpressionUtil.createExpression((AbstractExpression) message.getTargetElementExpression())); if(message.getMessageContent() != null){ for(ListExpression row : message.getMessageContent().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; org.bonitasoft.studio.model.expression.Expression idExp = col.get(0); org.bonitasoft.studio.model.expression.Expression messageContentExp = col.get(1) ; if(col.size()==2){ if (idExp.getContent()!=null && !idExp.getContent().isEmpty() && messageContentExp.getContent()!=null && !messageContentExp.getContent().isEmpty()){ taskBuilder.addMessageContentExpression(EngineExpressionUtil.createExpression(idExp), EngineExpressionUtil.createExpression(messageContentExp)) ; } } } } if(message.getCorrelation() != null){ for(ListExpression row : message.getCorrelation().getCorrelationAssociation().getExpressions()){ List<org.bonitasoft.studio.model.expression.Expression> col = row.getExpressions() ; if(col.size() == 2){ org.bonitasoft.studio.model.expression.Expression correlationKeyExp = col.get(0); org.bonitasoft.studio.model.expression.Expression valueExpression = col.get(1); if(correlationKeyExp.getContent() != null && !correlationKeyExp.getContent().isEmpty() && valueExpression.getContent() != null && !valueExpression.getContent().isEmpty()){ taskBuilder.addCorrelation(EngineExpressionUtil.createExpression(correlationKeyExp), EngineExpressionUtil.createExpression(valueExpression)) ; } } } } } handleCommonActivity(senTask, taskBuilder); return senTask; }
diff --git a/patch/patch-core/src/test/java/org/fusesource/patch/impl/ServiceImplTest.java b/patch/patch-core/src/test/java/org/fusesource/patch/impl/ServiceImplTest.java index 42070f255..d965760eb 100644 --- a/patch/patch-core/src/test/java/org/fusesource/patch/impl/ServiceImplTest.java +++ b/patch/patch-core/src/test/java/org/fusesource/patch/impl/ServiceImplTest.java @@ -1,372 +1,374 @@ /** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.patch.impl; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import java.util.Set; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.Deflater; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.fusesource.patch.Patch; import org.fusesource.patch.Result; import org.junit.Before; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkListener; import org.osgi.framework.Version; import org.osgi.framework.wiring.FrameworkWiring; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; public class ServiceImplTest { File baseDir; File storage; File bundlev131; File bundlev132; File bundlev140; File patch132; File patch140; @Before public void setUp() throws Exception { URL base = getClass().getClassLoader().getResource("log4j.properties"); try { baseDir = new File(base.toURI()).getParentFile(); } catch(URISyntaxException e) { baseDir = new File(base.getPath()).getParentFile(); } generateData(); } private void generateData() throws Exception { storage = new File(baseDir, "storage"); delete(storage); storage.mkdirs(); bundlev131 = createBundle("my-bsn", "1.3.1"); bundlev132 = createBundle("my-bsn", "1.3.2"); bundlev140 = createBundle("my-bsn", "1.4.0"); patch132 = createPatch("patch-1.3.2", bundlev132); patch140 = createPatch("patch-1.4.0", bundlev140); } private File createPatch(String id, File bundle) throws Exception { File patchFile = new File(storage, "temp/" + id + ".zip"); File pd = new File(storage, "temp/" + id + "/" + id + ".patch"); pd.getParentFile().mkdirs(); Properties props = new Properties(); props.put("id", id); props.put("bundle.count", "1"); props.put("bundle.0", bundle.toURI().toURL().toString()); FileOutputStream fos = new FileOutputStream(pd); props.store(fos, null); fos.close(); fos = new FileOutputStream(patchFile); jarDir(pd.getParentFile(), fos); fos.close(); return patchFile; } private File createBundle(String bundleSymbolicName, String version) throws Exception { File jar = new File(storage, "temp/" + bundleSymbolicName + "-" + version + ".jar"); File man = new File(storage, "temp/" + bundleSymbolicName + "-" + version + "/META-INF/MANIFEST.MF"); man.getParentFile().mkdirs(); Manifest mf = new Manifest(); mf.getMainAttributes().putValue("Manifest-Version", "1.0"); mf.getMainAttributes().putValue("Bundle-ManifestVersion", "2"); mf.getMainAttributes().putValue("Bundle-SymbolicName", bundleSymbolicName); mf.getMainAttributes().putValue("Bundle-Version", version); FileOutputStream fos = new FileOutputStream(man); mf.write(fos); fos.close(); fos = new FileOutputStream(jar); jarDir(man.getParentFile().getParentFile(), fos); fos.close(); return jar; } @Test public void testPatch() throws Exception { BundleContext bundleContext = createMock(BundleContext.class); Bundle sysBundle = createMock(Bundle.class); BundleContext sysBundleContext = createMock(BundleContext.class); Bundle bundle = createMock(Bundle.class); Bundle bundle2 = createMock(Bundle.class); FrameworkWiring wiring = createMock(FrameworkWiring.class); // // Create a new service, download a patch // expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); ServiceImpl service = new ServiceImpl(bundleContext); Iterable<Patch> patches = service.download(patch132.toURI().toURL()); assertNotNull(patches); Iterator<Patch> it = patches.iterator(); assertTrue( it.hasNext() ); Patch patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); Iterator<String> itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Simulate the patch // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle }); expect(bundle.getSymbolicName()).andReturn("my-bsn"); expect(bundle.getVersion()).andReturn(new Version("1.3.1")); expect(bundle.getLocation()).andReturn("location"); + expect(bundle.getBundleId()).andReturn(123L); replay(sysBundleContext, sysBundle, bundleContext, bundle); Result result = patch.simulate(); assertNotNull( result ); assertNull( patch.getResult() ); assertTrue(result.isSimulation()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Recreate a new service and verify the downloaded patch is still available // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); service = new ServiceImpl(bundleContext); patches = service.getPatches(); assertNotNull(patches); it = patches.iterator(); assertTrue( it.hasNext() ); patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Install the patch // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle }); expect(bundle.getSymbolicName()).andReturn("my-bsn"); expect(bundle.getVersion()).andReturn(new Version("1.3.1")); expect(bundle.getLocation()).andReturn("location"); expect(bundle.getHeaders()).andReturn(new Hashtable()).anyTimes(); + expect(bundle.getBundleId()).andReturn(123L); bundle.uninstall(); expect(sysBundleContext.installBundle(bundlev132.toURI().toURL().toString())).andReturn(bundle2); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle2 }); expect(bundle2.getState()).andReturn(Bundle.INSTALLED); expect(bundle2.getHeaders()).andReturn(new Hashtable()).anyTimes(); expect(bundle.getState()).andReturn(Bundle.UNINSTALLED).anyTimes(); expect(bundle.getRegisteredServices()).andReturn(null); expect(sysBundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.adapt(FrameworkWiring.class)).andReturn(wiring); bundle2.start(); wiring.refreshBundles(eq(asSet(bundle2, bundle)), anyObject(FrameworkListener[].class)); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { for (FrameworkListener l : (FrameworkListener[]) (EasyMock.getCurrentArguments()[1])) { l.frameworkEvent(null); } return null; } }); replay(sysBundleContext, sysBundle, bundleContext, bundle, bundle2, wiring); result = patch.install(); assertNotNull( result ); assertSame( result, patch.getResult() ); assertFalse(patch.getResult().isSimulation()); verify(sysBundleContext, sysBundle, bundleContext, bundle, wiring); // // Recreate a new service and verify the downloaded patch is still available and installed // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); service = new ServiceImpl(bundleContext); patches = service.getPatches(); assertNotNull(patches); it = patches.iterator(); assertTrue( it.hasNext() ); patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNotNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); } private <T> Set<T> asSet(T... objects) { HashSet<T> set = new HashSet<T>(); for (T t : objects) { set.add(t); } return set; } private void delete(File file) { if (file.isDirectory()) { for (File child : file.listFiles()) { delete( child ); } file.delete(); } else if (file.isFile()) { file.delete(); } } private URL getZippedTestDir(String name) throws IOException { File f2 = new File(baseDir, name + ".jar"); OutputStream os = new FileOutputStream(f2); jarDir(new File(baseDir, name), os); os.close(); return f2.toURI().toURL(); } public static void jarDir(File directory, OutputStream os) throws IOException { // create a ZipOutputStream to zip the data to JarOutputStream zos = new JarOutputStream(os); zos.setLevel(Deflater.NO_COMPRESSION); String path = ""; File manFile = new File(directory, JarFile.MANIFEST_NAME); if (manFile.exists()) { byte[] readBuffer = new byte[8192]; FileInputStream fis = new FileInputStream(manFile); try { ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME); zos.putNextEntry(anEntry); int bytesIn = fis.read(readBuffer); while (bytesIn != -1) { zos.write(readBuffer, 0, bytesIn); bytesIn = fis.read(readBuffer); } } finally { fis.close(); } zos.closeEntry(); } zipDir(directory, zos, path, Collections.singleton(JarFile.MANIFEST_NAME)); // close the stream zos.close(); } public static void zipDir(File directory, ZipOutputStream zos, String path, Set/* <String> */ exclusions) throws IOException { // get a listing of the directory content File[] dirList = directory.listFiles(); byte[] readBuffer = new byte[8192]; int bytesIn = 0; // loop through dirList, and zip the files for (int i = 0; i < dirList.length; i++) { File f = dirList[i]; if (f.isDirectory()) { String prefix = path + f.getName() + "/"; zos.putNextEntry(new ZipEntry(prefix)); zipDir(f, zos, prefix, exclusions); continue; } String entry = path + f.getName(); if (!exclusions.contains(entry)) { FileInputStream fis = new FileInputStream(f); try { ZipEntry anEntry = new ZipEntry(entry); zos.putNextEntry(anEntry); bytesIn = fis.read(readBuffer); while (bytesIn != -1) { zos.write(readBuffer, 0, bytesIn); bytesIn = fis.read(readBuffer); } } finally { fis.close(); } } } } }
false
true
public void testPatch() throws Exception { BundleContext bundleContext = createMock(BundleContext.class); Bundle sysBundle = createMock(Bundle.class); BundleContext sysBundleContext = createMock(BundleContext.class); Bundle bundle = createMock(Bundle.class); Bundle bundle2 = createMock(Bundle.class); FrameworkWiring wiring = createMock(FrameworkWiring.class); // // Create a new service, download a patch // expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); ServiceImpl service = new ServiceImpl(bundleContext); Iterable<Patch> patches = service.download(patch132.toURI().toURL()); assertNotNull(patches); Iterator<Patch> it = patches.iterator(); assertTrue( it.hasNext() ); Patch patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); Iterator<String> itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Simulate the patch // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle }); expect(bundle.getSymbolicName()).andReturn("my-bsn"); expect(bundle.getVersion()).andReturn(new Version("1.3.1")); expect(bundle.getLocation()).andReturn("location"); replay(sysBundleContext, sysBundle, bundleContext, bundle); Result result = patch.simulate(); assertNotNull( result ); assertNull( patch.getResult() ); assertTrue(result.isSimulation()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Recreate a new service and verify the downloaded patch is still available // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); service = new ServiceImpl(bundleContext); patches = service.getPatches(); assertNotNull(patches); it = patches.iterator(); assertTrue( it.hasNext() ); patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Install the patch // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle }); expect(bundle.getSymbolicName()).andReturn("my-bsn"); expect(bundle.getVersion()).andReturn(new Version("1.3.1")); expect(bundle.getLocation()).andReturn("location"); expect(bundle.getHeaders()).andReturn(new Hashtable()).anyTimes(); bundle.uninstall(); expect(sysBundleContext.installBundle(bundlev132.toURI().toURL().toString())).andReturn(bundle2); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle2 }); expect(bundle2.getState()).andReturn(Bundle.INSTALLED); expect(bundle2.getHeaders()).andReturn(new Hashtable()).anyTimes(); expect(bundle.getState()).andReturn(Bundle.UNINSTALLED).anyTimes(); expect(bundle.getRegisteredServices()).andReturn(null); expect(sysBundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.adapt(FrameworkWiring.class)).andReturn(wiring); bundle2.start(); wiring.refreshBundles(eq(asSet(bundle2, bundle)), anyObject(FrameworkListener[].class)); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { for (FrameworkListener l : (FrameworkListener[]) (EasyMock.getCurrentArguments()[1])) { l.frameworkEvent(null); } return null; } }); replay(sysBundleContext, sysBundle, bundleContext, bundle, bundle2, wiring); result = patch.install(); assertNotNull( result ); assertSame( result, patch.getResult() ); assertFalse(patch.getResult().isSimulation()); verify(sysBundleContext, sysBundle, bundleContext, bundle, wiring); // // Recreate a new service and verify the downloaded patch is still available and installed // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); service = new ServiceImpl(bundleContext); patches = service.getPatches(); assertNotNull(patches); it = patches.iterator(); assertTrue( it.hasNext() ); patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNotNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); }
public void testPatch() throws Exception { BundleContext bundleContext = createMock(BundleContext.class); Bundle sysBundle = createMock(Bundle.class); BundleContext sysBundleContext = createMock(BundleContext.class); Bundle bundle = createMock(Bundle.class); Bundle bundle2 = createMock(Bundle.class); FrameworkWiring wiring = createMock(FrameworkWiring.class); // // Create a new service, download a patch // expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); ServiceImpl service = new ServiceImpl(bundleContext); Iterable<Patch> patches = service.download(patch132.toURI().toURL()); assertNotNull(patches); Iterator<Patch> it = patches.iterator(); assertTrue( it.hasNext() ); Patch patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); Iterator<String> itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Simulate the patch // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle }); expect(bundle.getSymbolicName()).andReturn("my-bsn"); expect(bundle.getVersion()).andReturn(new Version("1.3.1")); expect(bundle.getLocation()).andReturn("location"); expect(bundle.getBundleId()).andReturn(123L); replay(sysBundleContext, sysBundle, bundleContext, bundle); Result result = patch.simulate(); assertNotNull( result ); assertNull( patch.getResult() ); assertTrue(result.isSimulation()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Recreate a new service and verify the downloaded patch is still available // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); service = new ServiceImpl(bundleContext); patches = service.getPatches(); assertNotNull(patches); it = patches.iterator(); assertTrue( it.hasNext() ); patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); // // Install the patch // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle }); expect(bundle.getSymbolicName()).andReturn("my-bsn"); expect(bundle.getVersion()).andReturn(new Version("1.3.1")); expect(bundle.getLocation()).andReturn("location"); expect(bundle.getHeaders()).andReturn(new Hashtable()).anyTimes(); expect(bundle.getBundleId()).andReturn(123L); bundle.uninstall(); expect(sysBundleContext.installBundle(bundlev132.toURI().toURL().toString())).andReturn(bundle2); expect(sysBundleContext.getBundles()).andReturn(new Bundle[] { bundle2 }); expect(bundle2.getState()).andReturn(Bundle.INSTALLED); expect(bundle2.getHeaders()).andReturn(new Hashtable()).anyTimes(); expect(bundle.getState()).andReturn(Bundle.UNINSTALLED).anyTimes(); expect(bundle.getRegisteredServices()).andReturn(null); expect(sysBundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.adapt(FrameworkWiring.class)).andReturn(wiring); bundle2.start(); wiring.refreshBundles(eq(asSet(bundle2, bundle)), anyObject(FrameworkListener[].class)); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { for (FrameworkListener l : (FrameworkListener[]) (EasyMock.getCurrentArguments()[1])) { l.frameworkEvent(null); } return null; } }); replay(sysBundleContext, sysBundle, bundleContext, bundle, bundle2, wiring); result = patch.install(); assertNotNull( result ); assertSame( result, patch.getResult() ); assertFalse(patch.getResult().isSimulation()); verify(sysBundleContext, sysBundle, bundleContext, bundle, wiring); // // Recreate a new service and verify the downloaded patch is still available and installed // reset(sysBundleContext, sysBundle, bundleContext, bundle); expect(bundleContext.getBundle(0)).andReturn(sysBundle); expect(sysBundle.getBundleContext()).andReturn(sysBundleContext); expect(sysBundleContext.getProperty("fuse.patch.location")) .andReturn(storage.toString()).anyTimes(); replay(sysBundleContext, sysBundle, bundleContext, bundle); service = new ServiceImpl(bundleContext); patches = service.getPatches(); assertNotNull(patches); it = patches.iterator(); assertTrue( it.hasNext() ); patch = it.next(); assertNotNull( patch ); assertEquals("patch-1.3.2", patch.getId()); assertNotNull(patch.getBundles()); assertEquals(1, patch.getBundles().size()); itb = patch.getBundles().iterator(); assertEquals(bundlev132.toURI().toURL().toString(), itb.next()); assertNotNull(patch.getResult()); verify(sysBundleContext, sysBundle, bundleContext, bundle); }
diff --git a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderSurrealIslands.java b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderSurrealIslands.java index 261ce01..af2a315 100644 --- a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderSurrealIslands.java +++ b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderSurrealIslands.java @@ -1,65 +1,65 @@ package net.nexisonline.spade.chunkproviders; import java.util.logging.Logger; import net.nexisonline.spade.SpadeChunkProvider; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.util.config.ConfigurationNode; import toxi.math.noise.SimplexOctaves; public class ChunkProviderSurrealIslands extends SpadeChunkProvider { private SimplexOctaves terrainNoiseA; private SimplexOctaves terrainNoiseB; @Override public void onLoad(Object world, long seed) { this.setHasCustomTerrain(true); try { terrainNoiseA=new SimplexOctaves(seed,4); terrainNoiseB=new SimplexOctaves(seed+51,4); } catch (Exception e) { } } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#generateChunk(int, int, byte[], * org.bukkit.block.Biome[], double[]) */ @Override public void generateChunk(Object world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { final double SCALE=0.01; final double THRESHOLD=-0.3; for (int x = 0; x < 16; x+=1) { for (int z = 0; z < 16; z+=1) { for (int y = 0; y < 128; y+=1) { double a = terrainNoiseA.noise((double)(x+(X*16))*SCALE, (double)y*SCALE , (double)(z+(Z*16))*SCALE); double b = terrainNoiseB.noise((double)(x+(X*16))*SCALE, (double)y*SCALE , (double)(z+(Z*16))*SCALE); byte block = (byte) ((a*b<THRESHOLD) ? Material.STONE.getId() : Material.AIR.getId()); // If below height, set rock. Otherwise, set air. block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water - block = (y <= 5 && block==9) ? (byte)Material.SAND.getId() : block; + block = (y <= 32) ? (byte)Material.STONE.getId() : block; block = (y <= 1) ? (byte)Material.BEDROCK.getId() : block; // Origin point + sand to prevent 5000 years of loading. if(x==0&&z==0&&X==x&&Z==z&&y<=63) block=(byte) ((y==63)?12:7); abyte[getBlockIndex(x,y,z)]=block;//(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } Logger.getLogger("Minecraft").info(String.format("[Islands] Chunk (%d,%d)",X,Z)); } @Override public ConfigurationNode configure(ConfigurationNode node) { return node; } }
true
true
public void generateChunk(Object world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { final double SCALE=0.01; final double THRESHOLD=-0.3; for (int x = 0; x < 16; x+=1) { for (int z = 0; z < 16; z+=1) { for (int y = 0; y < 128; y+=1) { double a = terrainNoiseA.noise((double)(x+(X*16))*SCALE, (double)y*SCALE , (double)(z+(Z*16))*SCALE); double b = terrainNoiseB.noise((double)(x+(X*16))*SCALE, (double)y*SCALE , (double)(z+(Z*16))*SCALE); byte block = (byte) ((a*b<THRESHOLD) ? Material.STONE.getId() : Material.AIR.getId()); // If below height, set rock. Otherwise, set air. block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water block = (y <= 5 && block==9) ? (byte)Material.SAND.getId() : block; block = (y <= 1) ? (byte)Material.BEDROCK.getId() : block; // Origin point + sand to prevent 5000 years of loading. if(x==0&&z==0&&X==x&&Z==z&&y<=63) block=(byte) ((y==63)?12:7); abyte[getBlockIndex(x,y,z)]=block;//(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } Logger.getLogger("Minecraft").info(String.format("[Islands] Chunk (%d,%d)",X,Z)); }
public void generateChunk(Object world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { final double SCALE=0.01; final double THRESHOLD=-0.3; for (int x = 0; x < 16; x+=1) { for (int z = 0; z < 16; z+=1) { for (int y = 0; y < 128; y+=1) { double a = terrainNoiseA.noise((double)(x+(X*16))*SCALE, (double)y*SCALE , (double)(z+(Z*16))*SCALE); double b = terrainNoiseB.noise((double)(x+(X*16))*SCALE, (double)y*SCALE , (double)(z+(Z*16))*SCALE); byte block = (byte) ((a*b<THRESHOLD) ? Material.STONE.getId() : Material.AIR.getId()); // If below height, set rock. Otherwise, set air. block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water block = (y <= 32) ? (byte)Material.STONE.getId() : block; block = (y <= 1) ? (byte)Material.BEDROCK.getId() : block; // Origin point + sand to prevent 5000 years of loading. if(x==0&&z==0&&X==x&&Z==z&&y<=63) block=(byte) ((y==63)?12:7); abyte[getBlockIndex(x,y,z)]=block;//(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } Logger.getLogger("Minecraft").info(String.format("[Islands] Chunk (%d,%d)",X,Z)); }
diff --git a/src/main/java/org/todoke/countstream/Main.java b/src/main/java/org/todoke/countstream/Main.java index 69e680e..e2b7cee 100644 --- a/src/main/java/org/todoke/countstream/Main.java +++ b/src/main/java/org/todoke/countstream/Main.java @@ -1,54 +1,54 @@ /* * Copyright 2011 Yusuke Yamamoto * * 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.todoke.countstream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.FilterQuery; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; import java.io.File; /** * @author Yusuke Yamamoto - yusuke at mac.com */ public class Main { static Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { - if(args.length != 1){ + if (args.length != 1) { System.out.println("usage: java org.todoke.hashcount.Main [comma separated terms to track]"); System.exit(-1); } logger.info("terms to track: " + args[0]); String[] terms = args[0].split(","); FilterQuery query = new FilterQuery().track(terms); TwitterStream stream = new TwitterStreamFactory().getInstance(); StringBuffer path = new StringBuffer(args[0].length()); - for(String term : terms){ - if(0 != path.length()){ + for (String term : terms) { + if (0 != path.length()) { path.append("-"); } - path.append(term); + path.append(term.replaceAll("#", "")); } Callback callback = new Callback(new File(path.toString())); Counter counter = new Counter(callback); stream.addListener(counter); stream.filter(query); } }
false
true
public static void main(String[] args) { if(args.length != 1){ System.out.println("usage: java org.todoke.hashcount.Main [comma separated terms to track]"); System.exit(-1); } logger.info("terms to track: " + args[0]); String[] terms = args[0].split(","); FilterQuery query = new FilterQuery().track(terms); TwitterStream stream = new TwitterStreamFactory().getInstance(); StringBuffer path = new StringBuffer(args[0].length()); for(String term : terms){ if(0 != path.length()){ path.append("-"); } path.append(term); } Callback callback = new Callback(new File(path.toString())); Counter counter = new Counter(callback); stream.addListener(counter); stream.filter(query); }
public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: java org.todoke.hashcount.Main [comma separated terms to track]"); System.exit(-1); } logger.info("terms to track: " + args[0]); String[] terms = args[0].split(","); FilterQuery query = new FilterQuery().track(terms); TwitterStream stream = new TwitterStreamFactory().getInstance(); StringBuffer path = new StringBuffer(args[0].length()); for (String term : terms) { if (0 != path.length()) { path.append("-"); } path.append(term.replaceAll("#", "")); } Callback callback = new Callback(new File(path.toString())); Counter counter = new Counter(callback); stream.addListener(counter); stream.filter(query); }
diff --git a/src/main/java/org/tal/basiccircuits/receiver.java b/src/main/java/org/tal/basiccircuits/receiver.java index c7e3f34..bfe6962 100644 --- a/src/main/java/org/tal/basiccircuits/receiver.java +++ b/src/main/java/org/tal/basiccircuits/receiver.java @@ -1,61 +1,61 @@ package org.tal.basiccircuits; import org.bukkit.command.CommandSender; import org.tal.redstonechips.channel.ReceivingCircuit; import org.tal.redstonechips.util.BitSet7; import org.tal.redstonechips.util.BitSetUtils; /** * * @author Tal Eisenberg */ public class receiver extends ReceivingCircuit { private int dataPin; @Override public void inputChange(int inIdx, boolean newLevel) {} @Override protected boolean init(CommandSender sender, String[] args) { if (outputs.length==0) { error(sender, "Expecting at least 1 output pin."); return false; } if (args.length>0) { try { + dataPin = (outputs.length==1?0:1); this.initWireless(sender, args[0]); - dataPin = (outputs.length==1?0:1); return true; } catch (IllegalArgumentException ie) { error(sender, ie.getMessage()); return false; } } else { error(sender, "Channel name is missing."); return false; } } @Override public void receive(BitSet7 bits) { if (hasDebuggers()) debug("Received " + BitSetUtils.bitSetToBinaryString(bits, 0, outputs.length)); this.sendBitSet(dataPin, outputs.length-dataPin, bits); if (outputs.length>1) { this.sendOutput(0, true); this.sendOutput(0, false); } } @Override public void circuitShutdown() { if (getChannel()!=null) redstoneChips.removeReceiver(this); } @Override public int getChannelLength() { return outputs.length-dataPin; } }
false
true
protected boolean init(CommandSender sender, String[] args) { if (outputs.length==0) { error(sender, "Expecting at least 1 output pin."); return false; } if (args.length>0) { try { this.initWireless(sender, args[0]); dataPin = (outputs.length==1?0:1); return true; } catch (IllegalArgumentException ie) { error(sender, ie.getMessage()); return false; } } else { error(sender, "Channel name is missing."); return false; } }
protected boolean init(CommandSender sender, String[] args) { if (outputs.length==0) { error(sender, "Expecting at least 1 output pin."); return false; } if (args.length>0) { try { dataPin = (outputs.length==1?0:1); this.initWireless(sender, args[0]); return true; } catch (IllegalArgumentException ie) { error(sender, ie.getMessage()); return false; } } else { error(sender, "Channel name is missing."); return false; } }
diff --git a/src/ecologylab/generic/DomTools.java b/src/ecologylab/generic/DomTools.java index d2662581..e63113b2 100644 --- a/src/ecologylab/generic/DomTools.java +++ b/src/ecologylab/generic/DomTools.java @@ -1,106 +1,116 @@ /** * */ package ecologylab.generic; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Tools for manipulating org.w3c.documents * * @author andruid */ public class DomTools extends Debug { private static final int TAB_WIDTH = 3; /** * Print your DOM tree in a readable way. * * @param node */ public static void prettyPrint(Node node) { prettyPrint(node, 0); } private static void prettyPrint(Node node, int level) { try { if ("#document".equals(node.getNodeName())) { - prettyPrint(node.getFirstChild(), level); + Node nextChild = node.getFirstChild(); + prettyPrint(nextChild, level); + if (nextChild.getNextSibling() != null) + { + warning(node, "multiple root element!"); + while (nextChild != null) + { + prettyPrint(nextChild, level); + nextChild = nextChild.getNextSibling(); + } + } return; } for (int i=0; i< level; i++) printTab(); System.out.print("<" + node.getNodeName()); NamedNodeMap attrMap = node.getAttributes(); if (attrMap != null) for (int i = 0; i < attrMap.getLength(); i++) { Node attr = attrMap.item(i); String attrName = attr.getNodeName(); System.out.print(" " + attrName + "=\"" + attr.getNodeValue() + '"'); } String value = node.getNodeValue(); if (value != null) System.out.print(value); System.out.print(">"); NodeList nl = node.getChildNodes(); if (nl != null) { int numChildren = nl.getLength(); boolean printedNewline = false; if (numChildren > 0) { for (int i = 0; i < numChildren; i++) { Node childNode = nl.item(i); if ("#text".equals(childNode.getNodeName())) System.out.print(childNode.getTextContent()); else { if (!printedNewline) { printedNewline = true; System.out.print("\n"); } prettyPrint(childNode, level + 1); } } for (int i=0; i< level; i++) printTab(); } } System.out.println("</" + node.getNodeName() + ">"); } catch (Throwable e) { System.out.println("Cannot print!! " + e.getMessage()); e.printStackTrace(); } } private static void printTab() { for (int i=0; i<TAB_WIDTH; i++) System.out.print(' '); } public static String getAttribute(Node node, String name) { String result = null; if (node != null) { Node attrNode = node.getAttributes().getNamedItem(name); if (attrNode != null) { result = attrNode.getNodeValue(); } } return result; } }
true
true
private static void prettyPrint(Node node, int level) { try { if ("#document".equals(node.getNodeName())) { prettyPrint(node.getFirstChild(), level); return; } for (int i=0; i< level; i++) printTab(); System.out.print("<" + node.getNodeName()); NamedNodeMap attrMap = node.getAttributes(); if (attrMap != null) for (int i = 0; i < attrMap.getLength(); i++) { Node attr = attrMap.item(i); String attrName = attr.getNodeName(); System.out.print(" " + attrName + "=\"" + attr.getNodeValue() + '"'); } String value = node.getNodeValue(); if (value != null) System.out.print(value); System.out.print(">"); NodeList nl = node.getChildNodes(); if (nl != null) { int numChildren = nl.getLength(); boolean printedNewline = false; if (numChildren > 0) { for (int i = 0; i < numChildren; i++) { Node childNode = nl.item(i); if ("#text".equals(childNode.getNodeName())) System.out.print(childNode.getTextContent()); else { if (!printedNewline) { printedNewline = true; System.out.print("\n"); } prettyPrint(childNode, level + 1); } } for (int i=0; i< level; i++) printTab(); } } System.out.println("</" + node.getNodeName() + ">"); } catch (Throwable e) { System.out.println("Cannot print!! " + e.getMessage()); e.printStackTrace(); } }
private static void prettyPrint(Node node, int level) { try { if ("#document".equals(node.getNodeName())) { Node nextChild = node.getFirstChild(); prettyPrint(nextChild, level); if (nextChild.getNextSibling() != null) { warning(node, "multiple root element!"); while (nextChild != null) { prettyPrint(nextChild, level); nextChild = nextChild.getNextSibling(); } } return; } for (int i=0; i< level; i++) printTab(); System.out.print("<" + node.getNodeName()); NamedNodeMap attrMap = node.getAttributes(); if (attrMap != null) for (int i = 0; i < attrMap.getLength(); i++) { Node attr = attrMap.item(i); String attrName = attr.getNodeName(); System.out.print(" " + attrName + "=\"" + attr.getNodeValue() + '"'); } String value = node.getNodeValue(); if (value != null) System.out.print(value); System.out.print(">"); NodeList nl = node.getChildNodes(); if (nl != null) { int numChildren = nl.getLength(); boolean printedNewline = false; if (numChildren > 0) { for (int i = 0; i < numChildren; i++) { Node childNode = nl.item(i); if ("#text".equals(childNode.getNodeName())) System.out.print(childNode.getTextContent()); else { if (!printedNewline) { printedNewline = true; System.out.print("\n"); } prettyPrint(childNode, level + 1); } } for (int i=0; i< level; i++) printTab(); } } System.out.println("</" + node.getNodeName() + ">"); } catch (Throwable e) { System.out.println("Cannot print!! " + e.getMessage()); e.printStackTrace(); } }
diff --git a/src/main/java/com/philihp/weblabora/action/BaseAction.java b/src/main/java/com/philihp/weblabora/action/BaseAction.java index 77e1ca3..30ed01b 100644 --- a/src/main/java/com/philihp/weblabora/action/BaseAction.java +++ b/src/main/java/com/philihp/weblabora/action/BaseAction.java @@ -1,59 +1,62 @@ package com.philihp.weblabora.action; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.philihp.weblabora.jpa.User; import com.philihp.weblabora.util.FacebookSignedRequest; import com.philihp.weblabora.util.FacebookSignedRequestDeserializer; import com.philihp.weblabora.util.FacebookUtil; abstract public class BaseAction extends Action { @SuppressWarnings("unchecked") private static final Set<Object> PUBLIC_ACTIONS = new HashSet<Object>(Arrays.asList(ShowGame.class, ShowGameState.class, ShowLobby.class, Offline.class)); @Override public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("Action: "+this.getClass().getCanonicalName()); EntityManager em = (EntityManager)request.getAttribute("em"); User user = (User)request.getSession().getAttribute("user"); - if(user != null) em.persist(user); + if(user != null) { + user = em.merge(user); + request.getSession().setAttribute("user", user); + } //if still no user, restart authentication process if(user == null && isActionPrivate()) { throw new AuthenticationException(); } return execute(mapping, actionForm, request, response, user); } abstract ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response, User user) throws AuthenticationException, Exception; private boolean isActionPrivate() { return PUBLIC_ACTIONS.contains(this.getClass()) == false; } }
true
true
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("Action: "+this.getClass().getCanonicalName()); EntityManager em = (EntityManager)request.getAttribute("em"); User user = (User)request.getSession().getAttribute("user"); if(user != null) em.persist(user); //if still no user, restart authentication process if(user == null && isActionPrivate()) { throw new AuthenticationException(); } return execute(mapping, actionForm, request, response, user); }
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("Action: "+this.getClass().getCanonicalName()); EntityManager em = (EntityManager)request.getAttribute("em"); User user = (User)request.getSession().getAttribute("user"); if(user != null) { user = em.merge(user); request.getSession().setAttribute("user", user); } //if still no user, restart authentication process if(user == null && isActionPrivate()) { throw new AuthenticationException(); } return execute(mapping, actionForm, request, response, user); }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/internal/editor/Editor.java b/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/internal/editor/Editor.java index e89d2f29f..f01246b0b 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/internal/editor/Editor.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/internal/editor/Editor.java @@ -1,215 +1,215 @@ /******************************************************************************* * Copyright (c) 2011 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.ui.views.internal.editor; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.tcf.te.ui.views.extensions.EditorPageBinding; import org.eclipse.tcf.te.ui.views.extensions.EditorPageBindingExtensionPointManager; import org.eclipse.tcf.te.ui.views.extensions.EditorPageExtensionPointManager; import org.eclipse.tcf.te.ui.views.interfaces.IEditorPage; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPersistable; import org.eclipse.ui.IPersistableEditor; import org.eclipse.ui.PartInitException; import org.eclipse.ui.XMLMemento; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.editor.IFormPage; /** * Details editor. */ public class Editor extends FormEditor implements IPersistableEditor { // The reference to an memento to restore once the editor got activated private IMemento mementoToRestore; /* (non-Javadoc) * @see org.eclipse.ui.forms.editor.FormEditor#addPages() */ @Override protected void addPages() { // Read extension point and add the contributed pages. IEditorInput input = getEditorInput(); // Get all applicable editor page bindings EditorPageBinding[] bindings = EditorPageBindingExtensionPointManager.getInstance().getApplicableEditorPageBindings(input); for (EditorPageBinding binding : bindings) { String pageId = binding.getPageId(); if (pageId != null) { // Get the corresponding editor page instance IEditorPage page = EditorPageExtensionPointManager.getInstance().getEditorPage(pageId, true); if (page != null) { try { // Associate this editor with the page instance. // This is typically done in the constructor, but we are // utilizing a default constructor to instantiate the page. page.initialize(this); // Read in the "insertBefore" and "insertAfter" properties of the binding String insertBefore = binding.getInsertBefore().trim(); String insertAfter = binding.getInsertAfter().trim(); // insertBefore will eclipse insertAfter is both is specified. if (!"".equals(insertBefore)) { //$NON-NLS-1$ // If it is "first", we insert the page at index 0 if ("first".equalsIgnoreCase(insertBefore)) { //$NON-NLS-1$ - addPage(0, page); + addPage(0, page, input); } else { // Find the index of the page we shall insert this page before int index = getIndexOf(insertBefore); - if (index != -1) addPage(index, page); - else addPage(page); + if (index != -1) addPage(index, page, input); + else addPage(page, input); } } else if (!"".equals(insertAfter) && !"last".equalsIgnoreCase(insertAfter)) { //$NON-NLS-1$ //$NON-NLS-2$ // Find the index of the page we shall insert this page after int index = getIndexOf(insertAfter); - if (index != -1 && index + 1 < pages.size()) addPage(index + 1, page); - else addPage(page); + if (index != -1 && index + 1 < pages.size()) addPage(index + 1, page, input); + else addPage(page, input); } else { // And add the page to the editor as last page. - addPage(page); + addPage(page, input); } } catch (PartInitException e) { /* ignored on purpose */ } } } } if (mementoToRestore != null) { // Loop over all registered pages and pass on the editor specific memento // to the pages which implements IPersistableEditor as well for (Object page : pages) { if (page instanceof IPersistableEditor) { ((IPersistableEditor)page).restoreState(mementoToRestore); } } mementoToRestore = null; } } /** * Returns the index of the page with the given id. * * @param pageId The page id. Must not be <code>null</code>. * @return The page index or <code>-1</code> if not found. */ private int getIndexOf(String pageId) { Assert.isNotNull(pageId); for (int i = 0; i < pages.size(); i++) { Object page = pages.get(i); if (page instanceof IFormPage) { IFormPage fpage = (IFormPage)page; if (fpage.getId().equals(pageId)) return i; } } return -1; } /* (non-Javadoc) * @see org.eclipse.ui.forms.editor.FormPage#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput) */ @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { super.init(site, input); // Update the part name if (!"".equals(input.getName())) setPartName(input.getName()); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.IProgressMonitor) */ @Override public void doSave(IProgressMonitor monitor) { commitPages(true); editorDirtyStateChanged(); } /* (non-Javadoc) * @see org.eclipse.ui.part.EditorPart#doSaveAs() */ @Override public void doSaveAs() { } /* (non-Javadoc) * @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed() */ @Override public boolean isSaveAsAllowed() { return false; } /* (non-Javadoc) * @see org.eclipse.ui.IPersistableEditor#restoreState(org.eclipse.ui.IMemento) */ @Override public void restoreState(IMemento memento) { // Get the editor specific memento mementoToRestore = internalGetMemento(memento); } /* (non-Javadoc) * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento) */ @Override public void saveState(IMemento memento) { // Get the editor specific memento memento = internalGetMemento(memento); // Loop over all registered pages and pass on the editor specific memento // to the pages which implements IPersistable as well for (Object page : pages) { if (page instanceof IPersistable) { ((IPersistable)page).saveState(memento); } } } /** * Internal helper method accessing our editor local child memento * from the given parent memento. */ private IMemento internalGetMemento(IMemento memento) { // Assume the editor memento to be the same as the parent memento IMemento editorMemento = memento; // If the parent memento is not null, create a child within the parent if (memento != null) { editorMemento = memento.getChild(Editor.class.getName()); if (editorMemento == null) { editorMemento = memento.createChild(Editor.class.getName()); } } else { // The parent memento is null. Create a new internal instance // of a XMLMemento. This case is happening if the user switches // to another perspective an the view becomes visible by this switch. editorMemento = XMLMemento.createWriteRoot(Editor.class.getName()); } return editorMemento; } /* (non-Javadoc) * @see org.eclipse.ui.part.MultiPageEditorPart#getAdapter(java.lang.Class) */ @Override public Object getAdapter(Class adapter) { // We pass on the adapt request to the currently active page Object adapterInstance = getActivePageInstance() != null ? getActivePageInstance().getAdapter(adapter) : null; if (adapterInstance == null) { // If failed to adapt via the currently active page, pass on to the super implementation adapterInstance = super.getAdapter(adapter); } return adapterInstance; } }
false
true
protected void addPages() { // Read extension point and add the contributed pages. IEditorInput input = getEditorInput(); // Get all applicable editor page bindings EditorPageBinding[] bindings = EditorPageBindingExtensionPointManager.getInstance().getApplicableEditorPageBindings(input); for (EditorPageBinding binding : bindings) { String pageId = binding.getPageId(); if (pageId != null) { // Get the corresponding editor page instance IEditorPage page = EditorPageExtensionPointManager.getInstance().getEditorPage(pageId, true); if (page != null) { try { // Associate this editor with the page instance. // This is typically done in the constructor, but we are // utilizing a default constructor to instantiate the page. page.initialize(this); // Read in the "insertBefore" and "insertAfter" properties of the binding String insertBefore = binding.getInsertBefore().trim(); String insertAfter = binding.getInsertAfter().trim(); // insertBefore will eclipse insertAfter is both is specified. if (!"".equals(insertBefore)) { //$NON-NLS-1$ // If it is "first", we insert the page at index 0 if ("first".equalsIgnoreCase(insertBefore)) { //$NON-NLS-1$ addPage(0, page); } else { // Find the index of the page we shall insert this page before int index = getIndexOf(insertBefore); if (index != -1) addPage(index, page); else addPage(page); } } else if (!"".equals(insertAfter) && !"last".equalsIgnoreCase(insertAfter)) { //$NON-NLS-1$ //$NON-NLS-2$ // Find the index of the page we shall insert this page after int index = getIndexOf(insertAfter); if (index != -1 && index + 1 < pages.size()) addPage(index + 1, page); else addPage(page); } else { // And add the page to the editor as last page. addPage(page); } } catch (PartInitException e) { /* ignored on purpose */ } } } } if (mementoToRestore != null) { // Loop over all registered pages and pass on the editor specific memento // to the pages which implements IPersistableEditor as well for (Object page : pages) { if (page instanceof IPersistableEditor) { ((IPersistableEditor)page).restoreState(mementoToRestore); } } mementoToRestore = null; } }
protected void addPages() { // Read extension point and add the contributed pages. IEditorInput input = getEditorInput(); // Get all applicable editor page bindings EditorPageBinding[] bindings = EditorPageBindingExtensionPointManager.getInstance().getApplicableEditorPageBindings(input); for (EditorPageBinding binding : bindings) { String pageId = binding.getPageId(); if (pageId != null) { // Get the corresponding editor page instance IEditorPage page = EditorPageExtensionPointManager.getInstance().getEditorPage(pageId, true); if (page != null) { try { // Associate this editor with the page instance. // This is typically done in the constructor, but we are // utilizing a default constructor to instantiate the page. page.initialize(this); // Read in the "insertBefore" and "insertAfter" properties of the binding String insertBefore = binding.getInsertBefore().trim(); String insertAfter = binding.getInsertAfter().trim(); // insertBefore will eclipse insertAfter is both is specified. if (!"".equals(insertBefore)) { //$NON-NLS-1$ // If it is "first", we insert the page at index 0 if ("first".equalsIgnoreCase(insertBefore)) { //$NON-NLS-1$ addPage(0, page, input); } else { // Find the index of the page we shall insert this page before int index = getIndexOf(insertBefore); if (index != -1) addPage(index, page, input); else addPage(page, input); } } else if (!"".equals(insertAfter) && !"last".equalsIgnoreCase(insertAfter)) { //$NON-NLS-1$ //$NON-NLS-2$ // Find the index of the page we shall insert this page after int index = getIndexOf(insertAfter); if (index != -1 && index + 1 < pages.size()) addPage(index + 1, page, input); else addPage(page, input); } else { // And add the page to the editor as last page. addPage(page, input); } } catch (PartInitException e) { /* ignored on purpose */ } } } } if (mementoToRestore != null) { // Loop over all registered pages and pass on the editor specific memento // to the pages which implements IPersistableEditor as well for (Object page : pages) { if (page instanceof IPersistableEditor) { ((IPersistableEditor)page).restoreState(mementoToRestore); } } mementoToRestore = null; } }
diff --git a/org/python/core/Options.java b/org/python/core/Options.java index b6f0b1d3..02bfef63 100644 --- a/org/python/core/Options.java +++ b/org/python/core/Options.java @@ -1,162 +1,162 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; /** * A class with static fields for each of the settable options. * The options from registry and command line is copied into * the fields here and the rest of Jyhton checks these fields. */ public class Options { // JPython options. Some of these can be set from the command line // options, but all can be controlled through the JPython registry /** * when an exception occurs in Java code, and it is not caught, should * the interpreter print out the Java exception in the traceback? */ public static boolean showJavaExceptions = false; /** * When true, python exception raised in overriden methods will * be shown on stderr. This option is remarkable usefull when * python is used for implementing CORBA server. Some CORBA * servers will turn python exception (say a NameError) into an * anonymous user exception without any stacktrace. Setting this * option will show the stacktrace. */ public static boolean showPythonProxyExceptions = false; /** * To force JIT compilation of Jython code -- should be unnecessary * Setting this to true will cause jdk1.2rc1 to core dump on Windows */ public static boolean skipCompile = true; /** * Setting this to true will cause the console to poll standard in. * This might be helpful on systems without system-level threads. */ public static boolean pollStandardIn = false; /** * If true, JPython respects Java the accessibility flag for fields, * methods, and constructors. This means you can only access public * members. Set this to false to access all members by toggling the * accessible flag on the member. */ public static boolean respectJavaAccessibility = true; /** * When false the <code>site.py</code> will not be imported. * This is only honored by the command line main class. */ public static boolean importSite = true; /** * Set verbosity to Py.ERROR, Py.WARNING, Py.MESSAGE, Py.COMMENT, * or Py.DEBUG for varying levels of informative messages from * Jython. Normally this option is set from the command line. */ public static int verbose = Py.MESSAGE; /** * Setting this to true will support old 1.0 style keyword+"_" names. * This isn't needed any more due to improvements in the parser */ public static boolean deprecatedKeywordMangling = true; /** * A directory where the dynamicly generated classes are written. * Nothing is ever read from here, it is only for debugging * purposes. */ public static String proxyDebugDirectory = null; /** * If true, Jython will use the first module found on sys.path * where java File.isFile() returns true. Setting this to true * have no effect on unix-type filesystems. On Windows/HPS+ * systems setting it to true will enable Jython-2.0 behaviour. */ public static boolean caseok = false; // // ####### END OF OPTIONS // private Options() { ; } private static boolean getBooleanOption(String name, boolean defaultValue) { String prop = PySystemState.registry.getProperty("python."+name); if (prop == null) return defaultValue; return prop.equalsIgnoreCase("true") || prop.equalsIgnoreCase("yes"); } private static String getStringOption(String name, String defaultValue) { String prop = PySystemState.registry.getProperty("python."+name); if (prop == null) return defaultValue; return prop; } /** * Initialize the static fields from the registry options. */ public static void setFromRegistry() { // Set the more unusual options Options.showJavaExceptions = getBooleanOption("options.showJavaExceptions", Options.showJavaExceptions); Options.showPythonProxyExceptions = getBooleanOption("options.showPythonProxyExceptions", Options.showPythonProxyExceptions); Options.skipCompile = getBooleanOption("options.skipCompile", Options.skipCompile); Options.deprecatedKeywordMangling = getBooleanOption("deprecated.keywordMangling", Options.deprecatedKeywordMangling); Options.pollStandardIn = getBooleanOption("console.poll", Options.pollStandardIn); Options.respectJavaAccessibility = getBooleanOption("security.respectJavaAccessibility", Options.respectJavaAccessibility); Options.proxyDebugDirectory = getStringOption("options.proxyDebugDirectory", Options.proxyDebugDirectory); // verbosity is more complicated: String prop = PySystemState.registry.getProperty("python.verbose"); if (prop != null) { if (prop.equalsIgnoreCase("error")) Options.verbose = Py.ERROR; else if (prop.equalsIgnoreCase("warning")) Options.verbose = Py.WARNING; else if (prop.equalsIgnoreCase("message")) Options.verbose = Py.MESSAGE; else if (prop.equalsIgnoreCase("comment")) Options.verbose = Py.COMMENT; else if (prop.equalsIgnoreCase("debug")) Options.verbose = Py.DEBUG; else throw Py.ValueError("Illegal verbose option setting: '"+ prop+"'"); } Options.caseok = - getBooleanOption("options.caseok", Options.pollStandardIn); + getBooleanOption("options.caseok", Options.caseok); // additional initializations which must happen after the registry // is guaranteed to be initialized. JavaAccessibility.initialize(); } }
true
true
*/ public static void setFromRegistry() { // Set the more unusual options Options.showJavaExceptions = getBooleanOption("options.showJavaExceptions", Options.showJavaExceptions); Options.showPythonProxyExceptions = getBooleanOption("options.showPythonProxyExceptions", Options.showPythonProxyExceptions); Options.skipCompile = getBooleanOption("options.skipCompile", Options.skipCompile); Options.deprecatedKeywordMangling = getBooleanOption("deprecated.keywordMangling", Options.deprecatedKeywordMangling); Options.pollStandardIn = getBooleanOption("console.poll", Options.pollStandardIn); Options.respectJavaAccessibility = getBooleanOption("security.respectJavaAccessibility", Options.respectJavaAccessibility); Options.proxyDebugDirectory = getStringOption("options.proxyDebugDirectory", Options.proxyDebugDirectory); // verbosity is more complicated: String prop = PySystemState.registry.getProperty("python.verbose"); if (prop != null) { if (prop.equalsIgnoreCase("error")) Options.verbose = Py.ERROR; else if (prop.equalsIgnoreCase("warning")) Options.verbose = Py.WARNING; else if (prop.equalsIgnoreCase("message")) Options.verbose = Py.MESSAGE; else if (prop.equalsIgnoreCase("comment")) Options.verbose = Py.COMMENT; else if (prop.equalsIgnoreCase("debug")) Options.verbose = Py.DEBUG; else throw Py.ValueError("Illegal verbose option setting: '"+ prop+"'"); } Options.caseok = getBooleanOption("options.caseok", Options.pollStandardIn); // additional initializations which must happen after the registry // is guaranteed to be initialized. JavaAccessibility.initialize(); }
*/ public static void setFromRegistry() { // Set the more unusual options Options.showJavaExceptions = getBooleanOption("options.showJavaExceptions", Options.showJavaExceptions); Options.showPythonProxyExceptions = getBooleanOption("options.showPythonProxyExceptions", Options.showPythonProxyExceptions); Options.skipCompile = getBooleanOption("options.skipCompile", Options.skipCompile); Options.deprecatedKeywordMangling = getBooleanOption("deprecated.keywordMangling", Options.deprecatedKeywordMangling); Options.pollStandardIn = getBooleanOption("console.poll", Options.pollStandardIn); Options.respectJavaAccessibility = getBooleanOption("security.respectJavaAccessibility", Options.respectJavaAccessibility); Options.proxyDebugDirectory = getStringOption("options.proxyDebugDirectory", Options.proxyDebugDirectory); // verbosity is more complicated: String prop = PySystemState.registry.getProperty("python.verbose"); if (prop != null) { if (prop.equalsIgnoreCase("error")) Options.verbose = Py.ERROR; else if (prop.equalsIgnoreCase("warning")) Options.verbose = Py.WARNING; else if (prop.equalsIgnoreCase("message")) Options.verbose = Py.MESSAGE; else if (prop.equalsIgnoreCase("comment")) Options.verbose = Py.COMMENT; else if (prop.equalsIgnoreCase("debug")) Options.verbose = Py.DEBUG; else throw Py.ValueError("Illegal verbose option setting: '"+ prop+"'"); } Options.caseok = getBooleanOption("options.caseok", Options.caseok); // additional initializations which must happen after the registry // is guaranteed to be initialized. JavaAccessibility.initialize(); }
diff --git a/src/edu/rpi/sss/util/jsp/UtilAbstractAction.java b/src/edu/rpi/sss/util/jsp/UtilAbstractAction.java index fedb8db..9facd22 100644 --- a/src/edu/rpi/sss/util/jsp/UtilAbstractAction.java +++ b/src/edu/rpi/sss/util/jsp/UtilAbstractAction.java @@ -1,1550 +1,1550 @@ /* ********************************************************************** Copyright 2006 Rensselaer Polytechnic Institute. All worldwide rights reserved. Redistribution and use of this distribution in source and binary forms, with or without modification, are permitted provided that: The above copyright notice and this permission notice appear in all copies and supporting documentation; The name, identifiers, and trademarks of Rensselaer Polytechnic Institute are not used in advertising or publicity without the express prior written permission of Rensselaer Polytechnic Institute; DISCLAIMER: The software is distributed" AS IS" without any express or implied warranty, including but not limited to, any implied warranties of merchantability or fitness for a particular purpose or any warrant)' of non-infringement of any current or pending patent rights. The authors of the software make no representations about the suitability of this software for any particular purpose. The entire risk as to the quality and performance of the software is with the user. Should the software prove defective, the user assumes the cost of all necessary servicing, repair or correction. In particular, neither Rensselaer Polytechnic Institute, nor the authors of the software are liable for any indirect, special, consequential, or incidental damages related to the software, to the maximum extent the law permits. */ package edu.rpi.sss.util.jsp; import edu.rpi.sss.util.Util; import edu.rpi.sss.util.log.HttpAppLogger; import edu.rpi.sss.util.servlets.HttpServletUtils; import edu.rpi.sss.util.servlets.PresentationState; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessages; import org.apache.struts.config.ActionConfig; import org.apache.struts.util.MessageResources; /** * Abstract implementation of <strong>Action</strong> which sets up frequently * required fields then calls an abstract method to do the work. * * <p>If the abstract action method returns null or throws an exception the * struts action method will forward to "error". * * <p>An invalid form of request parameter (for those recognized by the * abstract action) will cause a forward to "badRequest".. * * <p>Otherwise we forward to the result from the abstract action. * * <p>This action also checks for a number of request parameters, mostly * related to presentation of data but some related to debugging. * * <p>Debugging actions:<ul> * <li><em>debug=yes|no</em> Set the debugging mode</li> * <li><em>seralize=anything</em> Try to serialize all session attributes * and log the result. Only when debugging on.</li> * </ul> * <p>The following are related to presentation of data. They are often * useful when debugging xslt but can be used to force content types. * <ul> * <li><em>browserType=!</em> Reset to normal dynamic behaviour, * that is browser type reset every request.</li> * <li><em>browserType=string</em> Set the browser type for one request</li> * <li><em>browserTypeSticky=!</em> Reset to normal dynamic behaviour, * that is reset browser type every request. * </li> * <li><em>browserTypeSticky=string</em> Set the browser type permanently * - browser type set until * next explicit setting.</li> * </ul><p> * Set the 'skinName' - maybe change the look and feel or e.g. provide * printer friendly output: * <p><ul> * <li><em>skinName=!</em> Reset to normal dynamic behaviour, * that is reset every request. * </li> * <li><em>skinName=string</em> Set the skin name for one request * </li> * <li><em>skinNameSticky=!</em> Reset to normal dynamic behaviour, * that is reset every request. * </li> * <li><em>skinNameSticky=string</em> Set the skin name permanently * </li> * </ul><p> * Allow user to set the content type explicitly. Used mainly for * debugging. The incoming request may contain the following: * <p><ul> * <li><em>contentType=!</em> Reset to normal dynamic behaviour, * that is reset every request. * </li> * <li><em>contentType=string</em> Set the Content type * </li> * <li><em>contentTypeSticky=!</em> Reset to normal dynamic behaviour, * that is reset every request. * </li> * <li><em>contentTypeSticky=string</em> Set the Content type permanently * </li> * </ul><p> * Allow user to indicate if we should refresh the xslt once, every time * or only when something changes. Used mainly for * debugging. The incoming request may contain the following: * <p><ul> * <li><em>refreshXslt=!</em> Reset to normal dynamic behaviour, * that is reset every request. * </li> * <li><em>refreshXslt=yes</em> One shot refresh * </li> * <li><em>refreshxslt=always</em> Refresh every request. * </li> * </ul><p> * Some misc actions: * <p><ul> * <li><em>forwardto=name</em> Just does a forward to that name. Used to * provide a null action with arbitrary forward * configured in struts-config.xml * <li><em>noxslt=anything</em> Suppress XSLT transform for one request. * Used for debugging - provides the raw xml. * </li> * * </ul> * <p>A combination of the above can allow us to dump the output in a file, * <br /><em>contentType=text/text&amp;noxslt=yes</em> */ public abstract class UtilAbstractAction extends Action implements HttpAppLogger { /** */ public static final String refreshIntervalKey = "refinterval="; /** */ public static final String refreshActionKey = "refaction="; /** */ public static final String actionTypeKey = "actionType="; /** */ public static final String actionTypeConversation = "conversation="; /** true for debugging on */ public boolean debug; protected transient Logger log; transient MessageResources messages; private transient String logPrefix; protected String requestLogout = "logout"; /** Forward to here for logged out */ public final String forwardLoggedOut = "loggedOut"; private boolean noActionErrors = false; protected boolean isPortlet; /** This is the routine which does the work. * * @param request Provide http request/response and form * @param messages Resources * @return String forward name * @throws Throwable */ public abstract String performAction(Request request, MessageResources messages) throws Throwable; public ActionForward execute(ActionMapping mapping, ActionForm frm, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ErrorEmitSvlt err = null; MessageEmitSvlt msg = null; String forward = "success"; UtilActionForm form = (UtilActionForm)frm; try { messages = getResources(request); /* Explicitly set logging on/off with an init parameter. Basing debugging off the state of log4j turns out to be too inflexible - for example, we have many applications with exactly the same code, basing logging on class names doesn't work. */ String debugVal = servlet.getServletConfig().getServletContext().getInitParameter("debug"); debug = !"0".equals(debugVal); checkDebug(request, form); isPortlet = isPortletRequest(request); noActionErrors = JspUtil.getProperty(messages, "edu.rpi.sss.util.action.noactionerrors", "no").equals("yes"); err = getErrorObj(request, messages); msg = getMessageObj(request, messages); /** Log the request - virtual domains can make it difficult to * distinguish applications. */ logRequest(request); if (debug) { debugOut("entry"); debugOut("================================"); debugOut("isPortlet=" + isPortlet); Enumeration en = servlet.getInitParameterNames(); while (en.hasMoreElements()) { debugOut("attr name=" + en.nextElement()); } debugOut("================================"); dumpRequest(request); } if (!form.getInitialised()) { // Do one time settings form.setNocache( JspUtil.getProperty(messages, "edu.rpi.sss.util.action.nocache", "no").equals("yes")); form.setInitialised(true); } form.setLog(getLogger()); form.setDebug(debug); form.setMres(messages); form.setBrowserType(JspUtil.getBrowserType(request)); form.assignCurrentUser(request.getRemoteUser()); form.setUrl(JspUtil.getUrl(request)); form.setSchemeHostPort(JspUtil.getURLshp(request)); form.setContext(JspUtil.getContext(request)); form.setUrlPrefix(JspUtil.getURLPrefix(request)); form.setActionPath(mapping.getPath()); form.setMapping(mapping); form.setActionParameter(mapping.getParameter()); form.setErr(err); form.setMsg(msg); form.assignSessionId(getSessionId(request)); checkNocache(request, response, form); String defaultContentType = JspUtil.getProperty(messages, "edu.rpi.sss.util.action.contenttype", "text/html"); Request req = new Request(request, response, form, this); String actionType = getStringActionPar(actionTypeKey, form); if (actionType != null) { for (int ati = 0; ati < Request.actionTypes.length; ati++) { if (Request.actionTypes[ati].equals(actionType)) { - req.setActionType(ati); - break; + req.setActionType(ati); + break; } } } /** Set up presentation values from request */ doPresentation(req, form); String contentName = getContentName(form); if (contentName != null) { /* Indicate we have a file attachment with the given name */ response.setHeader("Content-Disposition", "Attachment; Filename=\"" + contentName + "\""); } // Debugging action to test session serialization if (debug) { checkSerialize(request); } String appRoot = form.getPresentationState().getAppRoot(); if (appRoot != null) { // Embed in request for pages that cannot access the form (loggedOut) request.setAttribute("edu.rpi.sss.util.action.approot", appRoot); } /* ---------------------------------------------------------------- Everything is set up and ready to go. Execute something ---------------------------------------------------------------- */ if (!isPortlet) { forward = checkLogOut(request, form); } else { forward = null; } if (forward != null) { // Disable xslt filters response.setContentType("text/html"); } else { if (!isPortlet) { response.setContentType(defaultContentType); } forward = checkVarReq(req, form); if (forward == null) { forward = checkForwardto(request); } if (forward == null) { forward = performAction(req, messages); } } if (forward == null) { getLogger().warn("Forward = null"); err.emit("edu.rpi.sss.util.nullforward"); forward = "error"; } else if (forward.equals("FORWARD-NULL")) { forward = null; } if (err == null) { getLogger().warn("No errors object"); } else if (err.messagesEmitted()) { if (noActionErrors) { } else { ActionErrors aes = ((ErrorEmitSvlt)err).getErrors(); saveErrors(request, aes); } if (debug) { getLogger().debug(((ErrorEmitSvlt)err).getMsgList().size() + " errors emitted"); } } else if (debug) { getLogger().debug("No errors emitted"); } if (msg == null) { getLogger().warn("No messages object"); } else if (msg.messagesEmitted()) { ActionMessages ams = ((MessageEmitSvlt)msg).getMessages(); saveMessages(request, ams); if (debug) { getLogger().debug(ams.size() + " messages emitted"); } } else if (debug) { getLogger().debug("No messages emitted"); } if (debug) { getLogger().debug("exit to " + forward); } } catch (Throwable t) { if (debug) { getLogger().debug("Action exception: ", t); } err.emit(t); forward = "error"; } if (forward == null) { return null; } return (mapping.findForward(forward)); } protected void traceConfig(Request req) { ActionConfig[] actions = req.getMapping().getModuleConfig().findActionConfigs(); getLogger().debug("========== Action configs ==========="); for (ActionConfig aconfig: actions) { StringBuilder sb = new StringBuilder(); sb.append(aconfig.getPath()); String param = aconfig.getParameter(); boolean noActionType = traceConfigParam(sb, actionTypeKey, param, req.getForm()) == null; traceConfigParam(sb, actionTypeConversation, param, req.getForm()); traceConfigParam(sb, refreshIntervalKey, param, req.getForm()); traceConfigParam(sb, refreshActionKey, param, req.getForm()); getLogger().debug(sb.toString()); if (noActionType) { getLogger().debug("***** Warning: no action type specified ****"); } } } private String traceConfigParam(StringBuilder sb, String name, String param, UtilActionForm form) { String res = getStringActionPar(name, param, form); if (res == null) { return null; } sb.append(",\t"); sb.append(name); sb.append(res); return res; } /** Override this to get the contentName from different sources * * @param form * @return String name of content */ public String getContentName(UtilActionForm form) { String contentName = form.getPresentationState().getContentName(); form.setContentName(contentName); return contentName; } /** Set the global id to some name for logging * * @return String id */ public abstract String getId(); /** In a portlet environment a render action should override this to return * false to preserve messages. * * @return boolean true to clear messages */ public boolean clearMessages() { return true; } /** Override to return the name of the error object session attribute. * * @return String request attribute name. Null to suppress. */ public String getErrorObjAttrName() { return "edu.rpi.sss.util.errorobj"; } /** Override to return the name of the messages object session attribute. * * @return String request attribute name. Null to suppress. */ public String getMessageObjAttrName() { return "edu.rpi.sss.util.messageobj"; } /** Override to return a different name for the error exception property. * This must return non-null if getErrorObjAttrName returns a value. * * @return error exception property name */ public String getErrorObjErrProp() { return "edu.rpi.sss.util.error.exc"; } /** Overide this to set the value or turn off presentation support * by returning null or the value "NONE". * * @return presentation attr name */ public String getPresentationAttrName() { return PresentationState.presentationAttrName; } /** * @return message resources */ public MessageResources getMessages() { return messages; } /** * @param name * @return message identified by name */ public String getMessage(String name) { return messages.getMessage(name); } /** Allow user to explicitly set debugging. * * @param request Needed to locate session * @param form Action form */ private void checkDebug(HttpServletRequest request, UtilActionForm form) { String reqpar = request.getParameter("debug"); if (reqpar == null) { return; } boolean newDebug = (reqpar.equals("yes")); if (debug == newDebug) { // No change return; } debug = newDebug; form.setDebug(debug); } /* ==================================================================== * Log request * ==================================================================== */ class LogEntryImpl extends LogEntry { StringBuffer sb; HttpAppLogger logger; LogEntryImpl(StringBuffer sb, HttpAppLogger logger){ this.sb = sb; this.logger = logger; } /** Append to a log entry. Value should not contain colons or should be * the last element. * * @param val String element to append */ public void append(String val) { sb.append(":"); sb.append(val); } /** Concatenate some info without a delimiter. * * @param val String to concat */ public void concat(String val) { sb.append(val); } /** Emit the log entry */ public void emit() { logger.logIt(sb.toString()); } } /** Return a LogEntry containing the start of a log entry. * * @param request HttpServletRequest * @param logname String name for the log entry * @return LogEntry containing prefix */ public LogEntry getLogEntry(HttpServletRequest request, String logname) { StringBuffer sb = new StringBuffer(logname); sb.append(":"); sb.append(getSessionId(request)); sb.append(":"); sb.append(getLogPrefix(request)); return new LogEntryImpl(sb, this); } /** Log some information. * * @param request HttpServletRequest * @param logname String name for the log entry * @param info String information to log */ public void logInfo(HttpServletRequest request, String logname, String info) { LogEntry le = getLogEntry(request, logname); le.append(info); le.emit(); } /* (non-Javadoc) * @see edu.rpi.sss.util.log.HttpAppLogger#logRequest(javax.servlet.http.HttpServletRequest) */ public void logRequest(HttpServletRequest request) throws Throwable { LogEntry le = getLogEntry(request, "REQUEST"); le.append(request.getRemoteAddr()); le.append(HttpServletUtils.getUrl(request)); String q = request.getQueryString(); if (q != null) { le.concat("?"); le.concat(q); } le.emit(); String referrer = request.getHeader("Referer"); if (referrer == null) { referrer = "NONE"; } logInfo(request, "REFERRER", referrer); } /** Log the session counters for applications that maintain them. * * @param request HttpServletRequest * @param start true for session start * @param sessionNum long number of session * @param sessions long number of concurrent sessions */ public void logSessionCounts(HttpServletRequest request, boolean start, long sessionNum, long sessions) { LogEntry le; if (start) { le = getLogEntry(request, "SESSION-START"); } else { le = getLogEntry(request, "SESSION-END"); } le.append(String.valueOf(sessionNum)); le.append(String.valueOf(sessions)); le.emit(); } public void debugOut(String msg) { getLogger().debug(msg); } public void logIt(String msg) { getLogger().info(msg); } /** Get a prefix for the loggers. * * @param request HttpServletRequest * @return String log prefix */ protected String getLogPrefix(HttpServletRequest request) { try { if (logPrefix == null) { logPrefix = JspUtil.getProperty(getMessages(), "edu.rpi.sss.util.action.logprefix", "unknown"); } return logPrefix; } catch (Throwable t) { error(t); return "LOG-PREFIX-EXCEPTION"; } } /** Get the session id for the loggers. * * @param request * @return String session id */ private String getSessionId(HttpServletRequest request) { try { HttpSession sess = request.getSession(false); if (sess == null) { return "NO-SESSIONID"; } else { return sess.getId(); } } catch (Throwable t) { error(t); return "SESSION-ID-EXCEPTION"; } } /* ==================================================================== * Check logout * ==================================================================== */ /** Clean up - we're about to logout * * @param request HttpServletRequest * @param form * @return boolean true for OK to log out. False - not allowed - ignore it. */ protected boolean logOutCleanup(HttpServletRequest request, UtilActionForm form) { return true; } /** Check for logout request. * * @param request HttpServletRequest * @param form * @return null for continue, forwardLoggedOut to end session. * @throws Throwable */ protected String checkLogOut(HttpServletRequest request, UtilActionForm form) throws Throwable { String temp = request.getParameter(requestLogout); if (temp != null) { HttpSession sess = request.getSession(false); if ((sess != null) && logOutCleanup(request, form)) { sess.invalidate(); } return forwardLoggedOut; } return null; } /* ==================================================================== * Check nocache * ==================================================================== */ /* We handle our own nocache headers instead of letting struts do it. * Struts does it on every response but, if we are running with nocache, * we need to be able to disable it for the occassional response. * * <p>This gets around an IE problem when attempting to deliver files. * IE requires caching on or it is unable to locate the file it is * supposed to be delivering. * */ private void checkNocache(HttpServletRequest request, HttpServletResponse response, UtilActionForm form) { String reqpar = request.getParameter("nocacheSticky"); if (reqpar != null) { /* (re)set the default */ form.setNocache(reqpar.equals("yes")); } /** Look for a one-shot setting */ reqpar = request.getParameter("nocache"); if ((reqpar == null) && (!form.getNocache())) { return; } /** If we got a request parameter it overrides the default */ boolean nocache = form.getNocache(); if (reqpar != null) { nocache = reqpar.equals("yes"); } if (nocache) { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 1); } } /* ==================================================================== * Check serialization * ==================================================================== */ /* Debugging routine to see if we can serialize the session. * We see session serialization errors in the web container if an * unserializable object class gets embedded in the session somewhere */ private void checkSerialize(HttpServletRequest request) { String reqpar = request.getParameter("serialize"); if (reqpar == null) { return; } HttpSession sess = request.getSession(false); Enumeration en = sess.getAttributeNames(); while (en.hasMoreElements()) { String attrname = (String)en.nextElement(); ObjectOutputStream oo = null; logIt("Attempt to serialize attr " + attrname); Object o = sess.getAttribute(attrname); try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); oo = new ObjectOutputStream(bo); oo.writeObject(o); oo.flush(); logIt("Serialized object " + attrname + " has size: " + bo.size()); } catch (Throwable t) { t.printStackTrace(); } finally { if (oo != null) { try { oo.close(); } catch (Throwable t) {} } } } } /* ==================================================================== * Response methods * ==================================================================== */ /** Check request for refresh interval * * @param request * @param response * @param refreshInterval * @param refreshAction * @param form */ public void setRefreshInterval(HttpServletRequest request, HttpServletResponse response, int refreshInterval, String refreshAction, UtilActionForm form) { if (refreshInterval != 0) { StringBuilder sb = new StringBuilder(250); sb.append(refreshInterval); sb.append("; URL="); sb.append(form.getUrlPrefix()); if (!refreshAction.startsWith("/")) { sb.append("/"); } sb.append(refreshAction); response.setHeader("Refresh", sb.toString()); } } protected Integer getRefreshInt(UtilActionForm form) { return getIntActionPar(refreshIntervalKey, form); } protected String getRefreshAction(UtilActionForm form) { return getStringActionPar(refreshActionKey, form); } protected Integer getIntActionPar(String name, UtilActionForm form) { return getIntActionPar(name, form.getActionParameter(), form); } protected String getStringActionPar(String name, UtilActionForm form) { return getStringActionPar(name, form.getActionParameter(), form); } protected Integer getIntActionPar(String name, String par, UtilActionForm form) { if (par == null) { return null; } try { int pos = par.indexOf(name); if (pos < 0) { return null; } pos += name.length(); int epos = par.indexOf(";", pos); if (epos < 0) { epos = par.length(); } return Integer.valueOf(par.substring(pos, epos)); } catch (Throwable t) { form.getErr().emit("edu.rpi.bad.actionparameter", par); return null; } } protected String getStringActionPar(String name, String par, UtilActionForm form) { if (par == null) { return null; } try { int pos = par.indexOf(name); if (pos < 0) { return null; } pos += name.length(); int epos = par.indexOf(";", pos); if (epos < 0) { epos = par.length(); } return par.substring(pos, epos); } catch (Throwable t) { form.getErr().emit("edu.rpi.bad.actionparameter", par); return null; } } /* ==================================================================== * Application variable methods * ==================================================================== */ /** * @param request * @return app vars */ @SuppressWarnings("unchecked") public HashMap<String, String> getAppVars(Request request) { Object o = request.getSessionAttr("edu.rpi.sss.util.UtilAbstractAction.appVars"); if ((o == null) || (!(o instanceof HashMap))) { o = new HashMap<String, String>(); request.setSessionAttr("edu.rpi.sss.util.UtilAbstractAction.appVars", o); } return (HashMap<String, String>)o; } private static final int maxAppVars = 50; // Stop screwing around. /** Check for action setting a variable * We expect the request parameter to be of the form<br/> * setappvar=name(value) or <br/> * setappvar=name{value}<p>. * Currently we're not escaping characters so if you want both right * terminators in the value you're out of luck - actually we cheat a bit * We just look at the last char and then look for that from the start. * * @param request Needed to locate session * @param form Action form * @return String forward to here. null if no error found. * @throws Throwable */ private String checkVarReq(Request request, UtilActionForm form) throws Throwable { Collection<String> avs = request.getReqPars("setappvar"); if (avs == null) { return null; } HashMap<String, String> appVars = getAppVars(request); for (String reqpar: avs) { int start; if (reqpar.endsWith("}")) { start = reqpar.indexOf('{'); } else if (reqpar.endsWith(")")) { start = reqpar.indexOf('('); } else { return "badRequest"; } if (start < 0) { return "badRequest"; } String varName = reqpar.substring(0, start); String varVal = reqpar.substring(start + 1, reqpar.length() - 1); if (varVal.length() == 0) { varVal = null; } if (!setAppVar(varName, varVal, appVars)) { return "badRequest"; } } form.setAppVarsTbl(appVars); return null; } /** Called to set an application variable to a value * * @param name name of variable * @param val new value of variable - null means remove. * @param appVars * @return boolean True if ok - false for too many vars */ public boolean setAppVar(String name, String val, HashMap<String, String> appVars) { if (val == null) { appVars.remove(name); return true; } if (appVars.size() > maxAppVars) { return false; } appVars.put(name, val); return true; } /* ==================================================================== * Forward methods * ==================================================================== */ /** Check for action forwarding * We expect the request parameter to be of the form<br/> * forward=name<p>. * * @param request Needed to locate session * @return String forward to here. null if no forward found. * @throws Throwable */ private String checkForwardto(HttpServletRequest request) throws Throwable { String reqpar = request.getParameter("forwardto"); return reqpar; } /* ==================================================================== * Confirmation id methods * ==================================================================== */ /** Check for a confirmation id. This is a random string embedded * in some requests to confirm that the incoming request came from a page * we generated. Not all pages will have such an id but if we do it must * match. * * We expect the request parameter to be of the form<br/> * confirmationid=id<p>. * * @param request Needed to locate session * @param form * @return String forward to here on error. null for OK. * @throws Throwable */ protected String checkConfirmationId(HttpServletRequest request, UtilActionForm form) throws Throwable { String reqpar = request.getParameter("confirmationid"); if (reqpar == null) { return null; } if (!reqpar.equals(form.getConfirmationId())) { return "badConformationId"; } return null; } /** Require a confirmation id. This is a random string embedded * in some requests to confirm that the incoming request came from a page * we generated. Not all pages will have such an id but if we do it must * match. * * We expect the request parameter to be of the form<br/> * confirmationid=id<p>. * * @param request Needed to locate session * @param form * @return String forward to here on error. null for OK. * @throws Throwable */ protected String requireConfirmationId(HttpServletRequest request, UtilActionForm form) throws Throwable { String reqpar = request.getParameter("confirmationid"); if (reqpar == null) { return "missingConformationId"; } if (!reqpar.equals(form.getConfirmationId())) { return "badConformationId"; } return null; } /* ==================================================================== * Presentation state methods * ==================================================================== */ /** * @param request * @param form */ public void doPresentation(Request request, UtilActionForm form) { PresentationState ps = getPresentationState(request, form); if (ps == null) { if (debug) { debugOut("No presentation state"); } return; } if (debug) { debugOut("Set presentation state"); } HttpServletRequest req = request.getRequest(); ps.checkBrowserType(req); ps.checkContentType(req); ps.checkContentName(req); ps.checkNoXSLT(req); ps.checkRefreshXslt(req); ps.checkSkinName(req); form.setPresentationState(ps); request.setSessionAttr(getPresentationAttrName(), ps); if (debug) { ps.debugDump("action", getLogger()); } } /** * @param request * @param form * @return PresentationState */ public PresentationState getPresentationState(Request request, UtilActionForm form) { String attrName = getPresentationAttrName(); if ((attrName == null) || (attrName.equals("NONE"))) { return null; } Object o = request.getSessionAttr(attrName); if ((o == null) || (!(o instanceof PresentationState))) { PresentationState ps = new PresentationState(); ps.setBrowserType(form.getBrowserType()); try { ps.setNoXSLTSticky(JspUtil.getProperty(messages, "edu.rpi.sss.util.action.noxslt", "no").equals("yes")); } catch (Throwable t) { t.printStackTrace(); } request.setSessionAttr(attrName, ps); return ps; } return (PresentationState)o; } /* ================================================================== Various utility methods ================================================================== */ /* * Set the value of a named session attribute. * * @param request Needed to locate session * @param attrName Name of the attribute * @param val Object * / public void setSessionAttr(HttpServletRequest request, String attrName, Object val) { HttpSession sess = request.getSession(false); if (sess == null) { return; } sess.setAttribute(attrName, val); } /* * Return the value of a named session attribute. * * @param request Needed to locate session * @param attrName Name of the attribute * @return Object Attribute value or null * / public Object getSessionAttr(HttpServletRequest request, String attrName) { HttpSession sess = request.getSession(false); if (sess == null) { return null; } return sess.getAttribute(attrName); } */ /** Return the value of a required named resource. * * @param resName Name of the property * @return String Resource value or null * @throws Throwable */ public String getReqRes(String resName) throws Throwable { return JspUtil.getReqProperty(messages, resName); } /** * @param req * @return boolean true for portlet */ public boolean isPortletRequest(HttpServletRequest req) { // JSR 168 requires this attribute be present return req.getAttribute("javax.portlet.request") != null; } /** Get a request parameter stripped of white space. Return null for zero * length. * * @param req * @param name name of parameter * @return String value * @throws Throwable */ protected String getReqPar(HttpServletRequest req, String name) throws Throwable { return Util.checkNull(req.getParameter(name)); } /** Get a multi-valued request parameter stripped of white space. * Return null for zero length. * * @param req * @param name name of parameter * @return Collection<String> or null * @throws Throwable */ protected Collection<String> getReqPars(HttpServletRequest req, String name) throws Throwable { String[] s = req.getParameterValues(name); ArrayList<String> res = null; if ((s == null) || (s.length == 0)) { return null; } for (String par: s) { par = Util.checkNull(par); if (par != null) { if (res == null) { res = new ArrayList<String>(); } res.add(par); } } return res; } /* * Get an Integer request parameter or null. * * @param req * @param name name of parameter * @return Integer value or null * @throws Throwable * / protected Integer getIntReqPar(HttpServletRequest req, String name) throws Throwable { String reqpar = getReqPar(req, name); if (reqpar == null) { return null; } return Integer.valueOf(reqpar); } /* * Get an Integer request parameter or null. Emit error for non-null and * non integer * * @param req * @param name name of parameter * @param err name of parameter * @param errProp * @return Integer value or null * @throws Throwable * / protected Integer getIntReqPar(HttpServletRequest req, String name, MessageEmit err, String errProp) throws Throwable { String reqpar = getReqPar(req, name); if (reqpar == null) { return null; } try { return Integer.valueOf(reqpar); } catch (Throwable t) { err.emit(errProp, reqpar); return null; } } /* * Get an integer valued request parameter. * * @param req * @param name name of parameter * @param defaultVal * @return int value * @throws Throwable * / protected int getIntReqPar(HttpServletRequest req, String name, int defaultVal) throws Throwable { String reqpar = req.getParameter(name); if (reqpar == null) { return defaultVal; } try { return Integer.parseInt(reqpar); } catch (Throwable t) { return defaultVal; // XXX exception? } } /* * Get a Long request parameter or null. * * @param req * @param name name of parameter * @return Long value or null * @throws Throwable * / protected Long getLongReqPar(HttpServletRequest req, String name) throws Throwable { String reqpar = getReqPar(req, name); if (reqpar == null) { return null; } return Long.valueOf(reqpar); } /* * Get an long valued request parameter. * * @param req * @param name name of parameter * @param defaultVal * @return long value * @throws Throwable * / protected long getLongReqPar(HttpServletRequest req, String name, long defaultVal) throws Throwable { String reqpar = req.getParameter(name); if (reqpar == null) { return defaultVal; } try { return Long.parseLong(reqpar); } catch (Throwable t) { return defaultVal; // XXX exception? } } /* * Get a boolean valued request parameter. * * @param req * @param name name of parameter * @return Boolean value or null for absent parameter * @throws Throwable * / protected Boolean getBooleanReqPar(HttpServletRequest req, String name) throws Throwable { String reqpar = req.getParameter(name); if (reqpar == null) { return null; } try { return Boolean.valueOf(reqpar); } catch (Throwable t) { return null; // XXX exception? } } /* * Get a boolean valued request parameter giving a default value. * * @param req * @param name name of parameter * @param defVal default value for absent parameter * @return boolean value * @throws Throwable * / protected boolean getBooleanReqPar(HttpServletRequest req, String name, boolean defVal) throws Throwable { boolean val = defVal; Boolean valB = getBooleanReqPar(req, name); if (valB != null) { val = valB.booleanValue(); } return val; } */ /* ================================================================== Private methods ================================================================== */ /** Get the error object. If we haven't already got one and * getErrorObjAttrName returns non-null create one and implant it in * the session. * * @param request Needed to locate session * @param messages Resources * @return ErrorEmitSvlt */ private ErrorEmitSvlt getErrorObj(HttpServletRequest request, MessageResources messages) { return (ErrorEmitSvlt)JspUtil.getErrorObj(getId(), this, request, messages, getErrorObjAttrName(), getErrorObjErrProp(), noActionErrors, clearMessages(), debug); } /** Get the message object. If we haven't already got one and * getMessageObjAttrName returns non-null create one and implant it in * the session. * * @param request Needed to locate session * @param messages Resources * @return MessageEmitSvlt */ private MessageEmitSvlt getMessageObj(HttpServletRequest request, MessageResources messages) { return (MessageEmitSvlt)JspUtil.getMessageObj(getId(), this, request, messages, getMessageObjAttrName(), getErrorObjErrProp(), clearMessages(), debug); } /** * @param req */ public void dumpRequest(HttpServletRequest req) { Logger log = getLogger(); try { Enumeration names = req.getParameterNames(); String title = "Request parameters"; log.debug(title + " - global info and uris"); log.debug("getRequestURI = " + req.getRequestURI()); log.debug("getRemoteUser = " + req.getRemoteUser()); log.debug("getRequestedSessionId = " + req.getRequestedSessionId()); log.debug("HttpUtils.getRequestURL(req) = " + req.getRequestURL()); log.debug("query=" + req.getQueryString()); log.debug("contentlen=" + req.getContentLength()); log.debug("request=" + req); log.debug("parameters:"); log.debug(title); while (names.hasMoreElements()) { String key = (String)names.nextElement(); String val = req.getParameter(key); log.debug(" " + key + " = \"" + val + "\""); } } catch (Throwable t) { } } /** * @return Logger */ public Logger getLogger() { if (log == null) { log = Logger.getLogger(this.getClass()); } return log; } /** Info message * * @param msg */ public void info(String msg) { getLogger().info(msg); } /** Warning message * * @param msg */ public void warn(String msg) { getLogger().warn(msg); } /** * @param msg */ public void debugMsg(String msg) { getLogger().debug(msg); } /** * @param t */ public void error(Throwable t) { getLogger().error(this, t); } }
true
true
public ActionForward execute(ActionMapping mapping, ActionForm frm, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ErrorEmitSvlt err = null; MessageEmitSvlt msg = null; String forward = "success"; UtilActionForm form = (UtilActionForm)frm; try { messages = getResources(request); /* Explicitly set logging on/off with an init parameter. Basing debugging off the state of log4j turns out to be too inflexible - for example, we have many applications with exactly the same code, basing logging on class names doesn't work. */ String debugVal = servlet.getServletConfig().getServletContext().getInitParameter("debug"); debug = !"0".equals(debugVal); checkDebug(request, form); isPortlet = isPortletRequest(request); noActionErrors = JspUtil.getProperty(messages, "edu.rpi.sss.util.action.noactionerrors", "no").equals("yes"); err = getErrorObj(request, messages); msg = getMessageObj(request, messages); /** Log the request - virtual domains can make it difficult to * distinguish applications. */ logRequest(request); if (debug) { debugOut("entry"); debugOut("================================"); debugOut("isPortlet=" + isPortlet); Enumeration en = servlet.getInitParameterNames(); while (en.hasMoreElements()) { debugOut("attr name=" + en.nextElement()); } debugOut("================================"); dumpRequest(request); } if (!form.getInitialised()) { // Do one time settings form.setNocache( JspUtil.getProperty(messages, "edu.rpi.sss.util.action.nocache", "no").equals("yes")); form.setInitialised(true); } form.setLog(getLogger()); form.setDebug(debug); form.setMres(messages); form.setBrowserType(JspUtil.getBrowserType(request)); form.assignCurrentUser(request.getRemoteUser()); form.setUrl(JspUtil.getUrl(request)); form.setSchemeHostPort(JspUtil.getURLshp(request)); form.setContext(JspUtil.getContext(request)); form.setUrlPrefix(JspUtil.getURLPrefix(request)); form.setActionPath(mapping.getPath()); form.setMapping(mapping); form.setActionParameter(mapping.getParameter()); form.setErr(err); form.setMsg(msg); form.assignSessionId(getSessionId(request)); checkNocache(request, response, form); String defaultContentType = JspUtil.getProperty(messages, "edu.rpi.sss.util.action.contenttype", "text/html"); Request req = new Request(request, response, form, this); String actionType = getStringActionPar(actionTypeKey, form); if (actionType != null) { for (int ati = 0; ati < Request.actionTypes.length; ati++) { if (Request.actionTypes[ati].equals(actionType)) { req.setActionType(ati); break; } } } /** Set up presentation values from request */ doPresentation(req, form); String contentName = getContentName(form); if (contentName != null) { /* Indicate we have a file attachment with the given name */ response.setHeader("Content-Disposition", "Attachment; Filename=\"" + contentName + "\""); } // Debugging action to test session serialization if (debug) { checkSerialize(request); } String appRoot = form.getPresentationState().getAppRoot(); if (appRoot != null) { // Embed in request for pages that cannot access the form (loggedOut) request.setAttribute("edu.rpi.sss.util.action.approot", appRoot); } /* ---------------------------------------------------------------- Everything is set up and ready to go. Execute something ---------------------------------------------------------------- */ if (!isPortlet) { forward = checkLogOut(request, form); } else { forward = null; } if (forward != null) { // Disable xslt filters response.setContentType("text/html"); } else { if (!isPortlet) { response.setContentType(defaultContentType); } forward = checkVarReq(req, form); if (forward == null) { forward = checkForwardto(request); } if (forward == null) { forward = performAction(req, messages); } } if (forward == null) { getLogger().warn("Forward = null"); err.emit("edu.rpi.sss.util.nullforward"); forward = "error"; } else if (forward.equals("FORWARD-NULL")) { forward = null; } if (err == null) { getLogger().warn("No errors object"); } else if (err.messagesEmitted()) { if (noActionErrors) { } else { ActionErrors aes = ((ErrorEmitSvlt)err).getErrors(); saveErrors(request, aes); } if (debug) { getLogger().debug(((ErrorEmitSvlt)err).getMsgList().size() + " errors emitted"); } } else if (debug) { getLogger().debug("No errors emitted"); } if (msg == null) { getLogger().warn("No messages object"); } else if (msg.messagesEmitted()) { ActionMessages ams = ((MessageEmitSvlt)msg).getMessages(); saveMessages(request, ams); if (debug) { getLogger().debug(ams.size() + " messages emitted"); } } else if (debug) { getLogger().debug("No messages emitted"); } if (debug) { getLogger().debug("exit to " + forward); } } catch (Throwable t) { if (debug) { getLogger().debug("Action exception: ", t); } err.emit(t); forward = "error"; } if (forward == null) { return null; } return (mapping.findForward(forward)); }
public ActionForward execute(ActionMapping mapping, ActionForm frm, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ErrorEmitSvlt err = null; MessageEmitSvlt msg = null; String forward = "success"; UtilActionForm form = (UtilActionForm)frm; try { messages = getResources(request); /* Explicitly set logging on/off with an init parameter. Basing debugging off the state of log4j turns out to be too inflexible - for example, we have many applications with exactly the same code, basing logging on class names doesn't work. */ String debugVal = servlet.getServletConfig().getServletContext().getInitParameter("debug"); debug = !"0".equals(debugVal); checkDebug(request, form); isPortlet = isPortletRequest(request); noActionErrors = JspUtil.getProperty(messages, "edu.rpi.sss.util.action.noactionerrors", "no").equals("yes"); err = getErrorObj(request, messages); msg = getMessageObj(request, messages); /** Log the request - virtual domains can make it difficult to * distinguish applications. */ logRequest(request); if (debug) { debugOut("entry"); debugOut("================================"); debugOut("isPortlet=" + isPortlet); Enumeration en = servlet.getInitParameterNames(); while (en.hasMoreElements()) { debugOut("attr name=" + en.nextElement()); } debugOut("================================"); dumpRequest(request); } if (!form.getInitialised()) { // Do one time settings form.setNocache( JspUtil.getProperty(messages, "edu.rpi.sss.util.action.nocache", "no").equals("yes")); form.setInitialised(true); } form.setLog(getLogger()); form.setDebug(debug); form.setMres(messages); form.setBrowserType(JspUtil.getBrowserType(request)); form.assignCurrentUser(request.getRemoteUser()); form.setUrl(JspUtil.getUrl(request)); form.setSchemeHostPort(JspUtil.getURLshp(request)); form.setContext(JspUtil.getContext(request)); form.setUrlPrefix(JspUtil.getURLPrefix(request)); form.setActionPath(mapping.getPath()); form.setMapping(mapping); form.setActionParameter(mapping.getParameter()); form.setErr(err); form.setMsg(msg); form.assignSessionId(getSessionId(request)); checkNocache(request, response, form); String defaultContentType = JspUtil.getProperty(messages, "edu.rpi.sss.util.action.contenttype", "text/html"); Request req = new Request(request, response, form, this); String actionType = getStringActionPar(actionTypeKey, form); if (actionType != null) { for (int ati = 0; ati < Request.actionTypes.length; ati++) { if (Request.actionTypes[ati].equals(actionType)) { req.setActionType(ati); break; } } } /** Set up presentation values from request */ doPresentation(req, form); String contentName = getContentName(form); if (contentName != null) { /* Indicate we have a file attachment with the given name */ response.setHeader("Content-Disposition", "Attachment; Filename=\"" + contentName + "\""); } // Debugging action to test session serialization if (debug) { checkSerialize(request); } String appRoot = form.getPresentationState().getAppRoot(); if (appRoot != null) { // Embed in request for pages that cannot access the form (loggedOut) request.setAttribute("edu.rpi.sss.util.action.approot", appRoot); } /* ---------------------------------------------------------------- Everything is set up and ready to go. Execute something ---------------------------------------------------------------- */ if (!isPortlet) { forward = checkLogOut(request, form); } else { forward = null; } if (forward != null) { // Disable xslt filters response.setContentType("text/html"); } else { if (!isPortlet) { response.setContentType(defaultContentType); } forward = checkVarReq(req, form); if (forward == null) { forward = checkForwardto(request); } if (forward == null) { forward = performAction(req, messages); } } if (forward == null) { getLogger().warn("Forward = null"); err.emit("edu.rpi.sss.util.nullforward"); forward = "error"; } else if (forward.equals("FORWARD-NULL")) { forward = null; } if (err == null) { getLogger().warn("No errors object"); } else if (err.messagesEmitted()) { if (noActionErrors) { } else { ActionErrors aes = ((ErrorEmitSvlt)err).getErrors(); saveErrors(request, aes); } if (debug) { getLogger().debug(((ErrorEmitSvlt)err).getMsgList().size() + " errors emitted"); } } else if (debug) { getLogger().debug("No errors emitted"); } if (msg == null) { getLogger().warn("No messages object"); } else if (msg.messagesEmitted()) { ActionMessages ams = ((MessageEmitSvlt)msg).getMessages(); saveMessages(request, ams); if (debug) { getLogger().debug(ams.size() + " messages emitted"); } } else if (debug) { getLogger().debug("No messages emitted"); } if (debug) { getLogger().debug("exit to " + forward); } } catch (Throwable t) { if (debug) { getLogger().debug("Action exception: ", t); } err.emit(t); forward = "error"; } if (forward == null) { return null; } return (mapping.findForward(forward)); }
diff --git a/src/web/org/codehaus/groovy/grails/web/mapping/filter/UrlMappingsFilter.java b/src/web/org/codehaus/groovy/grails/web/mapping/filter/UrlMappingsFilter.java index 65662fb9b..c5a6c08ff 100644 --- a/src/web/org/codehaus/groovy/grails/web/mapping/filter/UrlMappingsFilter.java +++ b/src/web/org/codehaus/groovy/grails/web/mapping/filter/UrlMappingsFilter.java @@ -1,188 +1,188 @@ /* Copyright 2004-2005 Graeme Rocher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.mapping.filter; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.commons.ControllerArtefactHandler; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsClass; import org.codehaus.groovy.grails.web.mapping.UrlMappingInfo; import org.codehaus.groovy.grails.web.mapping.UrlMappingsHolder; import org.codehaus.groovy.grails.web.servlet.GrailsUrlPathHelper; import org.codehaus.groovy.grails.web.servlet.WrappedResponseHolder; import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes; import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.UrlPathHelper; import org.springframework.web.util.WebUtils; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * <p>A Servlet filter that uses the Grails UrlMappings to match and forward requests to a relevant controller * and action * * @author Graeme Rocher * @since 0.5 * * * <p/> * Created: Mar 6, 2007 * Time: 7:58:19 AM */ public class UrlMappingsFilter extends OncePerRequestFilter { private UrlPathHelper urlHelper = new UrlPathHelper(); private static final char SLASH = '/'; private static final Log LOG = LogFactory.getLog(UrlMappingsFilter.class); protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { UrlMappingsHolder holder = lookupUrlMappings(); GrailsApplication application = lookupApplication(); GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST); GrailsClass[] controllers = application.getArtefacts(ControllerArtefactHandler.TYPE); if(controllers == null || controllers.length == 0 || holder == null) { processFilterChain(request, response, filterChain); return; } if(LOG.isDebugEnabled()) { LOG.debug("Executing URL mapping filter..."); LOG.debug(holder); } String uri = urlHelper.getPathWithinApplication(request); UrlMappingInfo[] urlInfos = holder.matchAll(uri); WrappedResponseHolder.setWrappedResponse(response); boolean dispatched = false; try { for (int i = 0; i < urlInfos.length; i++) { UrlMappingInfo info = urlInfos[i]; if(info!=null) { String action = info.getActionName() == null ? "" : info.getActionName(); + info.configure(webRequest); GrailsClass controller = application.getArtefactForFeature(ControllerArtefactHandler.TYPE, SLASH + info.getControllerName() + SLASH + action); if(controller == null) { continue; } dispatched = true; - info.configure(webRequest); String forwardUrl = buildDispatchUrlForMapping(request, info); if(LOG.isDebugEnabled()) { LOG.debug("Matched URI ["+uri+"] to URL mapping ["+info+"], forwarding to ["+forwardUrl+"] with response ["+response.getClass()+"]"); } //populateParamsForMapping(info); RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl); populateWebRequestWithInfo(webRequest, info); WebUtils.exposeForwardRequestAttributes(request); dispatcher.forward(request, response); break; } } } finally { WrappedResponseHolder.setWrappedResponse(null); } if(!dispatched) { if(LOG.isDebugEnabled()) { LOG.debug("No match found, processing remaining filter chain."); } processFilterChain(request, response, filterChain); } } private void processFilterChain(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { try { WrappedResponseHolder.setWrappedResponse(response); filterChain.doFilter(request,response); } finally { WrappedResponseHolder.setWrappedResponse(null); } return; } protected static void populateWebRequestWithInfo(GrailsWebRequest webRequest, UrlMappingInfo info) { if(webRequest != null) { webRequest.setControllerName(info.getControllerName()); webRequest.setActionName(info.getActionName()); String id = info.getId(); if(!StringUtils.isBlank(id))webRequest.getParams().put(GrailsWebRequest.ID_PARAMETER, id); } } /** * Constructs the URI to forward to using the given request and UrlMappingInfo instance * * @param request The HttpServletRequest * @param info The UrlMappingInfo * @return The URI to forward to */ protected static String buildDispatchUrlForMapping(HttpServletRequest request, UrlMappingInfo info) { StringBuffer forwardUrl = new StringBuffer(GrailsUrlPathHelper.GRAILS_SERVLET_PATH); forwardUrl.append(SLASH) .append(info.getControllerName()); if(!StringUtils.isBlank(info.getActionName())) { forwardUrl.append(SLASH) .append(info.getActionName()); } forwardUrl.append(GrailsUrlPathHelper.GRAILS_DISPATCH_EXTENSION); return forwardUrl.toString(); } /** * Looks up the UrlMappingsHolder instance * * @return The UrlMappingsHolder */ protected UrlMappingsHolder lookupUrlMappings() { WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); return (UrlMappingsHolder)wac.getBean(UrlMappingsHolder.BEAN_ID); } /** * Looks up the GrailsApplication instance * * @return The GrailsApplication instance */ protected GrailsApplication lookupApplication() { WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); return (GrailsApplication)wac.getBean(GrailsApplication.APPLICATION_ID); } }
false
true
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { UrlMappingsHolder holder = lookupUrlMappings(); GrailsApplication application = lookupApplication(); GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST); GrailsClass[] controllers = application.getArtefacts(ControllerArtefactHandler.TYPE); if(controllers == null || controllers.length == 0 || holder == null) { processFilterChain(request, response, filterChain); return; } if(LOG.isDebugEnabled()) { LOG.debug("Executing URL mapping filter..."); LOG.debug(holder); } String uri = urlHelper.getPathWithinApplication(request); UrlMappingInfo[] urlInfos = holder.matchAll(uri); WrappedResponseHolder.setWrappedResponse(response); boolean dispatched = false; try { for (int i = 0; i < urlInfos.length; i++) { UrlMappingInfo info = urlInfos[i]; if(info!=null) { String action = info.getActionName() == null ? "" : info.getActionName(); GrailsClass controller = application.getArtefactForFeature(ControllerArtefactHandler.TYPE, SLASH + info.getControllerName() + SLASH + action); if(controller == null) { continue; } dispatched = true; info.configure(webRequest); String forwardUrl = buildDispatchUrlForMapping(request, info); if(LOG.isDebugEnabled()) { LOG.debug("Matched URI ["+uri+"] to URL mapping ["+info+"], forwarding to ["+forwardUrl+"] with response ["+response.getClass()+"]"); } //populateParamsForMapping(info); RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl); populateWebRequestWithInfo(webRequest, info); WebUtils.exposeForwardRequestAttributes(request); dispatcher.forward(request, response); break; } } } finally { WrappedResponseHolder.setWrappedResponse(null); } if(!dispatched) { if(LOG.isDebugEnabled()) { LOG.debug("No match found, processing remaining filter chain."); } processFilterChain(request, response, filterChain); } }
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { UrlMappingsHolder holder = lookupUrlMappings(); GrailsApplication application = lookupApplication(); GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST); GrailsClass[] controllers = application.getArtefacts(ControllerArtefactHandler.TYPE); if(controllers == null || controllers.length == 0 || holder == null) { processFilterChain(request, response, filterChain); return; } if(LOG.isDebugEnabled()) { LOG.debug("Executing URL mapping filter..."); LOG.debug(holder); } String uri = urlHelper.getPathWithinApplication(request); UrlMappingInfo[] urlInfos = holder.matchAll(uri); WrappedResponseHolder.setWrappedResponse(response); boolean dispatched = false; try { for (int i = 0; i < urlInfos.length; i++) { UrlMappingInfo info = urlInfos[i]; if(info!=null) { String action = info.getActionName() == null ? "" : info.getActionName(); info.configure(webRequest); GrailsClass controller = application.getArtefactForFeature(ControllerArtefactHandler.TYPE, SLASH + info.getControllerName() + SLASH + action); if(controller == null) { continue; } dispatched = true; String forwardUrl = buildDispatchUrlForMapping(request, info); if(LOG.isDebugEnabled()) { LOG.debug("Matched URI ["+uri+"] to URL mapping ["+info+"], forwarding to ["+forwardUrl+"] with response ["+response.getClass()+"]"); } //populateParamsForMapping(info); RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl); populateWebRequestWithInfo(webRequest, info); WebUtils.exposeForwardRequestAttributes(request); dispatcher.forward(request, response); break; } } } finally { WrappedResponseHolder.setWrappedResponse(null); } if(!dispatched) { if(LOG.isDebugEnabled()) { LOG.debug("No match found, processing remaining filter chain."); } processFilterChain(request, response, filterChain); } }
diff --git a/src/main/java/org/apache/bcel/classfile/ClassParser.java b/src/main/java/org/apache/bcel/classfile/ClassParser.java index 69514477..0cb7751e 100644 --- a/src/main/java/org/apache/bcel/classfile/ClassParser.java +++ b/src/main/java/org/apache/bcel/classfile/ClassParser.java @@ -1,295 +1,297 @@ /* * Copyright 2000-2004 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.bcel.classfile; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.bcel.Constants; /** * Wrapper class that parses a given Java .class file. The method <A * href ="#parse">parse</A> returns a <A href ="JavaClass.html"> * JavaClass</A> object on success. When an I/O error or an * inconsistency occurs an appropiate exception is propagated back to * the caller. * * The structure and the names comply, except for a few conveniences, * exactly with the <A href="ftp://java.sun.com/docs/specs/vmspec.ps"> * JVM specification 1.0</a>. See this paper for * further details about the structure of a bytecode file. * * @version $Id$ * @author <A HREF="mailto:[email protected]">M. Dahm</A> */ public final class ClassParser { private DataInputStream file; private boolean fileOwned; private String file_name; private String zip_file; private int class_name_index, superclass_name_index; private int major, minor; // Compiler version private int access_flags; // Access rights of parsed class private int[] interfaces; // Names of implemented interfaces private ConstantPool constant_pool; // collection of constants private Field[] fields; // class fields, i.e., its variables private Method[] methods; // methods defined in the class private Attribute[] attributes; // attributes defined in the class private boolean is_zip; // Loaded from zip file private static final int BUFSIZE = 8192; /** * Parse class from the given stream. * * @param file Input stream * @param file_name File name */ public ClassParser(InputStream file, String file_name) { this.file_name = file_name; fileOwned = false; String clazz = file.getClass().getName(); // Not a very clean solution ... is_zip = clazz.startsWith("java.util.zip.") || clazz.startsWith("java.util.jar."); if (file instanceof DataInputStream) { this.file = (DataInputStream) file; } else { this.file = new DataInputStream(new BufferedInputStream(file, BUFSIZE)); } } /** Parse class from given .class file. * * @param file_name file name */ public ClassParser(String file_name) throws IOException { is_zip = false; this.file_name = file_name; fileOwned = true; } /** Parse class from given .class file in a ZIP-archive * * @param zip_file zip file name * @param file_name file name */ public ClassParser(String zip_file, String file_name) { is_zip = true; fileOwned = true; this.zip_file = zip_file; this.file_name = file_name; } /** * Parse the given Java class file and return an object that represents * the contained data, i.e., constants, methods, fields and commands. * A <em>ClassFormatException</em> is raised, if the file is not a valid * .class file. (This does not include verification of the byte code as it * is performed by the java interpreter). * * @return Class object representing the parsed class file * @throws IOException * @throws ClassFormatException */ public JavaClass parse() throws IOException, ClassFormatException { ZipFile zip = null; try { if (fileOwned) { if (is_zip) { zip = new ZipFile(zip_file); ZipEntry entry = zip.getEntry(file_name); file = new DataInputStream(new BufferedInputStream(zip.getInputStream(entry), BUFSIZE)); } else { file = new DataInputStream(new BufferedInputStream(new FileInputStream( file_name), BUFSIZE)); } } /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } } finally { // Read everything of interest, so close the file if (fileOwned) { - file.close(); + if (file != null) { + file.close(); + } if (zip != null) { zip.close(); } } } // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes, is_zip ? JavaClass.ZIP : JavaClass.FILE); } /** * Read information about the attributes of the class. * @throws IOException * @throws ClassFormatException */ private final void readAttributes() throws IOException, ClassFormatException { int attributes_count; attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(file, constant_pool); } } /** * Read information about the class and its super class. * @throws IOException * @throws ClassFormatException */ private final void readClassInfo() throws IOException, ClassFormatException { access_flags = file.readUnsignedShort(); /* Interfaces are implicitely abstract, the flag should be set * according to the JVM specification. */ if ((access_flags & Constants.ACC_INTERFACE) != 0) { access_flags |= Constants.ACC_ABSTRACT; } if (((access_flags & Constants.ACC_ABSTRACT) != 0) && ((access_flags & Constants.ACC_FINAL) != 0)) { throw new ClassFormatException("Class " + file_name + " can't be both final and abstract"); } class_name_index = file.readUnsignedShort(); superclass_name_index = file.readUnsignedShort(); } /** * Read constant pool entries. * @throws IOException * @throws ClassFormatException */ private final void readConstantPool() throws IOException, ClassFormatException { constant_pool = new ConstantPool(file); } /** * Read information about the fields of the class, i.e., its variables. * @throws IOException * @throws ClassFormatException */ private final void readFields() throws IOException, ClassFormatException { int fields_count; fields_count = file.readUnsignedShort(); fields = new Field[fields_count]; for (int i = 0; i < fields_count; i++) { fields[i] = new Field(file, constant_pool); } } /******************** Private utility methods **********************/ /** * Check whether the header of the file is ok. * Of course, this has to be the first action on successive file reads. * @throws IOException * @throws ClassFormatException */ private final void readID() throws IOException, ClassFormatException { int magic = 0xCAFEBABE; if (file.readInt() != magic) { throw new ClassFormatException(file_name + " is not a Java .class file"); } } /** * Read information about the interfaces implemented by this class. * @throws IOException * @throws ClassFormatException */ private final void readInterfaces() throws IOException, ClassFormatException { int interfaces_count; interfaces_count = file.readUnsignedShort(); interfaces = new int[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = file.readUnsignedShort(); } } /** * Read information about the methods of the class. * @throws IOException * @throws ClassFormatException */ private final void readMethods() throws IOException, ClassFormatException { int methods_count; methods_count = file.readUnsignedShort(); methods = new Method[methods_count]; for (int i = 0; i < methods_count; i++) { methods[i] = new Method(file, constant_pool); } } /** * Read major and minor version of compiler which created the file. * @throws IOException * @throws ClassFormatException */ private final void readVersion() throws IOException, ClassFormatException { minor = file.readUnsignedShort(); major = file.readUnsignedShort(); } }
true
true
public JavaClass parse() throws IOException, ClassFormatException { ZipFile zip = null; try { if (fileOwned) { if (is_zip) { zip = new ZipFile(zip_file); ZipEntry entry = zip.getEntry(file_name); file = new DataInputStream(new BufferedInputStream(zip.getInputStream(entry), BUFSIZE)); } else { file = new DataInputStream(new BufferedInputStream(new FileInputStream( file_name), BUFSIZE)); } } /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } } finally { // Read everything of interest, so close the file if (fileOwned) { file.close(); if (zip != null) { zip.close(); } } } // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes, is_zip ? JavaClass.ZIP : JavaClass.FILE); }
public JavaClass parse() throws IOException, ClassFormatException { ZipFile zip = null; try { if (fileOwned) { if (is_zip) { zip = new ZipFile(zip_file); ZipEntry entry = zip.getEntry(file_name); file = new DataInputStream(new BufferedInputStream(zip.getInputStream(entry), BUFSIZE)); } else { file = new DataInputStream(new BufferedInputStream(new FileInputStream( file_name), BUFSIZE)); } } /****************** Read headers ********************************/ // Check magic tag of class file readID(); // Get compiler version readVersion(); /****************** Read constant pool and related **************/ // Read constant pool entries readConstantPool(); // Get class information readClassInfo(); // Get interface information, i.e., implemented interfaces readInterfaces(); /****************** Read class fields and methods ***************/ // Read class fields, i.e., the variables of the class readFields(); // Read class methods, i.e., the functions in the class readMethods(); // Read class attributes readAttributes(); // Check for unknown variables //Unknown[] u = Unknown.getUnknownAttributes(); //for(int i=0; i < u.length; i++) // System.err.println("WARNING: " + u[i]); // Everything should have been read now // if(file.available() > 0) { // int bytes = file.available(); // byte[] buf = new byte[bytes]; // file.read(buf); // if(!(is_zip && (buf.length == 1))) { // System.err.println("WARNING: Trailing garbage at end of " + file_name); // System.err.println(bytes + " extra bytes: " + Utility.toHexString(buf)); // } // } } finally { // Read everything of interest, so close the file if (fileOwned) { if (file != null) { file.close(); } if (zip != null) { zip.close(); } } } // Return the information we have gathered in a new object return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, access_flags, constant_pool, interfaces, fields, methods, attributes, is_zip ? JavaClass.ZIP : JavaClass.FILE); }
diff --git a/src/main/java/com/github/kpacha/jkata/potter/Potter.java b/src/main/java/com/github/kpacha/jkata/potter/Potter.java index 1f2490e..4ab12f4 100644 --- a/src/main/java/com/github/kpacha/jkata/potter/Potter.java +++ b/src/main/java/com/github/kpacha/jkata/potter/Potter.java @@ -1,29 +1,30 @@ package com.github.kpacha.jkata.potter; import java.util.HashMap; import java.util.Map; public class Potter { private static Map<Integer, Double> discount = new HashMap<Integer, Double>() { { put(5, 0.75); put(4, 0.8); put(3, 0.9); put(2, 0.95); put(1, 1.0); put(0, 1.0); } }; public static double priceFor(int... items) { - double total = 8 * items[0] * getDiscountFor(items[0]); - if (items.length == 2) - total += 8 * items[1] * getDiscountFor(items[1]); + double total = 0.0; + for (int quantity : items) { + total += 8 * quantity * getDiscountFor(quantity); + } return total; } private static double getDiscountFor(int items) { return discount.get(items); } }
true
true
public static double priceFor(int... items) { double total = 8 * items[0] * getDiscountFor(items[0]); if (items.length == 2) total += 8 * items[1] * getDiscountFor(items[1]); return total; }
public static double priceFor(int... items) { double total = 0.0; for (int quantity : items) { total += 8 * quantity * getDiscountFor(quantity); } return total; }
diff --git a/demoapp/src/main/java/org/esbhive/demoapp/ResponseDataCalculator.java b/demoapp/src/main/java/org/esbhive/demoapp/ResponseDataCalculator.java index b689755..30669d9 100644 --- a/demoapp/src/main/java/org/esbhive/demoapp/ResponseDataCalculator.java +++ b/demoapp/src/main/java/org/esbhive/demoapp/ResponseDataCalculator.java @@ -1,79 +1,78 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.esbhive.demoapp; import java.io.File; /** * * @author pubudu */ public class ResponseDataCalculator { private int numESBs, numClients, totalRequests,requestsPerClient; private long totalTime, responseTimeSum, throughput, responseTime; public ResponseDataCalculator(File file) throws InvalidDataException { if (!file.isDirectory()) { throw new InvalidDataException("The " + file.getAbsolutePath() + " is not a directory."); } else { String fileName = file.getName(); String[] parts = fileName.split("\\."); numESBs = Integer.parseInt(parts[0].split("-")[1]); numClients = Integer.parseInt(parts[1].split("-")[1]); requestsPerClient = Integer.parseInt(parts[2].split("-")[1]); File[] files = file.listFiles(); if (files.length != numClients) { throw new InvalidDataException("The number of clients do not match the number of files"); } for (int i = 0; i < files.length; i++) { ResponseData responseData = new ResponseData(files[i]); responseTimeSum += responseData.getResponseTimeSum(); totalRequests += responseData.getTotalRequests(); - totalTime += responseData.getTotalTime(); + throughput += responseData.getTotalRequests()/(responseData.getTotalTime()/1000000000); if (responseData.getRequestsServed() != responseData.getTotalRequests()) { throw new InvalidDataException("Some requests have not been served."); } } - throughput = totalRequests / (totalTime / 1000000000); responseTime = (responseTimeSum / 1000000) / totalRequests; } } public void print() { System.out.println("Number of clients : " +this.getNumClients()); System.out.println("Number of ESBs : " +this.getNumESBs()); System.out.println("Response time (ms) : " +this.getResponseTime()); System.out.println("Throughput(per second) : " +this.getThroughput()); System.out.println("Total Requests : " +this.getTotalRequests()); } public int getNumClients() { return numClients; } public int getNumESBs() { return numESBs; } public long getResponseTime() { return responseTime; } public int getRequestsPerClient() { return requestsPerClient; } public long getThroughput() { return throughput; } public int getTotalRequests() { return totalRequests; } }
false
true
public ResponseDataCalculator(File file) throws InvalidDataException { if (!file.isDirectory()) { throw new InvalidDataException("The " + file.getAbsolutePath() + " is not a directory."); } else { String fileName = file.getName(); String[] parts = fileName.split("\\."); numESBs = Integer.parseInt(parts[0].split("-")[1]); numClients = Integer.parseInt(parts[1].split("-")[1]); requestsPerClient = Integer.parseInt(parts[2].split("-")[1]); File[] files = file.listFiles(); if (files.length != numClients) { throw new InvalidDataException("The number of clients do not match the number of files"); } for (int i = 0; i < files.length; i++) { ResponseData responseData = new ResponseData(files[i]); responseTimeSum += responseData.getResponseTimeSum(); totalRequests += responseData.getTotalRequests(); totalTime += responseData.getTotalTime(); if (responseData.getRequestsServed() != responseData.getTotalRequests()) { throw new InvalidDataException("Some requests have not been served."); } } throughput = totalRequests / (totalTime / 1000000000); responseTime = (responseTimeSum / 1000000) / totalRequests; } }
public ResponseDataCalculator(File file) throws InvalidDataException { if (!file.isDirectory()) { throw new InvalidDataException("The " + file.getAbsolutePath() + " is not a directory."); } else { String fileName = file.getName(); String[] parts = fileName.split("\\."); numESBs = Integer.parseInt(parts[0].split("-")[1]); numClients = Integer.parseInt(parts[1].split("-")[1]); requestsPerClient = Integer.parseInt(parts[2].split("-")[1]); File[] files = file.listFiles(); if (files.length != numClients) { throw new InvalidDataException("The number of clients do not match the number of files"); } for (int i = 0; i < files.length; i++) { ResponseData responseData = new ResponseData(files[i]); responseTimeSum += responseData.getResponseTimeSum(); totalRequests += responseData.getTotalRequests(); throughput += responseData.getTotalRequests()/(responseData.getTotalTime()/1000000000); if (responseData.getRequestsServed() != responseData.getTotalRequests()) { throw new InvalidDataException("Some requests have not been served."); } } responseTime = (responseTimeSum / 1000000) / totalRequests; } }
diff --git a/src/org/apache/xalan/templates/ElemApplyTemplates.java b/src/org/apache/xalan/templates/ElemApplyTemplates.java index af000951..a3689c86 100644 --- a/src/org/apache/xalan/templates/ElemApplyTemplates.java +++ b/src/org/apache/xalan/templates/ElemApplyTemplates.java @@ -1,461 +1,484 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xalan.templates; //import org.w3c.dom.*; import org.xml.sax.*; import org.apache.xpath.*; import org.apache.xpath.objects.XObject; import java.util.Vector; import org.apache.xalan.trace.TracerEvent; import org.apache.xml.utils.QName; import org.apache.xalan.res.XSLTErrorResources; import org.apache.xpath.VariableStack; import org.apache.xalan.transformer.TransformerImpl; import org.apache.xalan.transformer.ResultTreeHandler; import org.apache.xalan.transformer.ClonerToResultTree; import org.apache.xml.dtm.DTMAxisTraverser; import org.apache.xml.dtm.DTMIterator; import org.apache.xml.dtm.DTM; import org.apache.xml.dtm.Axis; import javax.xml.transform.TransformerException; import javax.xml.transform.SourceLocator; import org.apache.xml.dtm.DTMManager; // Experemental import org.apache.xml.dtm.ref.ExpandedNameTable; /** * <meta name="usage" content="advanced"/> * Implement xsl:apply-templates. * <pre> * &amp;!ELEMENT xsl:apply-templates (xsl:sort|xsl:with-param)*> * &amp;!ATTLIST xsl:apply-templates * select %expr; "node()" * mode %qname; #IMPLIED * &amp; * </pre> * @see <a href="http://www.w3.org/TR/xslt#section-Applying-Template-Rules">section-Applying-Template-Rules in XSLT Specification</a> */ public class ElemApplyTemplates extends ElemCallTemplate { /** * mode %qname; #IMPLIED * @serial */ private QName m_mode = null; /** * Set the mode attribute for this element. * * @param mode reference, which may be null, to the <a href="http://www.w3.org/TR/xslt#modes">current mode</a>. */ public void setMode(QName mode) { m_mode = mode; } /** * Get the mode attribute for this element. * * @return The mode attribute for this element */ public QName getMode() { return m_mode; } /** * Tells if this belongs to a default template, * in which case it will act different with * regard to processing modes. * @see <a href="http://www.w3.org/TR/xslt#built-in-rule">built-in-rule in XSLT Specification</a> * @serial */ private boolean m_isDefaultTemplate = false; // /** // * List of namespace/localname IDs, for identification of xsl:with-param to // * xsl:params. Initialized in the compose() method. // */ // private int[] m_paramIDs; /** * Set if this belongs to a default template, * in which case it will act different with * regard to processing modes. * @see <a href="http://www.w3.org/TR/xslt#built-in-rule">built-in-rule in XSLT Specification</a> * * @param b boolean value to set. */ public void setIsDefaultTemplate(boolean b) { m_isDefaultTemplate = b; } /** * Get an int constant identifying the type of element. * @see org.apache.xalan.templates.Constants * * @return Token ID for this element types */ public int getXSLToken() { return Constants.ELEMNAME_APPLY_TEMPLATES; } /** * This function is called after everything else has been * recomposed, and allows the template to set remaining * values that may be based on some other property that * depends on recomposition. */ public void compose(StylesheetRoot sroot) throws TransformerException { super.compose(sroot); } /** * Return the node name. * * @return Element name */ public String getNodeName() { return Constants.ELEMNAME_APPLY_TEMPLATES_STRING; } /** * Apply the context node to the matching templates. * @see <a href="http://www.w3.org/TR/xslt#section-Applying-Template-Rules">section-Applying-Template-Rules in XSLT Specification</a> * * @param transformer non-null reference to the the current transform-time state. * @param sourceNode non-null reference to the <a href="http://www.w3.org/TR/xslt#dt-current-node">current source node</a>. * @param mode reference, which may be null, to the <a href="http://www.w3.org/TR/xslt#modes">current mode</a>. * * @throws TransformerException */ public void execute(TransformerImpl transformer) throws TransformerException { transformer.pushCurrentTemplateRuleIsNull(false); boolean pushMode = false; try { // %REVIEW% Do we need this check?? // if (null != sourceNode) // { // boolean needToTurnOffInfiniteLoopCheck = false; QName mode = transformer.getMode(); if (!m_isDefaultTemplate) { if (((null == mode) && (null != m_mode)) || ((null != mode) &&!mode.equals(m_mode))) { pushMode = true; transformer.pushMode(m_mode); } } if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireTraceEvent(this); transformSelectedNodes(transformer); } finally { if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireTraceEndEvent(this); if (pushMode) transformer.popMode(); transformer.popCurrentTemplateRuleIsNull(); } } /** * <meta name="usage" content="advanced"/> * Perform a query if needed, and call transformNode for each child. * * @param transformer non-null reference to the the current transform-time state. * @param template The owning template context. * * @throws TransformerException Thrown in a variety of circumstances. */ public void transformSelectedNodes(TransformerImpl transformer) throws TransformerException { final XPathContext xctxt = transformer.getXPathContext(); final int sourceNode = xctxt.getCurrentNode(); DTMIterator sourceNodes = m_selectExpression.asIterator(xctxt, sourceNode); VariableStack vars = xctxt.getVarStack(); int nParams = getParamElemCount(); int thisframe = vars.getStackFrame(); try { final Vector keys = (m_sortElems == null) ? null : transformer.processSortKeys(this, sourceNode); // Sort if we need to. if (null != keys) sourceNodes = sortNodes(xctxt, keys, sourceNodes); if (TransformerImpl.S_DEBUG) { transformer.getTraceManager().fireSelectedEvent(sourceNode, this, "select", new XPath(m_selectExpression), new org.apache.xpath.objects.XNodeSet(sourceNodes)); } final ResultTreeHandler rth = transformer.getResultTreeHandler(); ContentHandler chandler = rth.getContentHandler(); final StylesheetRoot sroot = transformer.getStylesheet(); final TemplateList tl = sroot.getTemplateListComposed(); final boolean quiet = transformer.getQuietConflictWarnings(); // Should be able to get this from the iterator but there must be a bug. DTM dtm = xctxt.getDTM(sourceNode); int argsFrame = -1; if(nParams > 0) { // This code will create a section on the stack that is all the // evaluated arguments. These will be copied into the real params // section of each called template. argsFrame = vars.link(nParams); vars.setStackFrame(thisframe); for (int i = 0; i < nParams; i++) { ElemWithParam ewp = m_paramElems[i]; XObject obj = ewp.getValue(transformer, sourceNode); vars.setLocalVariable(i, obj, argsFrame); } vars.setStackFrame(argsFrame); } xctxt.pushCurrentNode(DTM.NULL); int[] currentNodes = xctxt.getCurrentNodeStack(); int currentNodePos = xctxt.getCurrentNodeFirstFree() - 1; xctxt.pushCurrentExpressionNode(DTM.NULL); int[] currentExpressionNodes = xctxt.getCurrentExpressionNodeStack(); int currentExpressionNodePos = xctxt.getCurrentExpressionNodesFirstFree() - 1; xctxt.pushSAXLocatorNull(); xctxt.pushContextNodeList(sourceNodes); transformer.pushElemTemplateElement(null); // pushParams(transformer, xctxt); int child; while (DTM.NULL != (child = sourceNodes.nextNode())) { currentNodes[currentNodePos] = child; currentExpressionNodes[currentExpressionNodePos] = child; if(xctxt.getDTM(child) != dtm) { dtm = xctxt.getDTM(child); } final int exNodeType = dtm.getExpandedTypeID(child); final int nodeType = (exNodeType >> ExpandedNameTable.ROTAMOUNT_TYPE); final QName mode = transformer.getMode(); ElemTemplate template = tl.getTemplateFast(xctxt, child, exNodeType, mode, -1, quiet, dtm); // If that didn't locate a node, fall back to a default template rule. // See http://www.w3.org/TR/xslt#built-in-rule. if (null == template) { switch (nodeType) { case DTM.DOCUMENT_FRAGMENT_NODE : case DTM.ELEMENT_NODE : template = sroot.getDefaultRule(); // %OPT% direct faster? break; case DTM.ATTRIBUTE_NODE : case DTM.CDATA_SECTION_NODE : case DTM.TEXT_NODE : // if(rth.m_elemIsPending || rth.m_docPending) // rth.flushPending(true); transformer.pushPairCurrentMatched(sroot.getDefaultTextRule(), child); transformer.setCurrentElement(sroot.getDefaultTextRule()); // dtm.dispatchCharactersEvents(child, chandler, false); dtm.dispatchCharactersEvents(child, rth, false); transformer.popCurrentMatched(); continue; case DTM.DOCUMENT_NODE : template = sroot.getDefaultRootRule(); break; default : // No default rules for processing instructions and the like. continue; } } transformer.pushPairCurrentMatched(template, child); + int currentFrameBottom; // See comment with unlink, below if(template.m_frameSize > 0) { + xctxt.pushRTFContext(); + currentFrameBottom = vars.getStackFrame(); // See comment with unlink, below vars.link(template.m_frameSize); // You can't do the check for nParams here, otherwise the // xsl:params might not be nulled. if(/* nParams > 0 && */ template.m_inArgsSize > 0) { int paramIndex = 0; for (ElemTemplateElement elem = template.getFirstChildElem(); null != elem; elem = elem.getNextSiblingElem()) { if(Constants.ELEMNAME_PARAMVARIABLE == elem.getXSLToken()) { ElemParam ep = (ElemParam)elem; int i; for (i = 0; i < nParams; i++) { ElemWithParam ewp = m_paramElems[i]; if(ewp.m_qnameID == ep.m_qnameID) { XObject obj = vars.getLocalVariable(i, argsFrame); vars.setLocalVariable(paramIndex, obj); break; } } if(i == nParams) vars.setLocalVariable(paramIndex, null); } else break; paramIndex++; } } } + else + currentFrameBottom = 0; // if (check) // guard.push(this, child); // Fire a trace event for the template. if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireTraceEvent(template); // And execute the child templates. // Loop through the children of the template, calling execute on // each of them. for (ElemTemplateElement t = template.m_firstChild; t != null; t = t.m_nextSibling) { xctxt.setSAXLocator(t); transformer.setCurrentElement(t); t.execute(transformer); } if (TransformerImpl.S_DEBUG) - transformer.getTraceManager().fireTraceEndEvent(this); + transformer.getTraceManager().fireTraceEndEvent(template); if(template.m_frameSize > 0) - vars.unlink(); + { + // See Frank Weiss bug around 03/19/2002 (no Bugzilla report yet). + // While unlink will restore to the proper place, the real position + // may have been changed for xsl:with-param, so that variables + // can be accessed. + // of right now. + // More: + // When we entered this function, the current + // frame buffer (cfb) index in the variable stack may + // have been manually set. If we just call + // unlink(), however, it will restore the cfb to the + // previous link index from the link stack, rather than + // the manually set cfb. So, + // the only safe solution is to restore it back + // to the same position it was on entry, since we're + // really not working in a stack context here. (Bug4218) + vars.unlink(currentFrameBottom); + xctxt.popRTFContext(); + } transformer.popCurrentMatched(); } // end while (DTM.NULL != (child = sourceNodes.nextNode())) } catch (SAXException se) { transformer.getErrorListener().fatalError(new TransformerException(se)); } finally { if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireSelectedEndEvent(sourceNode, this, "select", new XPath(m_selectExpression), new org.apache.xpath.objects.XNodeSet(sourceNodes)); // Unlink to the original stack frame if(nParams > 0) vars.unlink(thisframe); xctxt.popSAXLocator(); xctxt.popContextNodeList(); transformer.popElemTemplateElement(); xctxt.popCurrentExpressionNode(); xctxt.popCurrentNode(); sourceNodes.detach(); } } }
false
true
public void transformSelectedNodes(TransformerImpl transformer) throws TransformerException { final XPathContext xctxt = transformer.getXPathContext(); final int sourceNode = xctxt.getCurrentNode(); DTMIterator sourceNodes = m_selectExpression.asIterator(xctxt, sourceNode); VariableStack vars = xctxt.getVarStack(); int nParams = getParamElemCount(); int thisframe = vars.getStackFrame(); try { final Vector keys = (m_sortElems == null) ? null : transformer.processSortKeys(this, sourceNode); // Sort if we need to. if (null != keys) sourceNodes = sortNodes(xctxt, keys, sourceNodes); if (TransformerImpl.S_DEBUG) { transformer.getTraceManager().fireSelectedEvent(sourceNode, this, "select", new XPath(m_selectExpression), new org.apache.xpath.objects.XNodeSet(sourceNodes)); } final ResultTreeHandler rth = transformer.getResultTreeHandler(); ContentHandler chandler = rth.getContentHandler(); final StylesheetRoot sroot = transformer.getStylesheet(); final TemplateList tl = sroot.getTemplateListComposed(); final boolean quiet = transformer.getQuietConflictWarnings(); // Should be able to get this from the iterator but there must be a bug. DTM dtm = xctxt.getDTM(sourceNode); int argsFrame = -1; if(nParams > 0) { // This code will create a section on the stack that is all the // evaluated arguments. These will be copied into the real params // section of each called template. argsFrame = vars.link(nParams); vars.setStackFrame(thisframe); for (int i = 0; i < nParams; i++) { ElemWithParam ewp = m_paramElems[i]; XObject obj = ewp.getValue(transformer, sourceNode); vars.setLocalVariable(i, obj, argsFrame); } vars.setStackFrame(argsFrame); } xctxt.pushCurrentNode(DTM.NULL); int[] currentNodes = xctxt.getCurrentNodeStack(); int currentNodePos = xctxt.getCurrentNodeFirstFree() - 1; xctxt.pushCurrentExpressionNode(DTM.NULL); int[] currentExpressionNodes = xctxt.getCurrentExpressionNodeStack(); int currentExpressionNodePos = xctxt.getCurrentExpressionNodesFirstFree() - 1; xctxt.pushSAXLocatorNull(); xctxt.pushContextNodeList(sourceNodes); transformer.pushElemTemplateElement(null); // pushParams(transformer, xctxt); int child; while (DTM.NULL != (child = sourceNodes.nextNode())) { currentNodes[currentNodePos] = child; currentExpressionNodes[currentExpressionNodePos] = child; if(xctxt.getDTM(child) != dtm) { dtm = xctxt.getDTM(child); } final int exNodeType = dtm.getExpandedTypeID(child); final int nodeType = (exNodeType >> ExpandedNameTable.ROTAMOUNT_TYPE); final QName mode = transformer.getMode(); ElemTemplate template = tl.getTemplateFast(xctxt, child, exNodeType, mode, -1, quiet, dtm); // If that didn't locate a node, fall back to a default template rule. // See http://www.w3.org/TR/xslt#built-in-rule. if (null == template) { switch (nodeType) { case DTM.DOCUMENT_FRAGMENT_NODE : case DTM.ELEMENT_NODE : template = sroot.getDefaultRule(); // %OPT% direct faster? break; case DTM.ATTRIBUTE_NODE : case DTM.CDATA_SECTION_NODE : case DTM.TEXT_NODE : // if(rth.m_elemIsPending || rth.m_docPending) // rth.flushPending(true); transformer.pushPairCurrentMatched(sroot.getDefaultTextRule(), child); transformer.setCurrentElement(sroot.getDefaultTextRule()); // dtm.dispatchCharactersEvents(child, chandler, false); dtm.dispatchCharactersEvents(child, rth, false); transformer.popCurrentMatched(); continue; case DTM.DOCUMENT_NODE : template = sroot.getDefaultRootRule(); break; default : // No default rules for processing instructions and the like. continue; } } transformer.pushPairCurrentMatched(template, child); if(template.m_frameSize > 0) { vars.link(template.m_frameSize); // You can't do the check for nParams here, otherwise the // xsl:params might not be nulled. if(/* nParams > 0 && */ template.m_inArgsSize > 0) { int paramIndex = 0; for (ElemTemplateElement elem = template.getFirstChildElem(); null != elem; elem = elem.getNextSiblingElem()) { if(Constants.ELEMNAME_PARAMVARIABLE == elem.getXSLToken()) { ElemParam ep = (ElemParam)elem; int i; for (i = 0; i < nParams; i++) { ElemWithParam ewp = m_paramElems[i]; if(ewp.m_qnameID == ep.m_qnameID) { XObject obj = vars.getLocalVariable(i, argsFrame); vars.setLocalVariable(paramIndex, obj); break; } } if(i == nParams) vars.setLocalVariable(paramIndex, null); } else break; paramIndex++; } } } // if (check) // guard.push(this, child); // Fire a trace event for the template. if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireTraceEvent(template); // And execute the child templates. // Loop through the children of the template, calling execute on // each of them. for (ElemTemplateElement t = template.m_firstChild; t != null; t = t.m_nextSibling) { xctxt.setSAXLocator(t); transformer.setCurrentElement(t); t.execute(transformer); } if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireTraceEndEvent(this); if(template.m_frameSize > 0) vars.unlink(); transformer.popCurrentMatched(); } // end while (DTM.NULL != (child = sourceNodes.nextNode())) } catch (SAXException se) { transformer.getErrorListener().fatalError(new TransformerException(se)); } finally { if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireSelectedEndEvent(sourceNode, this, "select", new XPath(m_selectExpression), new org.apache.xpath.objects.XNodeSet(sourceNodes)); // Unlink to the original stack frame if(nParams > 0) vars.unlink(thisframe); xctxt.popSAXLocator(); xctxt.popContextNodeList(); transformer.popElemTemplateElement(); xctxt.popCurrentExpressionNode(); xctxt.popCurrentNode(); sourceNodes.detach(); } }
public void transformSelectedNodes(TransformerImpl transformer) throws TransformerException { final XPathContext xctxt = transformer.getXPathContext(); final int sourceNode = xctxt.getCurrentNode(); DTMIterator sourceNodes = m_selectExpression.asIterator(xctxt, sourceNode); VariableStack vars = xctxt.getVarStack(); int nParams = getParamElemCount(); int thisframe = vars.getStackFrame(); try { final Vector keys = (m_sortElems == null) ? null : transformer.processSortKeys(this, sourceNode); // Sort if we need to. if (null != keys) sourceNodes = sortNodes(xctxt, keys, sourceNodes); if (TransformerImpl.S_DEBUG) { transformer.getTraceManager().fireSelectedEvent(sourceNode, this, "select", new XPath(m_selectExpression), new org.apache.xpath.objects.XNodeSet(sourceNodes)); } final ResultTreeHandler rth = transformer.getResultTreeHandler(); ContentHandler chandler = rth.getContentHandler(); final StylesheetRoot sroot = transformer.getStylesheet(); final TemplateList tl = sroot.getTemplateListComposed(); final boolean quiet = transformer.getQuietConflictWarnings(); // Should be able to get this from the iterator but there must be a bug. DTM dtm = xctxt.getDTM(sourceNode); int argsFrame = -1; if(nParams > 0) { // This code will create a section on the stack that is all the // evaluated arguments. These will be copied into the real params // section of each called template. argsFrame = vars.link(nParams); vars.setStackFrame(thisframe); for (int i = 0; i < nParams; i++) { ElemWithParam ewp = m_paramElems[i]; XObject obj = ewp.getValue(transformer, sourceNode); vars.setLocalVariable(i, obj, argsFrame); } vars.setStackFrame(argsFrame); } xctxt.pushCurrentNode(DTM.NULL); int[] currentNodes = xctxt.getCurrentNodeStack(); int currentNodePos = xctxt.getCurrentNodeFirstFree() - 1; xctxt.pushCurrentExpressionNode(DTM.NULL); int[] currentExpressionNodes = xctxt.getCurrentExpressionNodeStack(); int currentExpressionNodePos = xctxt.getCurrentExpressionNodesFirstFree() - 1; xctxt.pushSAXLocatorNull(); xctxt.pushContextNodeList(sourceNodes); transformer.pushElemTemplateElement(null); // pushParams(transformer, xctxt); int child; while (DTM.NULL != (child = sourceNodes.nextNode())) { currentNodes[currentNodePos] = child; currentExpressionNodes[currentExpressionNodePos] = child; if(xctxt.getDTM(child) != dtm) { dtm = xctxt.getDTM(child); } final int exNodeType = dtm.getExpandedTypeID(child); final int nodeType = (exNodeType >> ExpandedNameTable.ROTAMOUNT_TYPE); final QName mode = transformer.getMode(); ElemTemplate template = tl.getTemplateFast(xctxt, child, exNodeType, mode, -1, quiet, dtm); // If that didn't locate a node, fall back to a default template rule. // See http://www.w3.org/TR/xslt#built-in-rule. if (null == template) { switch (nodeType) { case DTM.DOCUMENT_FRAGMENT_NODE : case DTM.ELEMENT_NODE : template = sroot.getDefaultRule(); // %OPT% direct faster? break; case DTM.ATTRIBUTE_NODE : case DTM.CDATA_SECTION_NODE : case DTM.TEXT_NODE : // if(rth.m_elemIsPending || rth.m_docPending) // rth.flushPending(true); transformer.pushPairCurrentMatched(sroot.getDefaultTextRule(), child); transformer.setCurrentElement(sroot.getDefaultTextRule()); // dtm.dispatchCharactersEvents(child, chandler, false); dtm.dispatchCharactersEvents(child, rth, false); transformer.popCurrentMatched(); continue; case DTM.DOCUMENT_NODE : template = sroot.getDefaultRootRule(); break; default : // No default rules for processing instructions and the like. continue; } } transformer.pushPairCurrentMatched(template, child); int currentFrameBottom; // See comment with unlink, below if(template.m_frameSize > 0) { xctxt.pushRTFContext(); currentFrameBottom = vars.getStackFrame(); // See comment with unlink, below vars.link(template.m_frameSize); // You can't do the check for nParams here, otherwise the // xsl:params might not be nulled. if(/* nParams > 0 && */ template.m_inArgsSize > 0) { int paramIndex = 0; for (ElemTemplateElement elem = template.getFirstChildElem(); null != elem; elem = elem.getNextSiblingElem()) { if(Constants.ELEMNAME_PARAMVARIABLE == elem.getXSLToken()) { ElemParam ep = (ElemParam)elem; int i; for (i = 0; i < nParams; i++) { ElemWithParam ewp = m_paramElems[i]; if(ewp.m_qnameID == ep.m_qnameID) { XObject obj = vars.getLocalVariable(i, argsFrame); vars.setLocalVariable(paramIndex, obj); break; } } if(i == nParams) vars.setLocalVariable(paramIndex, null); } else break; paramIndex++; } } } else currentFrameBottom = 0; // if (check) // guard.push(this, child); // Fire a trace event for the template. if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireTraceEvent(template); // And execute the child templates. // Loop through the children of the template, calling execute on // each of them. for (ElemTemplateElement t = template.m_firstChild; t != null; t = t.m_nextSibling) { xctxt.setSAXLocator(t); transformer.setCurrentElement(t); t.execute(transformer); } if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireTraceEndEvent(template); if(template.m_frameSize > 0) { // See Frank Weiss bug around 03/19/2002 (no Bugzilla report yet). // While unlink will restore to the proper place, the real position // may have been changed for xsl:with-param, so that variables // can be accessed. // of right now. // More: // When we entered this function, the current // frame buffer (cfb) index in the variable stack may // have been manually set. If we just call // unlink(), however, it will restore the cfb to the // previous link index from the link stack, rather than // the manually set cfb. So, // the only safe solution is to restore it back // to the same position it was on entry, since we're // really not working in a stack context here. (Bug4218) vars.unlink(currentFrameBottom); xctxt.popRTFContext(); } transformer.popCurrentMatched(); } // end while (DTM.NULL != (child = sourceNodes.nextNode())) } catch (SAXException se) { transformer.getErrorListener().fatalError(new TransformerException(se)); } finally { if (TransformerImpl.S_DEBUG) transformer.getTraceManager().fireSelectedEndEvent(sourceNode, this, "select", new XPath(m_selectExpression), new org.apache.xpath.objects.XNodeSet(sourceNodes)); // Unlink to the original stack frame if(nParams > 0) vars.unlink(thisframe); xctxt.popSAXLocator(); xctxt.popContextNodeList(); transformer.popElemTemplateElement(); xctxt.popCurrentExpressionNode(); xctxt.popCurrentNode(); sourceNodes.detach(); } }