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/src/main/java/com/pjbollinger/guilds/Guilds.java b/src/main/java/com/pjbollinger/guilds/Guilds.java index a7f7d48..b453412 100644 --- a/src/main/java/com/pjbollinger/guilds/Guilds.java +++ b/src/main/java/com/pjbollinger/guilds/Guilds.java @@ -1,90 +1,90 @@ package com.pjbollinger.guilds; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; public class Guilds extends JavaPlugin { @Override public void onEnable(){ getLogger().info("Guilds has started."); } @Override public void onDisable(){ getLogger().info("Guilds has stopped."); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("Judy")){ getLogger().info("Judy says, 'Hi!'"); return true; } else if(cmd.getName().equalsIgnoreCase("g")){ if(args[0].equalsIgnoreCase("create <name of Guild>")){ //Stuff for creating a faction will go here } else if(args[0].equalsIgnoreCase("invite")){ //Stuff for inviting a player will go here //Need to specify <name> } else if(args[0].equalsIgnoreCase("invitations")){ //Stuff for viewing which Guild(s) have invited a player to join will go here } else if(args[0].equalsIgnoreCase("join")){ //Stuff for if invited OR if desire to join an OPEN Guild //Need to specify <name of Guild> } else if(args[0].equalsIgnoreCase("leave")){ //Stuff for leaving the Guild } else if(args[0].equalsIgnoreCase("kick")){ //Stuff for getting rid of a troublemaker //Need to specify <name> } else if(args[0].equalsIgnoreCase("moderator")){ //Stuff for designating a Guild member as moderator of the Guild //Need to specify <name> } else if(args[0].equalsIgnoreCase("member")){ //Stuff for removing Guild mod status, returning to member only status //Need to specify <name> } else if(args[0].equalsIgnoreCase("leader")){ //Stuff for reassigning role of Guild leader // MUST be approved by SO or SAdmin before going into effect //Need to specify <name> } else if(args[0].equalsIgnoreCase("list")){ //Stuff for creating/showing list of Guilds //page # is optional } else if(args[0].equalsIgnoreCase("show")){ //Stuff for showing info about a Guild } else if(args[0].equalsIgnoreCase("player")){ //Stuff for showing info about a single person } else if(args[0].equalsIgnoreCase("home")){ //Stuff for going to home set point } else if(args[0].equalsIgnoreCase("set")){ //Stuff for setting the value, property, etc. //examples: property = home, value = open (is Guild open or closed) //examples: name = change name of Guild, description = motto for Guild //Need to specify <name, property> and [value(s), description] } else if(args[0].equalsIgnoreCase("ally")){ //Stuff for inviting another Guild to be allied with yours //Need to specify <name> } - else if(args[0].eqaulsIgnoreCase("neutral")){ + else if(args[0].equalsIgnoreCase("neutral")){ //Stuff for returning to neutral with a Guild //Need to specify <name> } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("Judy")){ getLogger().info("Judy says, 'Hi!'"); return true; } else if(cmd.getName().equalsIgnoreCase("g")){ if(args[0].equalsIgnoreCase("create <name of Guild>")){ //Stuff for creating a faction will go here } else if(args[0].equalsIgnoreCase("invite")){ //Stuff for inviting a player will go here //Need to specify <name> } else if(args[0].equalsIgnoreCase("invitations")){ //Stuff for viewing which Guild(s) have invited a player to join will go here } else if(args[0].equalsIgnoreCase("join")){ //Stuff for if invited OR if desire to join an OPEN Guild //Need to specify <name of Guild> } else if(args[0].equalsIgnoreCase("leave")){ //Stuff for leaving the Guild } else if(args[0].equalsIgnoreCase("kick")){ //Stuff for getting rid of a troublemaker //Need to specify <name> } else if(args[0].equalsIgnoreCase("moderator")){ //Stuff for designating a Guild member as moderator of the Guild //Need to specify <name> } else if(args[0].equalsIgnoreCase("member")){ //Stuff for removing Guild mod status, returning to member only status //Need to specify <name> } else if(args[0].equalsIgnoreCase("leader")){ //Stuff for reassigning role of Guild leader // MUST be approved by SO or SAdmin before going into effect //Need to specify <name> } else if(args[0].equalsIgnoreCase("list")){ //Stuff for creating/showing list of Guilds //page # is optional } else if(args[0].equalsIgnoreCase("show")){ //Stuff for showing info about a Guild } else if(args[0].equalsIgnoreCase("player")){ //Stuff for showing info about a single person } else if(args[0].equalsIgnoreCase("home")){ //Stuff for going to home set point } else if(args[0].equalsIgnoreCase("set")){ //Stuff for setting the value, property, etc. //examples: property = home, value = open (is Guild open or closed) //examples: name = change name of Guild, description = motto for Guild //Need to specify <name, property> and [value(s), description] } else if(args[0].equalsIgnoreCase("ally")){ //Stuff for inviting another Guild to be allied with yours //Need to specify <name> } else if(args[0].eqaulsIgnoreCase("neutral")){ //Stuff for returning to neutral with a Guild //Need to specify <name> } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("Judy")){ getLogger().info("Judy says, 'Hi!'"); return true; } else if(cmd.getName().equalsIgnoreCase("g")){ if(args[0].equalsIgnoreCase("create <name of Guild>")){ //Stuff for creating a faction will go here } else if(args[0].equalsIgnoreCase("invite")){ //Stuff for inviting a player will go here //Need to specify <name> } else if(args[0].equalsIgnoreCase("invitations")){ //Stuff for viewing which Guild(s) have invited a player to join will go here } else if(args[0].equalsIgnoreCase("join")){ //Stuff for if invited OR if desire to join an OPEN Guild //Need to specify <name of Guild> } else if(args[0].equalsIgnoreCase("leave")){ //Stuff for leaving the Guild } else if(args[0].equalsIgnoreCase("kick")){ //Stuff for getting rid of a troublemaker //Need to specify <name> } else if(args[0].equalsIgnoreCase("moderator")){ //Stuff for designating a Guild member as moderator of the Guild //Need to specify <name> } else if(args[0].equalsIgnoreCase("member")){ //Stuff for removing Guild mod status, returning to member only status //Need to specify <name> } else if(args[0].equalsIgnoreCase("leader")){ //Stuff for reassigning role of Guild leader // MUST be approved by SO or SAdmin before going into effect //Need to specify <name> } else if(args[0].equalsIgnoreCase("list")){ //Stuff for creating/showing list of Guilds //page # is optional } else if(args[0].equalsIgnoreCase("show")){ //Stuff for showing info about a Guild } else if(args[0].equalsIgnoreCase("player")){ //Stuff for showing info about a single person } else if(args[0].equalsIgnoreCase("home")){ //Stuff for going to home set point } else if(args[0].equalsIgnoreCase("set")){ //Stuff for setting the value, property, etc. //examples: property = home, value = open (is Guild open or closed) //examples: name = change name of Guild, description = motto for Guild //Need to specify <name, property> and [value(s), description] } else if(args[0].equalsIgnoreCase("ally")){ //Stuff for inviting another Guild to be allied with yours //Need to specify <name> } else if(args[0].equalsIgnoreCase("neutral")){ //Stuff for returning to neutral with a Guild //Need to specify <name> } } return false; }
diff --git a/src/main/java/me/eccentric_nz/TARDIS/artron/TARDISArtronStorageCommand.java b/src/main/java/me/eccentric_nz/TARDIS/artron/TARDISArtronStorageCommand.java index 0bb9095b7..83592f3a1 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/artron/TARDISArtronStorageCommand.java +++ b/src/main/java/me/eccentric_nz/TARDIS/artron/TARDISArtronStorageCommand.java @@ -1,164 +1,164 @@ /* * Copyright (C) 2013 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.artron; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.database.QueryFactory; import me.eccentric_nz.TARDIS.database.ResultSetPlayerPrefs; import me.eccentric_nz.TARDIS.database.ResultSetTardis; import me.eccentric_nz.TARDIS.enumeration.MESSAGE; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; /** * * @author eccentric_nz */ public class TARDISArtronStorageCommand implements CommandExecutor { private final TARDIS plugin; private final List<String> firstArgs = new ArrayList<String>(); public TARDISArtronStorageCommand(TARDIS plugin) { this.plugin = plugin; this.firstArgs.add("tardis"); this.firstArgs.add("timelord"); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardisartron then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardisartron")) { if (!sender.hasPermission("tardis.store")) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_PERMS.getText()); return true; } if (args.length < 2) { return false; } Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { sender.sendMessage(plugin.getPluginName() + ChatColor.RED + MESSAGE.MUST_BE_PLAYER.getText()); return true; } ItemStack is = player.getItemInHand(); if (is == null || !is.hasItemMeta()) { sender.sendMessage(plugin.getPluginName() + "You must be holding an Artron Storage Cell in your hand!"); return true; } if (is.getAmount() > 1) { sender.sendMessage(plugin.getPluginName() + "You can only charge 1 Artron Storage Cell at a time!"); return true; } ItemMeta im = is.getItemMeta(); String name = im.getDisplayName(); - if (!name.equals("Artron Storage Cell")) { + if (name == null || !name.equals("Artron Storage Cell")) { sender.sendMessage(plugin.getPluginName() + "You must be holding an Artron Storage Cell in your hand!"); return true; } String which = args[0].toLowerCase(Locale.ENGLISH); if (!firstArgs.contains(which)) { sender.sendMessage(plugin.getPluginName() + "You must specify 'tardis' or 'timelord' energy to transfer!"); return false; } // must be a timelord String playerNameStr = player.getName(); int current_level; HashMap<String, Object> wheret = new HashMap<String, Object>(); if (which.equals("tardis")) { wheret.put("owner", playerNameStr); ResultSetTardis rs = new ResultSetTardis(plugin, wheret, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_TARDIS.getText()); return true; } current_level = rs.getArtron_level(); } else { wheret.put("player", playerNameStr); ResultSetPlayerPrefs rs = new ResultSetPlayerPrefs(plugin, wheret); if (!rs.resultSet()) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_TARDIS.getText()); return true; } current_level = rs.getArtronLevel(); } int amount; try { amount = Integer.parseInt(args[1]); if (amount < 0) { sender.sendMessage(plugin.getPluginName() + "The amount cannot be negative!"); return true; } } catch (NumberFormatException n) { sender.sendMessage(plugin.getPluginName() + "The second command argument must be a number!"); return false; } // must have sufficient energy if (which.equals("tardis")) { if (current_level - amount < plugin.getArtronConfig().getInt("comehere")) { sender.sendMessage(plugin.getPluginName() + "You cannot transfer that much energy, you must have enough left to call your TARDIS!"); return true; } } else { if (current_level - amount < 0) { sender.sendMessage(plugin.getPluginName() + "You do not have that much Time Lord energy to transfer!"); return true; } } List<String> lore = im.getLore(); int level = plugin.getUtils().parseInt(lore.get(1)); int new_amount = amount + level; int max = plugin.getArtronConfig().getInt("full_charge"); if (new_amount > max) { sender.sendMessage(plugin.getPluginName() + "You cannot overcharge this cell, transfer " + (max - level) + ", or use an empty cell!"); return false; } lore.set(1, "" + new_amount); im.setLore(lore); im.addEnchant(Enchantment.DURABILITY, 1, true); is.setItemMeta(im); // remove the energy from the tardis/timelord HashMap<String, Object> where = new HashMap<String, Object>(); String table; if (which.equals("tardis")) { where.put("owner", playerNameStr); table = "tardis"; } else { where.put("player", playerNameStr); table = "player_prefs"; } new QueryFactory(plugin).alterEnergyLevel(table, -amount, where, player); sender.sendMessage(plugin.getPluginName() + "Artron Storage Cell charged to " + new_amount); return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardisartron then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardisartron")) { if (!sender.hasPermission("tardis.store")) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_PERMS.getText()); return true; } if (args.length < 2) { return false; } Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { sender.sendMessage(plugin.getPluginName() + ChatColor.RED + MESSAGE.MUST_BE_PLAYER.getText()); return true; } ItemStack is = player.getItemInHand(); if (is == null || !is.hasItemMeta()) { sender.sendMessage(plugin.getPluginName() + "You must be holding an Artron Storage Cell in your hand!"); return true; } if (is.getAmount() > 1) { sender.sendMessage(plugin.getPluginName() + "You can only charge 1 Artron Storage Cell at a time!"); return true; } ItemMeta im = is.getItemMeta(); String name = im.getDisplayName(); if (!name.equals("Artron Storage Cell")) { sender.sendMessage(plugin.getPluginName() + "You must be holding an Artron Storage Cell in your hand!"); return true; } String which = args[0].toLowerCase(Locale.ENGLISH); if (!firstArgs.contains(which)) { sender.sendMessage(plugin.getPluginName() + "You must specify 'tardis' or 'timelord' energy to transfer!"); return false; } // must be a timelord String playerNameStr = player.getName(); int current_level; HashMap<String, Object> wheret = new HashMap<String, Object>(); if (which.equals("tardis")) { wheret.put("owner", playerNameStr); ResultSetTardis rs = new ResultSetTardis(plugin, wheret, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_TARDIS.getText()); return true; } current_level = rs.getArtron_level(); } else { wheret.put("player", playerNameStr); ResultSetPlayerPrefs rs = new ResultSetPlayerPrefs(plugin, wheret); if (!rs.resultSet()) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_TARDIS.getText()); return true; } current_level = rs.getArtronLevel(); } int amount; try { amount = Integer.parseInt(args[1]); if (amount < 0) { sender.sendMessage(plugin.getPluginName() + "The amount cannot be negative!"); return true; } } catch (NumberFormatException n) { sender.sendMessage(plugin.getPluginName() + "The second command argument must be a number!"); return false; } // must have sufficient energy if (which.equals("tardis")) { if (current_level - amount < plugin.getArtronConfig().getInt("comehere")) { sender.sendMessage(plugin.getPluginName() + "You cannot transfer that much energy, you must have enough left to call your TARDIS!"); return true; } } else { if (current_level - amount < 0) { sender.sendMessage(plugin.getPluginName() + "You do not have that much Time Lord energy to transfer!"); return true; } } List<String> lore = im.getLore(); int level = plugin.getUtils().parseInt(lore.get(1)); int new_amount = amount + level; int max = plugin.getArtronConfig().getInt("full_charge"); if (new_amount > max) { sender.sendMessage(plugin.getPluginName() + "You cannot overcharge this cell, transfer " + (max - level) + ", or use an empty cell!"); return false; } lore.set(1, "" + new_amount); im.setLore(lore); im.addEnchant(Enchantment.DURABILITY, 1, true); is.setItemMeta(im); // remove the energy from the tardis/timelord HashMap<String, Object> where = new HashMap<String, Object>(); String table; if (which.equals("tardis")) { where.put("owner", playerNameStr); table = "tardis"; } else { where.put("player", playerNameStr); table = "player_prefs"; } new QueryFactory(plugin).alterEnergyLevel(table, -amount, where, player); sender.sendMessage(plugin.getPluginName() + "Artron Storage Cell charged to " + new_amount); return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardisartron then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardisartron")) { if (!sender.hasPermission("tardis.store")) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_PERMS.getText()); return true; } if (args.length < 2) { return false; } Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { sender.sendMessage(plugin.getPluginName() + ChatColor.RED + MESSAGE.MUST_BE_PLAYER.getText()); return true; } ItemStack is = player.getItemInHand(); if (is == null || !is.hasItemMeta()) { sender.sendMessage(plugin.getPluginName() + "You must be holding an Artron Storage Cell in your hand!"); return true; } if (is.getAmount() > 1) { sender.sendMessage(plugin.getPluginName() + "You can only charge 1 Artron Storage Cell at a time!"); return true; } ItemMeta im = is.getItemMeta(); String name = im.getDisplayName(); if (name == null || !name.equals("Artron Storage Cell")) { sender.sendMessage(plugin.getPluginName() + "You must be holding an Artron Storage Cell in your hand!"); return true; } String which = args[0].toLowerCase(Locale.ENGLISH); if (!firstArgs.contains(which)) { sender.sendMessage(plugin.getPluginName() + "You must specify 'tardis' or 'timelord' energy to transfer!"); return false; } // must be a timelord String playerNameStr = player.getName(); int current_level; HashMap<String, Object> wheret = new HashMap<String, Object>(); if (which.equals("tardis")) { wheret.put("owner", playerNameStr); ResultSetTardis rs = new ResultSetTardis(plugin, wheret, "", false); if (!rs.resultSet()) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_TARDIS.getText()); return true; } current_level = rs.getArtron_level(); } else { wheret.put("player", playerNameStr); ResultSetPlayerPrefs rs = new ResultSetPlayerPrefs(plugin, wheret); if (!rs.resultSet()) { sender.sendMessage(plugin.getPluginName() + MESSAGE.NO_TARDIS.getText()); return true; } current_level = rs.getArtronLevel(); } int amount; try { amount = Integer.parseInt(args[1]); if (amount < 0) { sender.sendMessage(plugin.getPluginName() + "The amount cannot be negative!"); return true; } } catch (NumberFormatException n) { sender.sendMessage(plugin.getPluginName() + "The second command argument must be a number!"); return false; } // must have sufficient energy if (which.equals("tardis")) { if (current_level - amount < plugin.getArtronConfig().getInt("comehere")) { sender.sendMessage(plugin.getPluginName() + "You cannot transfer that much energy, you must have enough left to call your TARDIS!"); return true; } } else { if (current_level - amount < 0) { sender.sendMessage(plugin.getPluginName() + "You do not have that much Time Lord energy to transfer!"); return true; } } List<String> lore = im.getLore(); int level = plugin.getUtils().parseInt(lore.get(1)); int new_amount = amount + level; int max = plugin.getArtronConfig().getInt("full_charge"); if (new_amount > max) { sender.sendMessage(plugin.getPluginName() + "You cannot overcharge this cell, transfer " + (max - level) + ", or use an empty cell!"); return false; } lore.set(1, "" + new_amount); im.setLore(lore); im.addEnchant(Enchantment.DURABILITY, 1, true); is.setItemMeta(im); // remove the energy from the tardis/timelord HashMap<String, Object> where = new HashMap<String, Object>(); String table; if (which.equals("tardis")) { where.put("owner", playerNameStr); table = "tardis"; } else { where.put("player", playerNameStr); table = "player_prefs"; } new QueryFactory(plugin).alterEnergyLevel(table, -amount, where, player); sender.sendMessage(plugin.getPluginName() + "Artron Storage Cell charged to " + new_amount); return true; } return false; }
diff --git a/NearMeServer/src/com/nearme/DatabasePoiFinder.java b/NearMeServer/src/com/nearme/DatabasePoiFinder.java index 0f71514..32b4ef2 100644 --- a/NearMeServer/src/com/nearme/DatabasePoiFinder.java +++ b/NearMeServer/src/com/nearme/DatabasePoiFinder.java @@ -1,113 +1,113 @@ package com.nearme; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.apache.log4j.Logger; /** * A PoiFinder class which talks to an SQL database and pulls out lists of * Points of Interest * * @author twhume * */ public class DatabasePoiFinder implements PoiFinder { private static final Logger logger = Logger.getLogger(DatabasePoiFinder.class); private DataSource dataSource = null; static Connection conn = null; static String bd = "nearme"; static String login = "root"; static String password = "123"; static String url = "jdbc:mysql://localhost/" + bd; public static void main(String args[]) throws Exception { Class.forName("com.mysql.jdbc.Driver").newInstance(); // load the driver // of mysql conn = DriverManager.getConnection(url, login, password); // connect // with data // base if (conn != null) { logger.debug("Database connection " + url); // conn.close(); } } /* Talk to this DataSource to deal with the database */ public DatabasePoiFinder(DataSource d) { this.dataSource = d; } /** * Pull out a list of Points of Interest matching the contents of the * PoiQuery passed in, and return them in a list. */ public List<Poi> find(PoiQuery pq) throws SQLException { ArrayList<Poi> ret = new ArrayList<Poi>(); Connection conn = dataSource.getConnection(); PoiType type = null; /** * Algorithm taken from * * http://stackoverflow.com/questions/574691/mysql-great-circle-distance * -haversine-formula * */ String sql = "SELECT *, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance FROM poi WHERE type IN ("; for (int i: pq.getTypes()) { sql = sql + i + ","; } sql = sql.substring(0, sql.length()-1); sql = sql + ") HAVING distance < ? ORDER BY distance"; logger.debug("find() sql="+sql); PreparedStatement locationSearch = conn.prepareStatement(sql); locationSearch.setDouble(1, pq.getLatitude()); locationSearch.setDouble(2, pq.getLongitude()); locationSearch.setDouble(3, pq.getLatitude()); float radiusInKm = ((float) pq.getRadius() / 1000); locationSearch.setDouble(4, radiusInKm); ResultSet rs = locationSearch.executeQuery(); while (rs.next()) // Return false when there is not more data in the // table { - type = new PoiType("",rs.getInt("type")); + type = new PoiType("",rs.getInt("type")); //TODO ought to populate these with names too, by joining on types in the SQL query above Poi newPoi = new Poi(rs.getString("name"), rs.getDouble("latitude"), rs.getDouble("longitude"), type, rs.getInt("Id")); ret.add(newPoi); logger.debug("Found " + rs.getObject("name") + ", Longitude: " + rs.getObject("longitude") + ", Latitude: " + rs.getObject("latitude") +", distance="+ rs.getString("distance")); } rs.close(); return ret; } }
true
true
public List<Poi> find(PoiQuery pq) throws SQLException { ArrayList<Poi> ret = new ArrayList<Poi>(); Connection conn = dataSource.getConnection(); PoiType type = null; /** * Algorithm taken from * * http://stackoverflow.com/questions/574691/mysql-great-circle-distance * -haversine-formula * */ String sql = "SELECT *, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance FROM poi WHERE type IN ("; for (int i: pq.getTypes()) { sql = sql + i + ","; } sql = sql.substring(0, sql.length()-1); sql = sql + ") HAVING distance < ? ORDER BY distance"; logger.debug("find() sql="+sql); PreparedStatement locationSearch = conn.prepareStatement(sql); locationSearch.setDouble(1, pq.getLatitude()); locationSearch.setDouble(2, pq.getLongitude()); locationSearch.setDouble(3, pq.getLatitude()); float radiusInKm = ((float) pq.getRadius() / 1000); locationSearch.setDouble(4, radiusInKm); ResultSet rs = locationSearch.executeQuery(); while (rs.next()) // Return false when there is not more data in the // table { type = new PoiType("",rs.getInt("type")); Poi newPoi = new Poi(rs.getString("name"), rs.getDouble("latitude"), rs.getDouble("longitude"), type, rs.getInt("Id")); ret.add(newPoi); logger.debug("Found " + rs.getObject("name") + ", Longitude: " + rs.getObject("longitude") + ", Latitude: " + rs.getObject("latitude") +", distance="+ rs.getString("distance")); } rs.close(); return ret; }
public List<Poi> find(PoiQuery pq) throws SQLException { ArrayList<Poi> ret = new ArrayList<Poi>(); Connection conn = dataSource.getConnection(); PoiType type = null; /** * Algorithm taken from * * http://stackoverflow.com/questions/574691/mysql-great-circle-distance * -haversine-formula * */ String sql = "SELECT *, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance FROM poi WHERE type IN ("; for (int i: pq.getTypes()) { sql = sql + i + ","; } sql = sql.substring(0, sql.length()-1); sql = sql + ") HAVING distance < ? ORDER BY distance"; logger.debug("find() sql="+sql); PreparedStatement locationSearch = conn.prepareStatement(sql); locationSearch.setDouble(1, pq.getLatitude()); locationSearch.setDouble(2, pq.getLongitude()); locationSearch.setDouble(3, pq.getLatitude()); float radiusInKm = ((float) pq.getRadius() / 1000); locationSearch.setDouble(4, radiusInKm); ResultSet rs = locationSearch.executeQuery(); while (rs.next()) // Return false when there is not more data in the // table { type = new PoiType("",rs.getInt("type")); //TODO ought to populate these with names too, by joining on types in the SQL query above Poi newPoi = new Poi(rs.getString("name"), rs.getDouble("latitude"), rs.getDouble("longitude"), type, rs.getInt("Id")); ret.add(newPoi); logger.debug("Found " + rs.getObject("name") + ", Longitude: " + rs.getObject("longitude") + ", Latitude: " + rs.getObject("latitude") +", distance="+ rs.getString("distance")); } rs.close(); return ret; }
diff --git a/src/ClassAdminFrontEnd/StudentPopUp.java b/src/ClassAdminFrontEnd/StudentPopUp.java index b0e90c8..31a1e5e 100644 --- a/src/ClassAdminFrontEnd/StudentPopUp.java +++ b/src/ClassAdminFrontEnd/StudentPopUp.java @@ -1,118 +1,123 @@ package ClassAdminFrontEnd; import javax.swing.*; import ClassAdminBackEnd.EntityType; import ClassAdminBackEnd.Project; import ClassAdminBackEnd.SuperEntity; import ClassAdminBackEnd.AbsentLeafMarkEntity; import ClassAdminBackEnd.MarkEntity; import Frames.FrmNewNode; import Frames.FrmUpdateNode; import prefuse.Visualization; import prefuse.controls.ControlAdapter; import prefuse.data.Table; import prefuse.data.Tree; import prefuse.visual.VisualItem; import java.awt.event.*; import java.util.LinkedList; public class StudentPopUp { JPopupMenu pMenu; TreeView tview; VisualItem activeItem = null; Tree activeTree = null; Project activeProject; SuperEntity activeEntity; JDialog frame = null; LinkedList<SuperEntity> activeStudentTreeLinkedList = null; JFrame parentFrame; JTextArea txtChange; JButton btnChange; public StudentPopUp() { pMenu = new JPopupMenu(); JMenuItem miEdit = new JMenuItem("Edit"); pMenu.add(miEdit); JMenuItem miAbsent = new JMenuItem("Mark Absent"); pMenu.add(miAbsent); JMenuItem miNotAbsent = new JMenuItem("Mark not Absent"); pMenu.add(miNotAbsent); miEdit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { String id = item.getString("name"); tview.setSelectedEntity(item.getRow()); txtChange.setVisible(true); btnChange.setVisible(true); txtChange.setText(id.substring(id.indexOf(":") + 2)); txtChange.requestFocus(true); txtChange.selectAll(); } } }); miAbsent.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { - tview.setSuperEntity(item.getRow(), new AbsentLeafMarkEntity(tview.getSuperEntity(item.getRow()))); + AbsentLeafMarkEntity newM = new AbsentLeafMarkEntity(tview.getSuperEntity(item.getRow())); + tview.setSuperEntity(item.getRow(),newM); + activeProject.getSelected().add(newM); activeProject.updateTables(); String nodeName = item.getString("name"); nodeName = nodeName.substring(0, nodeName.indexOf(":") + 2) + "*ABSENT"; item.set("name", nodeName); item.getVisualization().run("filter"); activeProject.getAudit().updateStudent(activeProject.getStudentLinkedList().get(0).getValue(), activeProject.getStudentLinkedList().get(item.getRow()).getValue(), "*ABSENT", true); } } }); miNotAbsent.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { - tview.setSuperEntity(item.getRow(),new MarkEntity(tview.getSuperEntity(item.getRow()))); + MarkEntity newM = new MarkEntity(tview.getSuperEntity(item.getRow())); + tview.setSuperEntity(item.getRow(),newM); + activeProject.getSelected().add(newM); + newM.setMark(0.0); activeProject.updateTables(); String nodeName = item.getString("name"); nodeName = nodeName.substring(0, nodeName.indexOf(":") + 2) + "N/A"; item.set("name", nodeName); item.getVisualization().run("filter"); activeProject.getAudit().updateStudent(activeProject.getStudentLinkedList().get(0).getValue(), activeProject.getStudentLinkedList().get(item.getRow()).getValue(), "NOT ABSENT", true); } } }); } public void setTreeView(TreeView treeView, Tree tree, Project project, JFrame pFrame,JTextArea tChange, JButton bChange) { activeProject = project; activeStudentTreeLinkedList = activeProject.getStudentLinkedList(); activeTree = tree; tview = treeView; parentFrame = pFrame; txtChange = tChange; btnChange = bChange; // add control listener for nodes on front end treeview tview.addControlListener(new ControlAdapter() { public void itemReleased(VisualItem item, MouseEvent e) { activeItem = null; if (e.isPopupTrigger()) { if (item.canGetString("name")) { pMenu.show(e.getComponent(), e.getX(), e.getY()); activeItem = item; activeItem.getVisualization().run("filter"); activeEntity = activeStudentTreeLinkedList.get(activeItem.getRow()); } } } }); } }
false
true
public StudentPopUp() { pMenu = new JPopupMenu(); JMenuItem miEdit = new JMenuItem("Edit"); pMenu.add(miEdit); JMenuItem miAbsent = new JMenuItem("Mark Absent"); pMenu.add(miAbsent); JMenuItem miNotAbsent = new JMenuItem("Mark not Absent"); pMenu.add(miNotAbsent); miEdit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { String id = item.getString("name"); tview.setSelectedEntity(item.getRow()); txtChange.setVisible(true); btnChange.setVisible(true); txtChange.setText(id.substring(id.indexOf(":") + 2)); txtChange.requestFocus(true); txtChange.selectAll(); } } }); miAbsent.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { tview.setSuperEntity(item.getRow(), new AbsentLeafMarkEntity(tview.getSuperEntity(item.getRow()))); activeProject.updateTables(); String nodeName = item.getString("name"); nodeName = nodeName.substring(0, nodeName.indexOf(":") + 2) + "*ABSENT"; item.set("name", nodeName); item.getVisualization().run("filter"); activeProject.getAudit().updateStudent(activeProject.getStudentLinkedList().get(0).getValue(), activeProject.getStudentLinkedList().get(item.getRow()).getValue(), "*ABSENT", true); } } }); miNotAbsent.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { tview.setSuperEntity(item.getRow(),new MarkEntity(tview.getSuperEntity(item.getRow()))); activeProject.updateTables(); String nodeName = item.getString("name"); nodeName = nodeName.substring(0, nodeName.indexOf(":") + 2) + "N/A"; item.set("name", nodeName); item.getVisualization().run("filter"); activeProject.getAudit().updateStudent(activeProject.getStudentLinkedList().get(0).getValue(), activeProject.getStudentLinkedList().get(item.getRow()).getValue(), "NOT ABSENT", true); } } }); }
public StudentPopUp() { pMenu = new JPopupMenu(); JMenuItem miEdit = new JMenuItem("Edit"); pMenu.add(miEdit); JMenuItem miAbsent = new JMenuItem("Mark Absent"); pMenu.add(miAbsent); JMenuItem miNotAbsent = new JMenuItem("Mark not Absent"); pMenu.add(miNotAbsent); miEdit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { String id = item.getString("name"); tview.setSelectedEntity(item.getRow()); txtChange.setVisible(true); btnChange.setVisible(true); txtChange.setText(id.substring(id.indexOf(":") + 2)); txtChange.requestFocus(true); txtChange.selectAll(); } } }); miAbsent.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { AbsentLeafMarkEntity newM = new AbsentLeafMarkEntity(tview.getSuperEntity(item.getRow())); tview.setSuperEntity(item.getRow(),newM); activeProject.getSelected().add(newM); activeProject.updateTables(); String nodeName = item.getString("name"); nodeName = nodeName.substring(0, nodeName.indexOf(":") + 2) + "*ABSENT"; item.set("name", nodeName); item.getVisualization().run("filter"); activeProject.getAudit().updateStudent(activeProject.getStudentLinkedList().get(0).getValue(), activeProject.getStudentLinkedList().get(item.getRow()).getValue(), "*ABSENT", true); } } }); miNotAbsent.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VisualItem item = activeItem; if (item.canGetString("name")) { MarkEntity newM = new MarkEntity(tview.getSuperEntity(item.getRow())); tview.setSuperEntity(item.getRow(),newM); activeProject.getSelected().add(newM); newM.setMark(0.0); activeProject.updateTables(); String nodeName = item.getString("name"); nodeName = nodeName.substring(0, nodeName.indexOf(":") + 2) + "N/A"; item.set("name", nodeName); item.getVisualization().run("filter"); activeProject.getAudit().updateStudent(activeProject.getStudentLinkedList().get(0).getValue(), activeProject.getStudentLinkedList().get(item.getRow()).getValue(), "NOT ABSENT", true); } } }); }
diff --git a/src/test/java/org/apache/ibatis/submitted/null_with_no_jdbctype/NullWithNoJdbcTypeTest.java b/src/test/java/org/apache/ibatis/submitted/null_with_no_jdbctype/NullWithNoJdbcTypeTest.java index 37390925d8..38d6f53fbd 100644 --- a/src/test/java/org/apache/ibatis/submitted/null_with_no_jdbctype/NullWithNoJdbcTypeTest.java +++ b/src/test/java/org/apache/ibatis/submitted/null_with_no_jdbctype/NullWithNoJdbcTypeTest.java @@ -1,95 +1,95 @@ /* * Copyright 2009-2011 The MyBatis Team * * 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.ibatis.submitted.null_with_no_jdbctype; import domain.blog.Author; import domain.blog.Section; import org.apache.ibatis.BaseDataTest; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import org.apache.ibatis.type.JdbcType; import org.junit.Test; import javax.sql.DataSource; import static org.junit.Assert.*; public class NullWithNoJdbcTypeTest extends BaseDataTest { private static interface JPetStoreMapper { @Insert("INSERT INTO category (catid, name, descn) VALUES (#{id},#{name},#{description})") int insertCategory(@Param("id") String id, @Param("name") String name, @Param("description") String description); } @Test public void shouldSucceedAddingRowWithNullValueWithHSQLDB() throws Exception { DataSource ds = BaseDataTest.createJPetstoreDataSource(); Environment env = new Environment("test", new JdbcTransactionFactory(), ds); Configuration config = new Configuration(env); config.addMapper(JPetStoreMapper.class); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlMapper = builder.build(config); SqlSession session = sqlMapper.openSession(); try { JPetStoreMapper mapper = session.getMapper(JPetStoreMapper.class); int n = mapper.insertCategory("MONKEYS", null, "Big hairy friendly (sometimes) mammals..."); assertEquals(1, n); session.rollback(); } finally { if (session != null) session.close(); } } private static interface BlogMapper { @Insert("insert into " + "Author (id,username,password,email,bio,favourite_section) " + "values(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection})") int insertAuthor(Author author); } @Test public void shouldFailAddingRowWithNullValueWithDerby() throws Exception { DataSource ds = BaseDataTest.createBlogDataSource(); Environment env = new Environment("test", new JdbcTransactionFactory(), ds); Configuration config = new Configuration(env); config.addMapper(BlogMapper.class); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlMapper = builder.build(config); SqlSession session = sqlMapper.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); int n = 0; try { n = mapper.insertAuthor(new Author(99999, "barney", "******", "[email protected]", null, Section.NEWS)); fail("Expected exception."); } catch (Exception e) { - assertTrue(e.getMessage().contains("Error setting null parameter")); + assertTrue(e.getMessage().contains("Error setting null")); } session.rollback(); } finally { if (session != null) session.close(); } } }
true
true
public void shouldFailAddingRowWithNullValueWithDerby() throws Exception { DataSource ds = BaseDataTest.createBlogDataSource(); Environment env = new Environment("test", new JdbcTransactionFactory(), ds); Configuration config = new Configuration(env); config.addMapper(BlogMapper.class); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlMapper = builder.build(config); SqlSession session = sqlMapper.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); int n = 0; try { n = mapper.insertAuthor(new Author(99999, "barney", "******", "[email protected]", null, Section.NEWS)); fail("Expected exception."); } catch (Exception e) { assertTrue(e.getMessage().contains("Error setting null parameter")); } session.rollback(); } finally { if (session != null) session.close(); } }
public void shouldFailAddingRowWithNullValueWithDerby() throws Exception { DataSource ds = BaseDataTest.createBlogDataSource(); Environment env = new Environment("test", new JdbcTransactionFactory(), ds); Configuration config = new Configuration(env); config.addMapper(BlogMapper.class); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlMapper = builder.build(config); SqlSession session = sqlMapper.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); int n = 0; try { n = mapper.insertAuthor(new Author(99999, "barney", "******", "[email protected]", null, Section.NEWS)); fail("Expected exception."); } catch (Exception e) { assertTrue(e.getMessage().contains("Error setting null")); } session.rollback(); } finally { if (session != null) session.close(); } }
diff --git a/src/prettify/example/Example.java b/src/prettify/example/Example.java index a5ea2f4..45d4e93 100644 --- a/src/prettify/example/Example.java +++ b/src/prettify/example/Example.java @@ -1,124 +1,124 @@ // Copyright (C) 2011 Chan Wai Shing // // 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 prettify.example; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; import prettify.PrettifyParser; import prettify.theme.ThemeDefault; import syntaxhighlight.Parser; import syntaxhighlight.SyntaxHighlighter; /** * Usage example. This will just cover some of the functions. To know other * available functions, please read the JavaDoc. * * @author Chan Wai Shing <[email protected]> */ public class Example { private static final Logger LOG = Logger.getLogger(Example.class.getName()); /** * Read the resource file from the jar. * @param path the resource path * @return the content of the resource file in byte array * @throws IOException error occurred when reading the content from the file */ public static byte[] readResourceFile(String path) throws IOException { if (path == null) { throw new NullPointerException("argument 'path' cannot be null"); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); InputStream in = null; try { in = Example.class.getResourceAsStream(path); if (in == null) { throw new IOException("Resources not found: " + path); } int byteRead = 0; byte[] b = new byte[8096]; while ((byteRead = in.read(b)) != -1) { bout.write(b, 0, byteRead); } } finally { if (in != null) { try { in.close(); } catch (IOException ex) { } } } return bout.toByteArray(); } public static void main(String[] args) { // set look & feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { LOG.log(Level.INFO, "Failed to set system look and feel.", ex); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // timer start long start, end; start = System.currentTimeMillis(); // the Prettify parser Parser parser = new PrettifyParser(); - // use Default theme + // initialize the highlighter and use Default theme SyntaxHighlighter highlighter = new SyntaxHighlighter(parser, new ThemeDefault()); // set the line number count from 10 instead of 1 highlighter.setFirstLine(10); // set to highlight line 13, 27, 28, 38, 42, 43 and 53 highlighter.setHighlightedLineList(Arrays.asList(13, 27, 28, 38, 42, 43, 53)); try { // set the content of the script, the example.html is located in the jar: /prettify/example/example.html highlighter.setContent(new String(readResourceFile("/prettify/example/example.html"))); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } // timer end end = System.currentTimeMillis(); System.out.println("time elapsed: " + (end - start) + "ms"); // initiate a frame and display JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // SyntaxHighlighter is actually a JScrollPane frame.setContentPane(highlighter); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); } }); } }
true
true
public static void main(String[] args) { // set look & feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { LOG.log(Level.INFO, "Failed to set system look and feel.", ex); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // timer start long start, end; start = System.currentTimeMillis(); // the Prettify parser Parser parser = new PrettifyParser(); // use Default theme SyntaxHighlighter highlighter = new SyntaxHighlighter(parser, new ThemeDefault()); // set the line number count from 10 instead of 1 highlighter.setFirstLine(10); // set to highlight line 13, 27, 28, 38, 42, 43 and 53 highlighter.setHighlightedLineList(Arrays.asList(13, 27, 28, 38, 42, 43, 53)); try { // set the content of the script, the example.html is located in the jar: /prettify/example/example.html highlighter.setContent(new String(readResourceFile("/prettify/example/example.html"))); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } // timer end end = System.currentTimeMillis(); System.out.println("time elapsed: " + (end - start) + "ms"); // initiate a frame and display JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // SyntaxHighlighter is actually a JScrollPane frame.setContentPane(highlighter); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); } }); }
public static void main(String[] args) { // set look & feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { LOG.log(Level.INFO, "Failed to set system look and feel.", ex); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // timer start long start, end; start = System.currentTimeMillis(); // the Prettify parser Parser parser = new PrettifyParser(); // initialize the highlighter and use Default theme SyntaxHighlighter highlighter = new SyntaxHighlighter(parser, new ThemeDefault()); // set the line number count from 10 instead of 1 highlighter.setFirstLine(10); // set to highlight line 13, 27, 28, 38, 42, 43 and 53 highlighter.setHighlightedLineList(Arrays.asList(13, 27, 28, 38, 42, 43, 53)); try { // set the content of the script, the example.html is located in the jar: /prettify/example/example.html highlighter.setContent(new String(readResourceFile("/prettify/example/example.html"))); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } // timer end end = System.currentTimeMillis(); System.out.println("time elapsed: " + (end - start) + "ms"); // initiate a frame and display JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // SyntaxHighlighter is actually a JScrollPane frame.setContentPane(highlighter); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); } }); }
diff --git a/java/engine/org/apache/derby/impl/load/ImportReadData.java b/java/engine/org/apache/derby/impl/load/ImportReadData.java index 8df7e3145..d8fb27e50 100644 --- a/java/engine/org/apache/derby/impl/load/ImportReadData.java +++ b/java/engine/org/apache/derby/impl/load/ImportReadData.java @@ -1,1074 +1,1074 @@ /* Derby - Class org.apache.derby.impl.load.ImportReadData 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.derby.impl.load; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.IOException; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import org.apache.derby.iapi.services.sanity.SanityManager; import java.sql.SQLException; final class ImportReadData implements java.security.PrivilegedExceptionAction { //Read data from this file private String inputFileName; private int[] columnWidths; private int rowWidth; private char[] tempString; private int numberOfCharsReadSoFar; //temporary variables private BufferedReader bufferedReader; //temporary variable which holds each token as we are building it. private static final int START_SIZE = 10240; private char[] currentToken = new char[START_SIZE]; private int currentTokenMaxSize = START_SIZE; //This tells whether to look for a matching stop pattern boolean foundStartDelimiter; int totalCharsSoFar; //following is used to ignore whitespaces in the front int positionOfNonWhiteSpaceCharInFront; //following is used to ignore whitespaces in the back int positionOfNonWhiteSpaceCharInBack; int lineNumber; int fieldStartDelimiterIndex; int fieldStopDelimiterIndex; int stopDelimiterPosition; boolean foundStartAndStopDelimiters; //in the constructor we open the stream only if it's delimited file to find out //number of columns. In case of fixed, we know that already from the control file. //then we close the stream. Now the stream is reopened when the first record is //read from the file(ie when the first time next is issued. This was done for the //bug 1032 filed by Dan boolean streamOpenForReading; static final int DEFAULT_FORMAT_CODE = 0; static final int ASCII_FIXED_FORMAT_CODE = 1; private int formatCode = DEFAULT_FORMAT_CODE; private boolean hasColumnDefinition; private char recordSeparatorChar0; private char fieldSeparatorChar0; private boolean recordSepStartNotWhite = true; private boolean fieldSepStartNotWhite = true; //get properties infr from following protected ControlInfo controlFileReader; //Read first row to find out how many columns make up a row and put it in //the following variable protected int numberOfColumns; // the types of the columns that we are about to read protected String [] columnTypes; //Read control file properties and write it in here protected char[] fieldSeparator; protected int fieldSeparatorLength; protected char[] recordSeparator; protected int recordSeparatorLength; protected String nullString; protected String columnDefinition; protected String format; protected String dataCodeset; protected char[] fieldStartDelimiter; protected int fieldStartDelimiterLength; protected char[] fieldStopDelimiter; protected int fieldStopDelimiterLength; protected boolean hasDelimiterAtEnd; // variables realted to reading lob data from files. private ImportLobFile[] lobFileHandles; // lob file handle object private String lobFileName; // current file name private int lobOffset; // offset of the current large object private int lobLength; //length of the current large object //load the control file properties info locally, since we need to refer to them //all the time while looking for tokens private void loadPropertiesInfo() throws Exception { fieldSeparator = controlFileReader.getFieldSeparator().toCharArray(); fieldSeparatorLength = fieldSeparator.length; recordSeparator = controlFileReader.getRecordSeparator().toCharArray(); recordSeparatorLength = recordSeparator.length; nullString = controlFileReader.getNullString(); columnDefinition = controlFileReader.getColumnDefinition(); format = controlFileReader.getFormat(); dataCodeset = controlFileReader.getDataCodeset(); fieldStartDelimiter = controlFileReader.getFieldStartDelimiter().toCharArray(); fieldStartDelimiterLength = fieldStartDelimiter.length; fieldStopDelimiter = controlFileReader.getFieldEndDelimiter().toCharArray(); fieldStopDelimiterLength = fieldStopDelimiter.length; hasDelimiterAtEnd = controlFileReader.getHasDelimiterAtEnd(); // when record or field separators start with typical white space, // we can't ignore it around values in the import file. So set up // a boolean so we don't keep re-testing for it. if (recordSeparatorLength >0) { recordSeparatorChar0=recordSeparator[0]; recordSepStartNotWhite = (Character.isWhitespace(recordSeparatorChar0)==false); } if (fieldSeparatorLength >0) { fieldSeparatorChar0=fieldSeparator[0]; fieldSepStartNotWhite = (Character.isWhitespace(fieldSeparatorChar0)==false); } } //inputFileName: File to read data from //controlFileReader: File used to interpret data in the inputFileName ImportReadData(String inputFileName, ControlInfo controlFileReader) throws Exception { this.inputFileName = inputFileName; this.controlFileReader = controlFileReader; //load the control file properties info locally, since we need to refer to //them all the time while looking for tokens loadPropertiesInfo(); //read the first row to find how many columns make a row and then save that //column information for further use loadMetaData(); lobFileHandles = new ImportLobFile[numberOfColumns]; } //just a getter returning number of columns for a row in the data file int getNumberOfColumns() { return numberOfColumns; } /**if columndefinition is true, ignore first row. The way to do that is to just * look for the record separator * @exception Exception if there is an error */ protected void ignoreFirstRow() throws Exception { readNextToken(recordSeparator, 0, recordSeparatorLength, true); } /** load the column types from the meta data line to be analyzed * later in the constructor of the ImportResultSetMetaData. */ protected void loadColumnTypes() throws Exception { int idx; String [] metaDataArray; // start by counting the number of columns that we have at the // meta data line findNumberOfColumnsInARow(); // reopen the file to the start of the file to read the actual column types data closeStream(); openFile(); // make room for the meta data metaDataArray=new String [numberOfColumns]; // read the meta data line line - meta data is always in a delimited format readNextDelimitedRow(metaDataArray); // allocate space for the columnTypes meta data // since the meta data line contains a combination of column name and // column type for every column we actually have only half the number of // columns that was counted. columnTypes=new String[numberOfColumns/2]; for(idx=0 ; idx<numberOfColumns ; idx=idx+2) { columnTypes[idx/2]=metaDataArray[idx+1]; } // reopen to the start of the file so the rest of the program will // work as expected closeStream(); openFile(); // init the numberOfColumns variable since it is // being accumulate by the findNumberOfColumnsInARow method numberOfColumns=0; } private void openFile() throws Exception { try { java.security.AccessController.doPrivileged(this); } catch (java.security.PrivilegedActionException pae) { throw pae.getException(); } } public final Object run() throws Exception { realOpenFile(); return null; } //open the input data file for reading private void realOpenFile() throws Exception { InputStream inputStream; try { try { URL url = new URL(inputFileName); if (url.getProtocol().equals("file")) { //this means it's a file url inputFileName = url.getFile(); //seems like you can't do openstream on file throw new MalformedURLException(); //so, get the filename from url and do it ususal way } inputStream = url.openStream(); } catch (MalformedURLException ex) { inputStream = new FileInputStream(inputFileName); } } catch (FileNotFoundException ex) { throw LoadError.dataFileNotFound(inputFileName); } catch (SecurityException se) { java.sql.SQLException sqle = LoadError.dataFileNotFound(inputFileName); sqle.setNextException(new java.sql.SQLException("XJ001", se.getMessage(), 0)); throw sqle; } java.io.Reader rd = dataCodeset == null ? new InputStreamReader(inputStream) : new InputStreamReader(inputStream, dataCodeset); bufferedReader = new BufferedReader(rd, 32*1024); streamOpenForReading = true; } //read the first data row to find how many columns make a row and then save that //column information for future use private void loadMetaData() throws Exception { //open the input data file for reading the metadata information openFile(); // if column definition is true, ignore the first row since that's not // really the data do uppercase because the ui shows the values as True // and False if (columnDefinition.toUpperCase(java.util.Locale.ENGLISH).equals(ControlInfo.INTERNAL_TRUE.toUpperCase(java.util.Locale.ENGLISH))) { hasColumnDefinition = true; ignoreFirstRow(); } if (formatCode == DEFAULT_FORMAT_CODE) { findNumberOfColumnsInARow(); } closeStream(); } /**close the input data file * @exception Exception if there is an error */ void closeStream() throws Exception { if (streamOpenForReading) { bufferedReader.close(); streamOpenForReading = false; } // close external lob file resources. if (lobFileHandles != null) { for (int i = 0 ; i < numberOfColumns ; i++) { if(lobFileHandles[i] != null) lobFileHandles[i].close(); } } } //actually looks at the data file to find how many columns make up a row int findNumberOfColumnsInARow() throws Exception { // init the number of columns to 1 - no such thing as a table // without columns numberOfColumns=1; while (! readTokensUntilEndOfRecord() ) { numberOfColumns++; } //--numberOfColumns; //what shall we do if there is delimeter after the last column? //reducing the number of columns seems to work fine. //this is necessary to be able to read delimited files that have a delimeter //at the end of a row. if (hasDelimiterAtEnd){ --numberOfColumns; } // a special check - if the imported file is empty then // set the number of columns to 0 if (numberOfCharsReadSoFar==0) { numberOfColumns=0; } return numberOfColumns; } //keep track of white spaces in the front. We use positionOfNonWhiteSpaceCharInFront for //that. It has the count of number of white spaces found so far before any non-white char //in the token. //Look for whitespace only if field start delimiter is not found yet. Any white spaces //within the start and stop delimiters are ignored. //Also if one of the white space chars is same as recordSeparator or fieldSeparator then //disregard it. private void checkForWhiteSpaceInFront() { //if found white space characters so far, the following if will be true if ((positionOfNonWhiteSpaceCharInFront + 1) == totalCharsSoFar && ((!foundStartDelimiter) && (!foundStartAndStopDelimiters) )) { char currentChar = currentToken[positionOfNonWhiteSpaceCharInFront]; if (//currentChar == '\t' || //currentChar == '\r' || alc: why isn't this included? // alc: BTW, \r and \n should be replaced // or amended with the first char of line.separator... //currentChar == '\n' || //currentChar == ' ') { // use String.trim()'s definition of whitespace. // i18n - check for whitespace - avoid doing a hard coded character // check and use the isWhitespace method to cover all the Unicode // options Character.isWhitespace(currentChar) == true) { if ((recordSepStartNotWhite || (currentChar != recordSeparatorChar0)) && (fieldSepStartNotWhite || (currentChar != fieldSeparatorChar0))) //disregard if whitespace char is same as separator first char positionOfNonWhiteSpaceCharInFront++; } } } //look for white spaces from the back towards the stop delimiter position. //If there was no startdelimite & stopdelimiter combination, then we start from the back //all the way to the beginning and stop when we find non-white char //positionOfNonWhiteSpaceCharInBack keeps the count of whitespaces at the back private void checkForWhiteSpaceInBack() { boolean onlyWhiteSpaceSoFar = true; positionOfNonWhiteSpaceCharInBack = 0; for (int i = totalCharsSoFar; (i > stopDelimiterPosition) && onlyWhiteSpaceSoFar; i--) { char currentChar = currentToken[i]; // replace test on \t,\n,' ' with String.trim's definition of white space // i18n - check for whitespace - avoid doing a hard coded character // check and use the isWhitespace method to cover all the Unicode // options if (Character.isWhitespace(currentChar)==true) { if ((recordSepStartNotWhite || (currentChar != recordSeparatorChar0)) && (fieldSepStartNotWhite || (currentChar != fieldSeparatorChar0))) //disregard if whitespace char is same as separator first char positionOfNonWhiteSpaceCharInBack++; } else onlyWhiteSpaceSoFar = false; } } //keep looking for field and record separators simultaneously because we don't yet //know how many columns make up a row in this data file. Stop as soon as we get //the record separator which is indicated by a return value of true from this function boolean readTokensUntilEndOfRecord() throws Exception { int nextChar; int fieldSeparatorIndex = 0; int recordSeparatorIndex = 0; fieldStopDelimiterIndex = 0; fieldStartDelimiterIndex = 0; totalCharsSoFar = 0; //at the start of every new token, make white space in front count 0 positionOfNonWhiteSpaceCharInFront = 0; foundStartDelimiter = false; foundStartAndStopDelimiters = false; numberOfCharsReadSoFar = 0; while (true) { nextChar = bufferedReader.read(); if (nextChar == -1) return true; numberOfCharsReadSoFar++; //read the character into the token holder. If token holder reaches it's capacity, //double it's capacity currentToken[totalCharsSoFar++] = (char)nextChar; //check if character read is white space char in front checkForWhiteSpaceInFront(); if (totalCharsSoFar == currentTokenMaxSize) { currentTokenMaxSize = currentTokenMaxSize * 2; char[] tempArray = new char[currentTokenMaxSize]; System.arraycopy(currentToken, 0, tempArray, 0, totalCharsSoFar); currentToken = tempArray; } //see if we can find fieldSeparator fieldSeparatorIndex = lookForPassedSeparator(fieldSeparator, fieldSeparatorIndex, fieldSeparatorLength, nextChar, false); //every time we find a column separator, the return false will indicate that count //this token as column data value and keep lookin for more tokens or record //separator if (fieldSeparatorIndex == -1) return false; //if found start delimiter, then don't look for record separator, just look for //end delimiter if (!foundStartDelimiter ) { //see if we can find recordSeparator recordSeparatorIndex = lookForPassedSeparator(recordSeparator, recordSeparatorIndex, recordSeparatorLength, nextChar, true); if (recordSeparatorIndex == -1) return true; } } } //if not inside a start delimiter, then look for the delimiter passed //else look for stop delimiter first. //this routine returns -1 if it finds field delimiter or record delimiter private int lookForPassedSeparator(char[] delimiter, int delimiterIndex, int delimiterLength, int nextChar, boolean lookForRecordSeperator) throws IOException { //foundStartDelimiter will be false if we haven't found a start delimiter yet //if we haven't found startdelimiter, then we look for both start delimiter //and passed delimiter(which can be field or record delimiter). If we do find //start delimiter, then we only look for stop delimiter and not the passed delimiter. if (!foundStartDelimiter ) { //look for start delimiter only if it's length is non-zero and only if haven't already //found it at all so far. if (fieldStartDelimiterLength != 0 && (!foundStartAndStopDelimiters) ) { //the code inside following if will be executed only if we have gone past all the //white characters in the front. if (totalCharsSoFar != positionOfNonWhiteSpaceCharInFront && (totalCharsSoFar - positionOfNonWhiteSpaceCharInFront) <= fieldStartDelimiterLength) { //After getting rid of white spaces in front, look for the start delimiter. If //found, set foundStartDelimiter flag. if (nextChar == fieldStartDelimiter[fieldStartDelimiterIndex]){ fieldStartDelimiterIndex++; if (fieldStartDelimiterIndex == fieldStartDelimiterLength) { foundStartDelimiter = true; //since characters read so far are same as start delimiters, discard those chars totalCharsSoFar = 0; positionOfNonWhiteSpaceCharInFront = 0; return 0; } } else { //found a mismatch for the start delimiter //see if found match for more than one char of this start delimiter before the //current mismatch, if so check the remaining chars agains //eg if stop delimiter is xa and data is xxa if (fieldStartDelimiterIndex > 0) { reCheckRestOfTheCharacters(totalCharsSoFar-fieldStartDelimiterIndex, fieldStartDelimiter, fieldStartDelimiterLength); } } } } /*look for typical record seperators line feed (\n), a carriage return * (\r) or a carriage return followed by line feed (\r\n) */ if(lookForRecordSeperator) { if(nextChar == '\r' || nextChar == '\n') { recordSeparatorChar0 = (char) nextChar; if(nextChar == '\r' ) { //omot the line feed character if it exists in the stream omitLineFeed(); } totalCharsSoFar = totalCharsSoFar - 1 ; return -1; } return delimiterIndex; } //look for passed delimiter if (nextChar == delimiter[delimiterIndex]) { delimiterIndex++; if (delimiterIndex == delimiterLength) { //found passed delimiter totalCharsSoFar = totalCharsSoFar - delimiterLength; return -1; } return delimiterIndex; //this number of chars of delimiter have exact match so far } else { //found a mismatch for the delimiter //see if found match for more than one char of this delimiter before the //current mismatch, if so check the remaining chars agains //eg if delimiter is xa and data is xxa if (delimiterIndex > 0) return(reCheckRestOfTheCharacters(totalCharsSoFar-delimiterIndex, delimiter, delimiterLength)); } } else { //see if we can find fieldStopDelimiter if (nextChar == fieldStopDelimiter[fieldStopDelimiterIndex]) { fieldStopDelimiterIndex++; if (fieldStopDelimiterIndex == fieldStopDelimiterLength) { boolean skipped = skipDoubleDelimiters(fieldStopDelimiter); if(!skipped) { foundStartDelimiter = false; //found stop delimiter, discard the chars corresponding to stop delimiter totalCharsSoFar = totalCharsSoFar - fieldStopDelimiterLength; //following is to take care of a case like "aa"aa This will result in an //error. Also a case like "aa" will truncate it to just aa stopDelimiterPosition = totalCharsSoFar; //following is used to distinguish between empty string ,"", and null string ,, foundStartAndStopDelimiters = true; }else { fieldStopDelimiterIndex =0 ; } return 0; } return 0; } else { //found a mismatch for the stop delimiter //see if found match for more than one char of this stop delimiter before the //current mismatch, if so check the remaining chars agains //eg if stop delimiter is xa and data is xxa if (fieldStopDelimiterIndex > 0) { reCheckRestOfTheCharacters(totalCharsSoFar-fieldStopDelimiterIndex, fieldStopDelimiter, fieldStopDelimiterLength); return 0; } } } return 0; } //If after finding a few matching characters for a delimiter, find a mismatch, //restart the matching process from character next to the one from which you //were in the process of finding the matching pattern private int reCheckRestOfTheCharacters(int startFrom, char[] delimiter, int delimiterLength) { int delimiterIndex = 0; // alc: need to test delim of abab with abaabab // if delimIndex resets to 0, i probably needs to reset to // (an ever increasing) startFrom=startFrom+1, not stay where it is for (int i = startFrom; i<totalCharsSoFar; i++) { if (currentToken[i] == delimiter[delimiterIndex]) delimiterIndex++; else delimiterIndex = 0; } return delimiterIndex; } /* * skips the duplicate delimeter characters inserd character stringd ata * to get the original string. In Double Delimter recognigation Delimiter * Format strings are written with a duplicate delimeter if a delimiter is * found inside the data while exporting. * For example with double quote(") as character delimiter * * "What a ""nice""day!" * * will be imported as: * * What a "nice"day! * * In the case of export, the rule applies in reverse. For example, * * I am 6"tall. * * will be exported to a file as: * * "I am 6""tall." */ private boolean skipDoubleDelimiters(char [] characterDelimiter) throws IOException { boolean skipped = true; int cDelLength = characterDelimiter.length ; bufferedReader.mark(cDelLength); for(int i = 0 ; i < cDelLength ; i++) { int nextChar = bufferedReader.read(); if(nextChar != characterDelimiter[i]) { //not a double delimter case bufferedReader.reset(); skipped = false; break; } } return skipped; } //omit the line feed character(\n) private void omitLineFeed() throws IOException { bufferedReader.mark(1); int nextChar = bufferedReader.read(); if(nextChar != '\n') { //not a Line Feed bufferedReader.reset(); } } /**returns the number of the current row */ int getCurrentRowNumber() { return lineNumber; } /**the way we read the next row from input file depends on it's format * @exception Exception if there is an error */ boolean readNextRow(String[] returnStringArray) throws Exception { boolean readVal; int idx; if (!streamOpenForReading) { openFile(); //as earlier, ignore the first row if it's colum definition //do uppercase because the ui shows the values as True and False if (hasColumnDefinition){ ignoreFirstRow(); } } if (formatCode == DEFAULT_FORMAT_CODE) readVal=readNextDelimitedRow(returnStringArray); else readVal=readNextFixedRow(returnStringArray); return readVal; } // made this a field so it isn't inited for each row, just // set and cleared on the rows that need it (the last row // in a file, typically, so it isn't used much) private boolean haveSep = true; //read the specified column width for each column private boolean readNextFixedRow(String[] returnStringArray) throws Exception { // readLength is how many bytes it has read so far int readLength = 0; int totalLength = 0; // keep reading until rolWidth bytes have been read while ((readLength += bufferedReader.read(tempString, readLength, rowWidth-readLength)) < rowWidth) { if (readLength == totalLength-1) {// EOF if ( readLength == -1) { // no row, EOF return false; } else { // it's only a bad read if insufficient data was // returned; missing the last record separator is ok if (totalLength != rowWidth - recordSeparator.length) { throw LoadError.unexpectedEndOfFile(lineNumber+1); } else { haveSep = false; break; } } } // else, some thing is read, continue until the whole column is // read totalLength = readLength; } int colStart = 0; for (int i=0; i< numberOfColumns; i++) { int colWidth = columnWidths[i]; if (colWidth == 0) //if column width is 0, return null returnStringArray[i] = null; else { // if found nullstring, return it as null value String checkAgainstNullString = new String(tempString, colStart, colWidth); if (checkAgainstNullString.trim().equals(nullString)) returnStringArray[i] = null; else returnStringArray[i] = checkAgainstNullString; colStart += colWidth; } } //if what we read is not recordSeparator, throw an exception if (haveSep) { for (int i=(recordSeparatorLength-1); i>=0; i--) { if (tempString[colStart+i] != recordSeparator[i]) throw LoadError.recordSeparatorMissing(lineNumber+1); } } else haveSep = true; // reset for the next time, if any. lineNumber++; return true; } //by this time, we know number of columns that make up a row in this data file //so first look for number of columns-1 field delimites and then look for record //delimiter private boolean readNextDelimitedRow(String[] returnStringArray) throws Exception { int upperLimit = numberOfColumns-1; //reduce # field accesses //no data in the input file for some reason if (upperLimit < 0) return false; //look for number of columns - 1 field separators for (int i = 0; i<upperLimit; i++) { if (!readNextToken(fieldSeparator, 0, fieldSeparatorLength, false) ) { if (i == 0) // still on the first check return false; else throw LoadError.unexpectedEndOfFile(lineNumber+1); } //following is to take care of a case like "aa"aa This will result in an //error. Also a case like "aa" will truncate it to just aa. valid blank //chars are ' ' '\r' '\t' if (stopDelimiterPosition!=0 && ((stopDelimiterPosition) != totalCharsSoFar)) { for (int k=stopDelimiterPosition+1; k<totalCharsSoFar; k++) { // alc: should change || to && since || case is never true -- // currentChar can't be three different things at once. // alc: why no \n? BTW, \r and \n should be replaced // or amended with the first char of line.separator... //char currentChar = currentToken[k]; //if (currentChar != ' ' && currentChar != '\r' && currentChar != '\t') // use String.trim()'s definition of whitespace. // i18n - check for whitespace - avoid doing a hard coded // character check and use the isWhitespace method to cover all // the Unicode options if (Character.isWhitespace(currentToken[k])==false) { throw LoadError.dataAfterStopDelimiter(lineNumber+1, i+1); } } totalCharsSoFar = stopDelimiterPosition; } //totalCharsSoFar can become -1 in readNextToken if (totalCharsSoFar != -1) { returnStringArray[i] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else returnStringArray[i] = null; } //look for record separator for the last column's value //if I find endoffile and the it's only one column table, then it's a valid endoffile //case. Otherwise, it's an error case. Without the following check for the return value //of readNextToken, import was going into infinite loop for a table with single column //import. end-of-file was getting ignored without the following if. if (!readNextToken(recordSeparator, 0, recordSeparatorLength, true) ) { if (upperLimit == 0) return false; else throw LoadError.unexpectedEndOfFile(lineNumber+1); } //following is to take care of a case like "aa"aa This will result in an //error. Also a case like "aa" will truncate it to just aa. valid blank //chars are ' ' '\r' '\t' if (stopDelimiterPosition!=0 && (stopDelimiterPosition != totalCharsSoFar)) { for (int i=stopDelimiterPosition+1; i<totalCharsSoFar; i++) { // alc: should change || to && since || case is never true -- // currentChar can't be three different things at once. // alc: why no \n? BTW, \r and \n should be replaced // or amended with the first char of line.separator... //char currentChar = currentToken[i]; //if (currentChar != ' ' && currentChar != '\r' && currentChar != '\t') // use String.trim()'s definition of whitespace. // i18n - check for whitespace - avoid doing a hard coded character // check and use the isWhitespace method to cover all the Unicode // options if (Character.isWhitespace(currentToken[i])==false) { throw LoadError.dataAfterStopDelimiter(lineNumber+1, numberOfColumns); } } totalCharsSoFar = stopDelimiterPosition; } //to be able to read delimited files that have a delimeter at the end, //we have to reduce totalCharsSoFar by one when it is last column. //Otherwise last delimeter becomes part of the data. if (hasDelimiterAtEnd) { if (!(fieldStopDelimiterLength > 0)) { //if there is no field stop delimeter specified, //hopefully fieldStopDelimiterLength will not be >0 //there is weird behavior in the code that makes it read the last //delimeter as part of the last column data, so this forces us to //reduce number of read chars only if there is data stop delimeter //Only if it is the last column: //if (fieldStopDelimiter==null){ --totalCharsSoFar; //} } } - if (totalCharsSoFar != -1) { + if (totalCharsSoFar > -1) { /* This is a hack to fix a problem: When there is missing data in columns and hasDelimiterAtEnd==true, then the last delimiter was read as the last column data. Hopefully this will tackle that issue by skipping the last column which is in this case just the delimiter. We need to be careful about the case when the last column data itself is actually same as the delimiter. */ if (!hasDelimiterAtEnd) {//normal path: - returnStringArray[upperLimit] = new String(currentToken, + returnStringArray[upperLimit] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else if (totalCharsSoFar==fieldSeparatorLength && isFieldSep(currentToken) ){ //means hasDelimiterAtEnd==true and all of the above are true String currentStr = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); if (currentToken[totalCharsSoFar+1]==fieldStopDelimiter[0]){ returnStringArray[upperLimit] = currentStr; } else { returnStringArray[upperLimit] = null; } } else { //means hasDelimiterAtEnd==true and previous case is wrong. if (totalCharsSoFar>0) { returnStringArray[upperLimit] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else{ returnStringArray[upperLimit] = null; } } } else returnStringArray[upperLimit] = null; lineNumber++; return true; } //tells if a char array is field separator: private boolean isFieldSep(char[] chrArray){ for (int i=0; i<chrArray.length && i<fieldSeparatorLength; i++){ if (chrArray[i]!=fieldSeparator[i]) return false; } return true; } //read one column's value at a time boolean readNextToken(char[] delimiter, int delimiterIndex, int delimiterLength, boolean isRecordSeperator) throws Exception { int nextChar; fieldStopDelimiterIndex = 0; fieldStartDelimiterIndex = 0; totalCharsSoFar = 0; //at the start of every new token, make white space in front count 0 positionOfNonWhiteSpaceCharInFront = 0; stopDelimiterPosition = 0; foundStartAndStopDelimiters = false; foundStartDelimiter = false; int returnValue; while (true) { nextChar = bufferedReader.read(); if (nextChar == -1) //end of file return false; //read the character into the token holder. If token holder reaches it's capacity, //double it's capacity currentToken[totalCharsSoFar++] = (char)nextChar; //check if character read is white space char in front checkForWhiteSpaceInFront(); if (totalCharsSoFar == currentTokenMaxSize) { currentTokenMaxSize = currentTokenMaxSize * 2; char[] tempArray = new char[currentTokenMaxSize]; System.arraycopy(currentToken, 0, tempArray, 0, totalCharsSoFar); currentToken = tempArray; } returnValue = lookForPassedSeparator(delimiter, delimiterIndex, delimiterLength, nextChar, isRecordSeperator); if (returnValue == -1) { //if no stop delimiter found that "" this means null //also if no stop delimiter found then get rid of spaces around the token if (!foundStartAndStopDelimiters ) { if (totalCharsSoFar == 0) totalCharsSoFar = -1; else { //get the count of white spaces from back and subtract that and white spaces in //the front from the characters read so far so that we ignore spaces around the //token. checkForWhiteSpaceInBack(); totalCharsSoFar = totalCharsSoFar - positionOfNonWhiteSpaceCharInFront - positionOfNonWhiteSpaceCharInBack; } } return true; } delimiterIndex = returnValue; } } /* following are the routines that are used to read lob data stored * in a external import file for clob/blob columns, the reference * to external file is stored in the main import file. */ /** * Returns a clob columnn data stored at the specified location. * @param lobLocationStr location of the clob data. * @param colIndex number of the column. starts at 1. * @exception SQLException on any errors. */ String getClobColumnFromExtFileAsString(String lobLocationStr, int colIndex) throws SQLException { try { initExternalLobFile(lobLocationStr, colIndex); if (lobLength == -1 ){ // lob length -1 indicates columnn value is a NULL, // just return null. return null; } else { return lobFileHandles[colIndex-1].getString(lobOffset,lobLength); } }catch(Exception ex) { throw LoadError.unexpectedError(ex); } } /** * Returns a clob columnn data stored at the specified location as * a java.sql.Clob object. * @param lobLocationStr location of the clob data. * @param colIndex number of the column. starts at 1. * @exception SQLException on any errors. */ java.sql.Clob getClobColumnFromExtFile(String lobLocationStr, int colIndex) throws SQLException { try { initExternalLobFile(lobLocationStr, colIndex); if (lobLength == -1 ){ // lob length -1 indicates columnn value is a NULL, // just return null. return null; } else { return new ImportClob(lobFileHandles[colIndex -1], lobOffset,lobLength); } }catch(Exception ex) { throw LoadError.unexpectedError(ex); } } /** * Returns a blob columnn data stored at the specified location as * a java.sql.Blob object. * @param lobLocationStr location of the clob data. * @param colIndex number of the column. starts at 1. * @exception SQLException on any errors. */ java.sql.Blob getBlobColumnFromExtFile(String lobLocationStr, int colIndex) throws SQLException { initExternalLobFile(lobLocationStr, colIndex); if (lobLength == -1) { // lob length -1 indicates columnn value is a NULL, // just return null. return null; } else { return new ImportBlob(lobFileHandles[colIndex -1], lobOffset, lobLength); } } /** * Extract the file name, offset and length from the given lob * location and setup the file resources to read the data from * the file on first invocaton. * * @param lobLocationStr location of the clob data. * @param colIndex number of the column. starts at 1. * @exception SQLException on any errors. */ private void initExternalLobFile(String lobLocationStr, int colIndex) throws SQLException { // extract file name, offset, and the length from the // given lob location. Lob location string format is // <code > <fileName>.<lobOffset>.<size of lob>/ </code>. // For a NULL blob, size will be -1 int lengthIndex = lobLocationStr.lastIndexOf(".") ; int offsetIndex = lobLocationStr.lastIndexOf(".", lengthIndex -1); lobLength = Integer.parseInt(lobLocationStr.substring( lengthIndex + 1, lobLocationStr.length() -1)); lobOffset = Integer.parseInt(lobLocationStr.substring( offsetIndex+1, lengthIndex)); lobFileName = lobLocationStr.substring(0 , offsetIndex); if (lobFileHandles[colIndex-1] == null) { // open external file where the lobs are stored. try { // each lob column in the table has it's own file handle. // separate file handles are must, lob stream objects // can not be reused until the whole row is inserted. File lobsFile = new File (lobFileName); if (lobsFile.getParentFile() == null) { // lob file name is unqualified. lob file // is expected to be in the same location as // the import file. lobsFile = new File(( new File(inputFileName)).getParentFile(), lobFileName); } lobFileHandles[colIndex-1] = new ImportLobFile(lobsFile, controlFileReader.getDataCodeset()); }catch(Exception ex) { throw LoadError.unexpectedError(ex); } } } }
false
true
private boolean readNextDelimitedRow(String[] returnStringArray) throws Exception { int upperLimit = numberOfColumns-1; //reduce # field accesses //no data in the input file for some reason if (upperLimit < 0) return false; //look for number of columns - 1 field separators for (int i = 0; i<upperLimit; i++) { if (!readNextToken(fieldSeparator, 0, fieldSeparatorLength, false) ) { if (i == 0) // still on the first check return false; else throw LoadError.unexpectedEndOfFile(lineNumber+1); } //following is to take care of a case like "aa"aa This will result in an //error. Also a case like "aa" will truncate it to just aa. valid blank //chars are ' ' '\r' '\t' if (stopDelimiterPosition!=0 && ((stopDelimiterPosition) != totalCharsSoFar)) { for (int k=stopDelimiterPosition+1; k<totalCharsSoFar; k++) { // alc: should change || to && since || case is never true -- // currentChar can't be three different things at once. // alc: why no \n? BTW, \r and \n should be replaced // or amended with the first char of line.separator... //char currentChar = currentToken[k]; //if (currentChar != ' ' && currentChar != '\r' && currentChar != '\t') // use String.trim()'s definition of whitespace. // i18n - check for whitespace - avoid doing a hard coded // character check and use the isWhitespace method to cover all // the Unicode options if (Character.isWhitespace(currentToken[k])==false) { throw LoadError.dataAfterStopDelimiter(lineNumber+1, i+1); } } totalCharsSoFar = stopDelimiterPosition; } //totalCharsSoFar can become -1 in readNextToken if (totalCharsSoFar != -1) { returnStringArray[i] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else returnStringArray[i] = null; } //look for record separator for the last column's value //if I find endoffile and the it's only one column table, then it's a valid endoffile //case. Otherwise, it's an error case. Without the following check for the return value //of readNextToken, import was going into infinite loop for a table with single column //import. end-of-file was getting ignored without the following if. if (!readNextToken(recordSeparator, 0, recordSeparatorLength, true) ) { if (upperLimit == 0) return false; else throw LoadError.unexpectedEndOfFile(lineNumber+1); } //following is to take care of a case like "aa"aa This will result in an //error. Also a case like "aa" will truncate it to just aa. valid blank //chars are ' ' '\r' '\t' if (stopDelimiterPosition!=0 && (stopDelimiterPosition != totalCharsSoFar)) { for (int i=stopDelimiterPosition+1; i<totalCharsSoFar; i++) { // alc: should change || to && since || case is never true -- // currentChar can't be three different things at once. // alc: why no \n? BTW, \r and \n should be replaced // or amended with the first char of line.separator... //char currentChar = currentToken[i]; //if (currentChar != ' ' && currentChar != '\r' && currentChar != '\t') // use String.trim()'s definition of whitespace. // i18n - check for whitespace - avoid doing a hard coded character // check and use the isWhitespace method to cover all the Unicode // options if (Character.isWhitespace(currentToken[i])==false) { throw LoadError.dataAfterStopDelimiter(lineNumber+1, numberOfColumns); } } totalCharsSoFar = stopDelimiterPosition; } //to be able to read delimited files that have a delimeter at the end, //we have to reduce totalCharsSoFar by one when it is last column. //Otherwise last delimeter becomes part of the data. if (hasDelimiterAtEnd) { if (!(fieldStopDelimiterLength > 0)) { //if there is no field stop delimeter specified, //hopefully fieldStopDelimiterLength will not be >0 //there is weird behavior in the code that makes it read the last //delimeter as part of the last column data, so this forces us to //reduce number of read chars only if there is data stop delimeter //Only if it is the last column: //if (fieldStopDelimiter==null){ --totalCharsSoFar; //} } } if (totalCharsSoFar != -1) { /* This is a hack to fix a problem: When there is missing data in columns and hasDelimiterAtEnd==true, then the last delimiter was read as the last column data. Hopefully this will tackle that issue by skipping the last column which is in this case just the delimiter. We need to be careful about the case when the last column data itself is actually same as the delimiter. */ if (!hasDelimiterAtEnd) {//normal path: returnStringArray[upperLimit] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else if (totalCharsSoFar==fieldSeparatorLength && isFieldSep(currentToken) ){ //means hasDelimiterAtEnd==true and all of the above are true String currentStr = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); if (currentToken[totalCharsSoFar+1]==fieldStopDelimiter[0]){ returnStringArray[upperLimit] = currentStr; } else { returnStringArray[upperLimit] = null; } } else { //means hasDelimiterAtEnd==true and previous case is wrong. if (totalCharsSoFar>0) { returnStringArray[upperLimit] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else{ returnStringArray[upperLimit] = null; } } } else returnStringArray[upperLimit] = null; lineNumber++; return true; }
private boolean readNextDelimitedRow(String[] returnStringArray) throws Exception { int upperLimit = numberOfColumns-1; //reduce # field accesses //no data in the input file for some reason if (upperLimit < 0) return false; //look for number of columns - 1 field separators for (int i = 0; i<upperLimit; i++) { if (!readNextToken(fieldSeparator, 0, fieldSeparatorLength, false) ) { if (i == 0) // still on the first check return false; else throw LoadError.unexpectedEndOfFile(lineNumber+1); } //following is to take care of a case like "aa"aa This will result in an //error. Also a case like "aa" will truncate it to just aa. valid blank //chars are ' ' '\r' '\t' if (stopDelimiterPosition!=0 && ((stopDelimiterPosition) != totalCharsSoFar)) { for (int k=stopDelimiterPosition+1; k<totalCharsSoFar; k++) { // alc: should change || to && since || case is never true -- // currentChar can't be three different things at once. // alc: why no \n? BTW, \r and \n should be replaced // or amended with the first char of line.separator... //char currentChar = currentToken[k]; //if (currentChar != ' ' && currentChar != '\r' && currentChar != '\t') // use String.trim()'s definition of whitespace. // i18n - check for whitespace - avoid doing a hard coded // character check and use the isWhitespace method to cover all // the Unicode options if (Character.isWhitespace(currentToken[k])==false) { throw LoadError.dataAfterStopDelimiter(lineNumber+1, i+1); } } totalCharsSoFar = stopDelimiterPosition; } //totalCharsSoFar can become -1 in readNextToken if (totalCharsSoFar != -1) { returnStringArray[i] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else returnStringArray[i] = null; } //look for record separator for the last column's value //if I find endoffile and the it's only one column table, then it's a valid endoffile //case. Otherwise, it's an error case. Without the following check for the return value //of readNextToken, import was going into infinite loop for a table with single column //import. end-of-file was getting ignored without the following if. if (!readNextToken(recordSeparator, 0, recordSeparatorLength, true) ) { if (upperLimit == 0) return false; else throw LoadError.unexpectedEndOfFile(lineNumber+1); } //following is to take care of a case like "aa"aa This will result in an //error. Also a case like "aa" will truncate it to just aa. valid blank //chars are ' ' '\r' '\t' if (stopDelimiterPosition!=0 && (stopDelimiterPosition != totalCharsSoFar)) { for (int i=stopDelimiterPosition+1; i<totalCharsSoFar; i++) { // alc: should change || to && since || case is never true -- // currentChar can't be three different things at once. // alc: why no \n? BTW, \r and \n should be replaced // or amended with the first char of line.separator... //char currentChar = currentToken[i]; //if (currentChar != ' ' && currentChar != '\r' && currentChar != '\t') // use String.trim()'s definition of whitespace. // i18n - check for whitespace - avoid doing a hard coded character // check and use the isWhitespace method to cover all the Unicode // options if (Character.isWhitespace(currentToken[i])==false) { throw LoadError.dataAfterStopDelimiter(lineNumber+1, numberOfColumns); } } totalCharsSoFar = stopDelimiterPosition; } //to be able to read delimited files that have a delimeter at the end, //we have to reduce totalCharsSoFar by one when it is last column. //Otherwise last delimeter becomes part of the data. if (hasDelimiterAtEnd) { if (!(fieldStopDelimiterLength > 0)) { //if there is no field stop delimeter specified, //hopefully fieldStopDelimiterLength will not be >0 //there is weird behavior in the code that makes it read the last //delimeter as part of the last column data, so this forces us to //reduce number of read chars only if there is data stop delimeter //Only if it is the last column: //if (fieldStopDelimiter==null){ --totalCharsSoFar; //} } } if (totalCharsSoFar > -1) { /* This is a hack to fix a problem: When there is missing data in columns and hasDelimiterAtEnd==true, then the last delimiter was read as the last column data. Hopefully this will tackle that issue by skipping the last column which is in this case just the delimiter. We need to be careful about the case when the last column data itself is actually same as the delimiter. */ if (!hasDelimiterAtEnd) {//normal path: returnStringArray[upperLimit] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else if (totalCharsSoFar==fieldSeparatorLength && isFieldSep(currentToken) ){ //means hasDelimiterAtEnd==true and all of the above are true String currentStr = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); if (currentToken[totalCharsSoFar+1]==fieldStopDelimiter[0]){ returnStringArray[upperLimit] = currentStr; } else { returnStringArray[upperLimit] = null; } } else { //means hasDelimiterAtEnd==true and previous case is wrong. if (totalCharsSoFar>0) { returnStringArray[upperLimit] = new String(currentToken, positionOfNonWhiteSpaceCharInFront, totalCharsSoFar); } else{ returnStringArray[upperLimit] = null; } } } else returnStringArray[upperLimit] = null; lineNumber++; return true; }
diff --git a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/ThreadManager.java b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/ThreadManager.java index 4da685ba8..2a085d711 100644 --- a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/ThreadManager.java +++ b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/ThreadManager.java @@ -1,272 +1,272 @@ /* * Copyright (c) 2002-2008 Gargoyle Software 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 com.gargoylesoftware.htmlunit; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory; import com.gargoylesoftware.htmlunit.javascript.host.Window; /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * * This is a class that provides thread handling services to internal clients * as well as exposes some of the status of these threads to the public API. * * @version $Revision$ * @author Brad Clarke * @author Marc Guillemot * @author Daniel Gredler */ public class ThreadManager { /** Logging support. */ private static final Log LOG = LogFactory.getLog(ThreadManager.class); /** Map of threads, keyed on thread ID. Use a tree map for deterministic iteration. */ private Map<Integer, Thread> threadMap_ = Collections.synchronizedMap(new TreeMap<Integer, Thread>()); private final WebWindow window_; ThreadManager(final WebWindow window) { window_ = window; } /** * @return the number of tracked threads */ public int activeCount() { return threadMap_.size(); } /** * Threads are given numeric IDs in JavaScript and that number is * stored here. */ private int nextThreadID_ = 1; /** * HtmlUnit threads are started at a higher priority than the priority * of the first thread to ask for HtmlUnit thread handling services. Assuming * there are no users screwing with their own thread priority after starting * a test this should be enough to encourage background threads to execute * quicker than the test they were started from, if possible. */ private static final int PRIORITY = Math.min(Thread.MAX_PRIORITY, Thread .currentThread() .getPriority() + 1); /** * Gets the next thread ID in a threadsafe way. * @return the next ID */ private synchronized int getNextThreadId() { return nextThreadID_++; } /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * * Starts a new job on a background thread. Threads started by this method * are always considered daemon threads and will not prevent the JVM from * shutting down. For our purposes the JUnit test is the only thread that * matters and the background threads are just there to keep the HtmlUnit * objects as up to date as possible. * * @param job the job to start * @param label a job description * @return the ID of the new thread, suitable for use in JavaScript and required * when calling {@link #stopThread(int)} */ public int startThread(final Runnable job, final String label) { final int myThreadID = getNextThreadId(); final Thread newThread = new Thread(job, "HtmlUnit Managed Thread #" + myThreadID + ": " + label) { @Override public void run() { - HtmlUnitContextFactory.putThreadLocal(window_.getWebClient().getBrowserVersion()); + HtmlUnitContextFactory.putThreadLocal(window_.getWebClient().getBrowserVersion()); try { super.run(); } finally { threadMap_.remove(new Integer(myThreadID)); } } }; newThread.setPriority(PRIORITY); newThread.setDaemon(true); threadMap_.put(new Integer(myThreadID), newThread); newThread.start(); return myThreadID; } /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * * Stops a thread that was started in this thread manager. * * Note: this does not immediately stop the thread, only interrupt * it and remove it from being tracked by this manager. The thread * is responsible for handling being interrupted properly and shutting * itself down. * * @param threadID the ID of the thread to stop */ public void stopThread(final int threadID) { final Thread thread = threadMap_.get(new Integer(threadID)); if (thread != null) { thread.interrupt(); } } /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * * Removes the job with the given id for schedule. * @param id the ID of the job to remove */ // this should totally replace stopThread in the future public void removeJob(final int id) { stopThread(id); } /** * Wait for any executing background threads to complete. * * @param maxWaitMillis the maximum time that should be waited, in milliseconds * This is not an exact time but will be fairly close. * @return true if all threads expired in the specified time */ public boolean joinAll(long maxWaitMillis) { for (Thread t = getNextThread(); t != null && maxWaitMillis > 0; t = getNextThread()) { final long before = System.currentTimeMillis(); try { LOG.debug("Trying to join: " + t); t.join(maxWaitMillis); } catch (final InterruptedException e) { throw new RuntimeException("Thread " + t + " interrupted.", e); } maxWaitMillis = maxWaitMillis - (System.currentTimeMillis() - before); } return threadMap_.size() == 0; } /** * Gets the next thread in the thread map in a threadsafe way. This method returns <tt>null</tt> * if there are no more threads in the thread map. * * @return the next thread in the thread map */ private Thread getNextThread() { final Thread thread; synchronized (threadMap_) { final Iterator<Thread> i = threadMap_.values().iterator(); if (i.hasNext()) { thread = i.next(); } else { thread = null; } } return thread; } /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * Attempts to stop running threads. */ public void interruptAll() { synchronized (threadMap_) { for (final Integer id : new HashSet<Integer>(threadMap_.keySet())) { stopThread(id.intValue()); } } } /** * {@inheritDoc} */ @Override public String toString() { return "ThreadManager: " + threadMap_; } /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * * Registers a JavaScript code to be executed at the given time. * @param codeToExec the string or function to execute * @param timeout the time to wait before to executed the code * @param description the job description * @return the ID of the registered job, suitable for use in JavaScript and required * when calling {@link #removeJob(int)} */ public int registerJob(final Object codeToExec, final int timeout, final String description) { final JavaScriptBackgroundJob job = createJavaScriptBackgroundJob(codeToExec, timeout, false, description); return startThread(job, description); } /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * * Registers a JavaScript code to be executed at the given intervals. * @param codeToExec the string or function to execute * @param interval the time to wait between two executions * @param description the job description * @return the ID of the registered job, suitable for use in JavaScript and required * when calling {@link #removeJob(int)} */ public int registerRecurringJob(final Object codeToExec, final int interval, final String description) { final JavaScriptBackgroundJob job = createJavaScriptBackgroundJob(codeToExec, interval, true, description); return startThread(job, description); } /** * Makes the job object for setTimeout and setInterval * * @param codeToExec either a Function or a String of the JavaScript code * @param timeout time to wait * @param thisWindow the window to associate the thread with * @param loopForever if the thread should keep looping (setTimeout vs setInterval) * @return the job */ private JavaScriptBackgroundJob createJavaScriptBackgroundJob(final Object codeToExec, final int timeout, final boolean loopForever, final String label) { final Window thisWindow = (Window) window_.getScriptObject(); if (codeToExec == null) { throw Context.reportRuntimeError("Function not provided"); } else if (codeToExec instanceof String) { final String scriptString = (String) codeToExec; return new JavaScriptBackgroundJob(thisWindow, timeout, scriptString, loopForever, label); } else if (codeToExec instanceof Function) { final Function scriptFunction = (Function) codeToExec; return new JavaScriptBackgroundJob(thisWindow, timeout, scriptFunction, loopForever, label); } else { throw Context.reportRuntimeError("Unknown type for function"); } } }
true
true
public int startThread(final Runnable job, final String label) { final int myThreadID = getNextThreadId(); final Thread newThread = new Thread(job, "HtmlUnit Managed Thread #" + myThreadID + ": " + label) { @Override public void run() { HtmlUnitContextFactory.putThreadLocal(window_.getWebClient().getBrowserVersion()); try { super.run(); } finally { threadMap_.remove(new Integer(myThreadID)); } } }; newThread.setPriority(PRIORITY); newThread.setDaemon(true); threadMap_.put(new Integer(myThreadID), newThread); newThread.start(); return myThreadID; }
public int startThread(final Runnable job, final String label) { final int myThreadID = getNextThreadId(); final Thread newThread = new Thread(job, "HtmlUnit Managed Thread #" + myThreadID + ": " + label) { @Override public void run() { HtmlUnitContextFactory.putThreadLocal(window_.getWebClient().getBrowserVersion()); try { super.run(); } finally { threadMap_.remove(new Integer(myThreadID)); } } }; newThread.setPriority(PRIORITY); newThread.setDaemon(true); threadMap_.put(new Integer(myThreadID), newThread); newThread.start(); return myThreadID; }
diff --git a/src/prop/hex/presentacio/JPanelTauler.java b/src/prop/hex/presentacio/JPanelTauler.java index a59f905..34b2568 100644 --- a/src/prop/hex/presentacio/JPanelTauler.java +++ b/src/prop/hex/presentacio/JPanelTauler.java @@ -1,405 +1,405 @@ package prop.hex.presentacio; import prop.cluster.domini.models.estats.EstatCasella; import prop.cluster.domini.models.estats.EstatPartida; import prop.hex.domini.models.Casella; import prop.hex.domini.models.enums.CombinacionsColors; import prop.hex.domini.models.enums.TipusJugadors; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public final class JPanelTauler extends JPanel { private static PresentacioCtrl presentacio_ctrl; private Object[] elements_de_control_partida; private Object[][] elements_de_control_jugadors; private Casella ultima_pista; private boolean pista_valida; /** * Poligon que s'utilitza per dibuixar a pantalla. */ private Polygon hexagon; /** * dx i dy són els increments horitzontals i verticals entre caselles. */ private int dx, dy; /** * Radi de les caselles. */ private double radi = 40.0; /** * Posició inicial del taulell a la pantalla. */ private int iniciX = 90; private int iniciY = 80; private boolean partida_en_curs; private boolean partida_ia; /** * Constructora, obté el taulell i els jugadors, construeix un poligon hexagonal i * afegeix el listener del ratoli pel cas del click. */ public JPanelTauler( boolean partida_en_curs, PresentacioCtrl presentacio_ctrl ) { this.presentacio_ctrl = presentacio_ctrl; elements_de_control_partida = presentacio_ctrl.getElementsDeControlPartida(); elements_de_control_jugadors = presentacio_ctrl.getElementsDeControlJugadors(); ultima_pista = new Casella( 0, 0 ); pista_valida = false; this.partida_en_curs = partida_en_curs; partida_ia = ( ( TipusJugadors ) elements_de_control_jugadors[0][0] ) != TipusJugadors.JUGADOR && ( ( TipusJugadors ) elements_de_control_jugadors[0][0] ) != TipusJugadors.CONVIDAT && ( ( TipusJugadors ) elements_de_control_jugadors[0][1] ) != TipusJugadors.JUGADOR && ( ( TipusJugadors ) elements_de_control_jugadors[0][1] ) != TipusJugadors.CONVIDAT; //Creem l'hexàgon que dibuixarem després. int x[] = new int[6]; int y[] = new int[6]; for ( int i = 0; i < 6; i++ ) { x[i] = ( int ) ( radi * Math.sin( ( double ) i * Math.PI / 3.0 ) ); y[i] = ( int ) ( radi * Math.cos( ( double ) i * Math.PI / 3.0 ) ); } hexagon = new Polygon( x, y, 6 ); dx = ( int ) ( 2 * radi * Math.sin( Math.PI / 3.0 ) ); dy = ( int ) ( 1.5 * radi ); // Afegim el listener del ratoli. addMouseListener( new MouseAdapter() { @Override public void mouseClicked( MouseEvent mouseEvent ) { comprovaClick( mouseEvent.getX(), mouseEvent.getY() ); } } ); } /** * Calcula sobre quina casella es corresponen les coordenades píxel i crida a clickHexagon amb aquesta * informació. Listener de mouseClicked. Si s'ha fet click sobre una casella crida a clickHexagon, * si s'ha fet click sobre el botó de moviment IA, crida a mouIA * * @param x Coordenades píxel horitxontals. * @param y Coordenades píxel verticals. */ private void comprovaClick( int x, int y ) { int rx = iniciX; int ry = iniciY; elements_de_control_partida = presentacio_ctrl.getElementsDeControlPartida(); elements_de_control_jugadors = presentacio_ctrl.getElementsDeControlJugadors(); if ( partida_en_curs && ( ( (Integer) elements_de_control_partida[2] % 2 == 0 && ( x < 170 && x > -50 && y < 480 && y > 360 ) ) || ( (Integer) elements_de_control_partida[2] % 2 != 0 && ( x < 800 && x > 580 && y < 270 && y > 150 ) ) ) ) { mouIAOMostraPista(); } else { for ( int i = 0; i < (Integer) elements_de_control_partida[1]; i++ ) { rx += i * dx / 2; ry += i * dy; for ( int j = 0; j < (Integer) elements_de_control_partida[1]; j++ ) { rx += j * dx; if ( hexagon.contains( x - rx, y - ry ) ) { clickHexagon( i, j ); } rx -= j * dx; } rx -= i * dx / 2; ry -= i * dy; } } } /** * Si la partida no està finalitzada i es torn de una IA, crida PartidaCtrl a executar moviment IA. * Torna a pintar l'escena. */ private void mouIAOMostraPista() { if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA && !presentacio_ctrl.esTornHuma () ) { presentacio_ctrl.executaMovimentIA(); } else if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA && presentacio_ctrl .esTornHuma() ) { ultima_pista = presentacio_ctrl.obtePista(); pista_valida = true; } repaint(); } /** * Si la partida no està finalitzada i es torn d'un huma, crida a fer moviment a la casella i, j. * Torna a pintar l'escena. * * @param i fila casella. * @param j columna casella. */ private void clickHexagon( int i, int j ) { if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA && ( presentacio_ctrl.esTornHuma() || !partida_en_curs ) ) { try { //No ens cal comprovar si el moviment es fa o no (si retorna true o false). presentacio_ctrl.mouFitxa( i, j ); pista_valida = false; paintImmediately( 0, 0, 800, 500 ); // De moment sembla que falla, ja ho mirarem. if ( partida_en_curs && !presentacio_ctrl.esTornHuma() ) { mouIAOMostraPista(); } } catch ( UnsupportedOperationException exepcio ) { System.out.println( "Moviment no vàlid, partida finalitzada: " + exepcio.getMessage() ); } } repaint(); } /** * Retorna la mida de la pantalla. * * @return */ public Dimension getPreferredSize() { return new Dimension( 800, 500 ); } /** * Pinta la pantalla. * * @param g Paràmetre Graphics on es pinta. */ protected void paintComponent( Graphics g ) { super.paintComponent( g ); elements_de_control_partida = presentacio_ctrl.getElementsDeControlPartida(); elements_de_control_jugadors = presentacio_ctrl.getElementsDeControlJugadors(); //Dibuixem el tauler, pintant cada hexagon del color que toca. g.translate( iniciX, iniciY ); for ( int i = 0; i < (Integer) elements_de_control_partida[1]; i++ ) { g.translate( i * dx / 2, i * dy ); for ( int j = 0; j < (Integer) elements_de_control_partida[1]; j++ ) { g.translate( j * dx, 0 ); if ( i == (Integer) elements_de_control_partida[1] / 2 && j == (Integer) elements_de_control_partida[1] / 2 && (Integer) elements_de_control_partida[2] == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorCasellesInhabilitades() ); } else { if ( pista_valida && ( ultima_pista.getFila() == i && ultima_pista.getColumna() == j ) ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorCasellesPista() ); ultima_pista.setColumna( 0 ); ultima_pista.setFila( 0 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( presentacio_ctrl.getEstatCasella( i, j ) ) ); } } g.fillPolygon( hexagon ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorVoraCaselles() ); g.drawPolygon( hexagon ); g.translate( -j * dx, 0 ); } g.translate( -i * dx / 2, -i * dy ); } // Si és torn de la IA mostrem el botó Mou IA, només si a la partida només juga la IA. if ( partida_en_curs && ( partida_ia || (Integer) elements_de_control_partida[2] == 0 || presentacio_ctrl.esPartidaAmbSituacioInicialAcabadaDeDefinir()) && !presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.fillRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextMouFitxaIA( EstatCasella.JUGADOR_A ) ); g.drawString( "Mou IA", -10, 385 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.fillRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextMouFitxaIA( EstatCasella.JUGADOR_B ) ); g.drawString( "Mou IA", 620, 175 ); } } // Si és torn de la IA i a la partida juga algun humà, if ( partida_en_curs && !partida_ia && !presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.drawString( "Pensant moviment...", -50, 370 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.drawString( "Pensant moviment...", 580, 160 ); } } // Si és torn d'un humà i té pistes per utilitzar mostrem el botó Demana Pista if ( partida_en_curs && !pista_valida && presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { if ( ( ( Integer ) elements_de_control_jugadors[1][0] ) < (Integer) elements_de_control_partida[0] ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.fillRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorTextMouFitxaIA( EstatCasella.JUGADOR_A ) ); g.drawString( "Demana pista", -30, 385 ); } } else { // Com ho fem per carregar el valor màxim de pistes, que està a una classe del domini? if ( ( ( Integer ) elements_de_control_jugadors[1][1] ) < (Integer) elements_de_control_partida[0] ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.fillRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorTextMouFitxaIA( EstatCasella.JUGADOR_B ) ); g.drawString( "Demana pista", 600, 175 ); } } } //Mostrem el torn actual. g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.BUIDA ) ); g.drawString( "Torn: " + elements_de_control_partida[2], -50, 210 ); g.drawString( "Torn: " + elements_de_control_partida[2], 580, 0 ); //Mostrem algunes dades pel jugador A g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.JUGADOR_A ) ); if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.drawString( "Té el torn", -50, 270 ); } g.drawString( ( ( String ) elements_de_control_jugadors[3][0] ), -50, 290 ); g.drawString( "D'esquerra a dreta", -50, 310 ); g.drawString( "Temps: " + ( String ) elements_de_control_jugadors[2][0], -50, 330 ); g.drawString( "Pistes disponibles: " + ( (Integer) elements_de_control_partida[0] - ( ( Integer ) elements_de_control_jugadors[1][0] ) ), -50, 350 ); //I algunes dades pel jugador B g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.JUGADOR_B ) ); if ( (Integer) elements_de_control_partida[2] % 2 == 1 ) { g.drawString( "Té el torn", 580, 60 ); } g.drawString( ( ( String ) elements_de_control_jugadors[3][1] ), 580, 80 ); g.drawString( "De dalt a baix", 580, 100 ); g.drawString( "Temps: " + ( String ) elements_de_control_jugadors[2][1], 580, 120 ); g.drawString( "Pistes disponibles: " + ( (Integer) elements_de_control_partida[0] - ( ( Integer ) elements_de_control_jugadors[1][1] ) ), 580, 140 ); if ( ( ( CombinacionsColors ) elements_de_control_partida[3] ) == CombinacionsColors.VERMELL_BLAU ) { g.drawImage( ( new ImageIcon( "img/tauler_vb.png" ) ).getImage(), -iniciX, -iniciY, getWidth(), getHeight(), null ); } else { g.drawImage( ( new ImageIcon( "img/tauler_nb.png" ) ).getImage(), -iniciX, -iniciY, getWidth(), getHeight(), null ); } //Si ha guanyat un jugador, mostrem el resultat. if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.GUANYA_JUGADOR_A ) { g.setColor( new Color( 0x66CCFF ) ); g.fillRoundRect( 150, 0, 300, 200, 16, 16 ); g.setColor( Color.black ); g.drawRoundRect( 150, 0, 300, 200, 16, 16 ); g.drawString( "Partida finalitzada.", 160, 30 ); g.drawString( "Guanya " + ( ( String ) elements_de_control_jugadors[3][0] ), 160, 50 ); - g.drawString( "amb un temps de " + ( ( Long ) elements_de_control_jugadors[2][0] )/1000 + " s,", 160, 70 ); + g.drawString( "amb un temps de " + ( String ) elements_de_control_jugadors[2][0] + ",", 160, 70 ); g.drawString( "col·locant un total de " + ( ( Integer ) elements_de_control_jugadors[4][0] ) + " fitxes,", 160, 90 ); g.drawString( "i utilitzant " + ( ( Integer ) elements_de_control_jugadors[1][0] ) + " pistes.", 160, 110 ); g.drawString( "Per a continuar, pitja el botó Abandona partida.", 160, 150); } else if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.GUANYA_JUGADOR_B ) { g.setColor( new Color( 0x66CCFF ) ); g.fillRoundRect( 150, 0, 300, 200, 16, 16 ); g.setColor( Color.black ); g.drawRoundRect( 150, 0, 300, 200, 16, 16 ); g.drawString( "Partida finalitzada.", 160, 30 ); g.drawString( "Guanya " + ( ( String ) elements_de_control_jugadors[3][1] ), 160, 50 ); - g.drawString( "amb un temps de " + ( ( Long ) elements_de_control_jugadors[2][1] )/1000 + " s,", 160, 70 ); + g.drawString( "amb un temps de " + ( String ) elements_de_control_jugadors[2][1] + ",", 160, 70 ); g.drawString( "col·locant un total de " + ( ( Integer ) elements_de_control_jugadors[4][1] ) + " fitxes,", 160, 90 ); g.drawString( "i utilitzant " + ( ( Integer ) elements_de_control_jugadors[1][1] ) + " pistes.", 160, 110 ); g.drawString( "Per a continuar, pitja el botó Abandona partida.", 160, 150); } } }
false
true
protected void paintComponent( Graphics g ) { super.paintComponent( g ); elements_de_control_partida = presentacio_ctrl.getElementsDeControlPartida(); elements_de_control_jugadors = presentacio_ctrl.getElementsDeControlJugadors(); //Dibuixem el tauler, pintant cada hexagon del color que toca. g.translate( iniciX, iniciY ); for ( int i = 0; i < (Integer) elements_de_control_partida[1]; i++ ) { g.translate( i * dx / 2, i * dy ); for ( int j = 0; j < (Integer) elements_de_control_partida[1]; j++ ) { g.translate( j * dx, 0 ); if ( i == (Integer) elements_de_control_partida[1] / 2 && j == (Integer) elements_de_control_partida[1] / 2 && (Integer) elements_de_control_partida[2] == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorCasellesInhabilitades() ); } else { if ( pista_valida && ( ultima_pista.getFila() == i && ultima_pista.getColumna() == j ) ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorCasellesPista() ); ultima_pista.setColumna( 0 ); ultima_pista.setFila( 0 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( presentacio_ctrl.getEstatCasella( i, j ) ) ); } } g.fillPolygon( hexagon ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorVoraCaselles() ); g.drawPolygon( hexagon ); g.translate( -j * dx, 0 ); } g.translate( -i * dx / 2, -i * dy ); } // Si és torn de la IA mostrem el botó Mou IA, només si a la partida només juga la IA. if ( partida_en_curs && ( partida_ia || (Integer) elements_de_control_partida[2] == 0 || presentacio_ctrl.esPartidaAmbSituacioInicialAcabadaDeDefinir()) && !presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.fillRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextMouFitxaIA( EstatCasella.JUGADOR_A ) ); g.drawString( "Mou IA", -10, 385 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.fillRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextMouFitxaIA( EstatCasella.JUGADOR_B ) ); g.drawString( "Mou IA", 620, 175 ); } } // Si és torn de la IA i a la partida juga algun humà, if ( partida_en_curs && !partida_ia && !presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.drawString( "Pensant moviment...", -50, 370 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.drawString( "Pensant moviment...", 580, 160 ); } } // Si és torn d'un humà i té pistes per utilitzar mostrem el botó Demana Pista if ( partida_en_curs && !pista_valida && presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { if ( ( ( Integer ) elements_de_control_jugadors[1][0] ) < (Integer) elements_de_control_partida[0] ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.fillRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorTextMouFitxaIA( EstatCasella.JUGADOR_A ) ); g.drawString( "Demana pista", -30, 385 ); } } else { // Com ho fem per carregar el valor màxim de pistes, que està a una classe del domini? if ( ( ( Integer ) elements_de_control_jugadors[1][1] ) < (Integer) elements_de_control_partida[0] ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.fillRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorTextMouFitxaIA( EstatCasella.JUGADOR_B ) ); g.drawString( "Demana pista", 600, 175 ); } } } //Mostrem el torn actual. g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.BUIDA ) ); g.drawString( "Torn: " + elements_de_control_partida[2], -50, 210 ); g.drawString( "Torn: " + elements_de_control_partida[2], 580, 0 ); //Mostrem algunes dades pel jugador A g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.JUGADOR_A ) ); if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.drawString( "Té el torn", -50, 270 ); } g.drawString( ( ( String ) elements_de_control_jugadors[3][0] ), -50, 290 ); g.drawString( "D'esquerra a dreta", -50, 310 ); g.drawString( "Temps: " + ( String ) elements_de_control_jugadors[2][0], -50, 330 ); g.drawString( "Pistes disponibles: " + ( (Integer) elements_de_control_partida[0] - ( ( Integer ) elements_de_control_jugadors[1][0] ) ), -50, 350 ); //I algunes dades pel jugador B g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.JUGADOR_B ) ); if ( (Integer) elements_de_control_partida[2] % 2 == 1 ) { g.drawString( "Té el torn", 580, 60 ); } g.drawString( ( ( String ) elements_de_control_jugadors[3][1] ), 580, 80 ); g.drawString( "De dalt a baix", 580, 100 ); g.drawString( "Temps: " + ( String ) elements_de_control_jugadors[2][1], 580, 120 ); g.drawString( "Pistes disponibles: " + ( (Integer) elements_de_control_partida[0] - ( ( Integer ) elements_de_control_jugadors[1][1] ) ), 580, 140 ); if ( ( ( CombinacionsColors ) elements_de_control_partida[3] ) == CombinacionsColors.VERMELL_BLAU ) { g.drawImage( ( new ImageIcon( "img/tauler_vb.png" ) ).getImage(), -iniciX, -iniciY, getWidth(), getHeight(), null ); } else { g.drawImage( ( new ImageIcon( "img/tauler_nb.png" ) ).getImage(), -iniciX, -iniciY, getWidth(), getHeight(), null ); } //Si ha guanyat un jugador, mostrem el resultat. if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.GUANYA_JUGADOR_A ) { g.setColor( new Color( 0x66CCFF ) ); g.fillRoundRect( 150, 0, 300, 200, 16, 16 ); g.setColor( Color.black ); g.drawRoundRect( 150, 0, 300, 200, 16, 16 ); g.drawString( "Partida finalitzada.", 160, 30 ); g.drawString( "Guanya " + ( ( String ) elements_de_control_jugadors[3][0] ), 160, 50 ); g.drawString( "amb un temps de " + ( ( Long ) elements_de_control_jugadors[2][0] )/1000 + " s,", 160, 70 ); g.drawString( "col·locant un total de " + ( ( Integer ) elements_de_control_jugadors[4][0] ) + " fitxes,", 160, 90 ); g.drawString( "i utilitzant " + ( ( Integer ) elements_de_control_jugadors[1][0] ) + " pistes.", 160, 110 ); g.drawString( "Per a continuar, pitja el botó Abandona partida.", 160, 150); } else if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.GUANYA_JUGADOR_B ) { g.setColor( new Color( 0x66CCFF ) ); g.fillRoundRect( 150, 0, 300, 200, 16, 16 ); g.setColor( Color.black ); g.drawRoundRect( 150, 0, 300, 200, 16, 16 ); g.drawString( "Partida finalitzada.", 160, 30 ); g.drawString( "Guanya " + ( ( String ) elements_de_control_jugadors[3][1] ), 160, 50 ); g.drawString( "amb un temps de " + ( ( Long ) elements_de_control_jugadors[2][1] )/1000 + " s,", 160, 70 ); g.drawString( "col·locant un total de " + ( ( Integer ) elements_de_control_jugadors[4][1] ) + " fitxes,", 160, 90 ); g.drawString( "i utilitzant " + ( ( Integer ) elements_de_control_jugadors[1][1] ) + " pistes.", 160, 110 ); g.drawString( "Per a continuar, pitja el botó Abandona partida.", 160, 150); } }
protected void paintComponent( Graphics g ) { super.paintComponent( g ); elements_de_control_partida = presentacio_ctrl.getElementsDeControlPartida(); elements_de_control_jugadors = presentacio_ctrl.getElementsDeControlJugadors(); //Dibuixem el tauler, pintant cada hexagon del color que toca. g.translate( iniciX, iniciY ); for ( int i = 0; i < (Integer) elements_de_control_partida[1]; i++ ) { g.translate( i * dx / 2, i * dy ); for ( int j = 0; j < (Integer) elements_de_control_partida[1]; j++ ) { g.translate( j * dx, 0 ); if ( i == (Integer) elements_de_control_partida[1] / 2 && j == (Integer) elements_de_control_partida[1] / 2 && (Integer) elements_de_control_partida[2] == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorCasellesInhabilitades() ); } else { if ( pista_valida && ( ultima_pista.getFila() == i && ultima_pista.getColumna() == j ) ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorCasellesPista() ); ultima_pista.setColumna( 0 ); ultima_pista.setFila( 0 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( presentacio_ctrl.getEstatCasella( i, j ) ) ); } } g.fillPolygon( hexagon ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorVoraCaselles() ); g.drawPolygon( hexagon ); g.translate( -j * dx, 0 ); } g.translate( -i * dx / 2, -i * dy ); } // Si és torn de la IA mostrem el botó Mou IA, només si a la partida només juga la IA. if ( partida_en_curs && ( partida_ia || (Integer) elements_de_control_partida[2] == 0 || presentacio_ctrl.esPartidaAmbSituacioInicialAcabadaDeDefinir()) && !presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.fillRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextMouFitxaIA( EstatCasella.JUGADOR_A ) ); g.drawString( "Mou IA", -10, 385 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.fillRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextMouFitxaIA( EstatCasella.JUGADOR_B ) ); g.drawString( "Mou IA", 620, 175 ); } } // Si és torn de la IA i a la partida juga algun humà, if ( partida_en_curs && !partida_ia && !presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.drawString( "Pensant moviment...", -50, 370 ); } else { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.drawString( "Pensant moviment...", 580, 160 ); } } // Si és torn d'un humà i té pistes per utilitzar mostrem el botó Demana Pista if ( partida_en_curs && !pista_valida && presentacio_ctrl.esTornHuma() && presentacio_ctrl.consultaEstatPartida() == EstatPartida.NO_FINALITZADA ) { if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { if ( ( ( Integer ) elements_de_control_jugadors[1][0] ) < (Integer) elements_de_control_partida[0] ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_A ) ); g.fillRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( -50, 360, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorTextMouFitxaIA( EstatCasella.JUGADOR_A ) ); g.drawString( "Demana pista", -30, 385 ); } } else { // Com ho fem per carregar el valor màxim de pistes, que està a una classe del domini? if ( ( ( Integer ) elements_de_control_jugadors[1][1] ) < (Integer) elements_de_control_partida[0] ) { g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorCasella( EstatCasella.JUGADOR_B ) ); g.fillRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( Color.black ); g.drawRoundRect( 580, 150, 120, 40, 8, 8 ); g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ) .getColorTextMouFitxaIA( EstatCasella.JUGADOR_B ) ); g.drawString( "Demana pista", 600, 175 ); } } } //Mostrem el torn actual. g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.BUIDA ) ); g.drawString( "Torn: " + elements_de_control_partida[2], -50, 210 ); g.drawString( "Torn: " + elements_de_control_partida[2], 580, 0 ); //Mostrem algunes dades pel jugador A g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.JUGADOR_A ) ); if ( (Integer) elements_de_control_partida[2] % 2 == 0 ) { g.drawString( "Té el torn", -50, 270 ); } g.drawString( ( ( String ) elements_de_control_jugadors[3][0] ), -50, 290 ); g.drawString( "D'esquerra a dreta", -50, 310 ); g.drawString( "Temps: " + ( String ) elements_de_control_jugadors[2][0], -50, 330 ); g.drawString( "Pistes disponibles: " + ( (Integer) elements_de_control_partida[0] - ( ( Integer ) elements_de_control_jugadors[1][0] ) ), -50, 350 ); //I algunes dades pel jugador B g.setColor( ( ( CombinacionsColors ) elements_de_control_partida[3] ).getColorTextInformacio( EstatCasella.JUGADOR_B ) ); if ( (Integer) elements_de_control_partida[2] % 2 == 1 ) { g.drawString( "Té el torn", 580, 60 ); } g.drawString( ( ( String ) elements_de_control_jugadors[3][1] ), 580, 80 ); g.drawString( "De dalt a baix", 580, 100 ); g.drawString( "Temps: " + ( String ) elements_de_control_jugadors[2][1], 580, 120 ); g.drawString( "Pistes disponibles: " + ( (Integer) elements_de_control_partida[0] - ( ( Integer ) elements_de_control_jugadors[1][1] ) ), 580, 140 ); if ( ( ( CombinacionsColors ) elements_de_control_partida[3] ) == CombinacionsColors.VERMELL_BLAU ) { g.drawImage( ( new ImageIcon( "img/tauler_vb.png" ) ).getImage(), -iniciX, -iniciY, getWidth(), getHeight(), null ); } else { g.drawImage( ( new ImageIcon( "img/tauler_nb.png" ) ).getImage(), -iniciX, -iniciY, getWidth(), getHeight(), null ); } //Si ha guanyat un jugador, mostrem el resultat. if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.GUANYA_JUGADOR_A ) { g.setColor( new Color( 0x66CCFF ) ); g.fillRoundRect( 150, 0, 300, 200, 16, 16 ); g.setColor( Color.black ); g.drawRoundRect( 150, 0, 300, 200, 16, 16 ); g.drawString( "Partida finalitzada.", 160, 30 ); g.drawString( "Guanya " + ( ( String ) elements_de_control_jugadors[3][0] ), 160, 50 ); g.drawString( "amb un temps de " + ( String ) elements_de_control_jugadors[2][0] + ",", 160, 70 ); g.drawString( "col·locant un total de " + ( ( Integer ) elements_de_control_jugadors[4][0] ) + " fitxes,", 160, 90 ); g.drawString( "i utilitzant " + ( ( Integer ) elements_de_control_jugadors[1][0] ) + " pistes.", 160, 110 ); g.drawString( "Per a continuar, pitja el botó Abandona partida.", 160, 150); } else if ( presentacio_ctrl.consultaEstatPartida() == EstatPartida.GUANYA_JUGADOR_B ) { g.setColor( new Color( 0x66CCFF ) ); g.fillRoundRect( 150, 0, 300, 200, 16, 16 ); g.setColor( Color.black ); g.drawRoundRect( 150, 0, 300, 200, 16, 16 ); g.drawString( "Partida finalitzada.", 160, 30 ); g.drawString( "Guanya " + ( ( String ) elements_de_control_jugadors[3][1] ), 160, 50 ); g.drawString( "amb un temps de " + ( String ) elements_de_control_jugadors[2][1] + ",", 160, 70 ); g.drawString( "col·locant un total de " + ( ( Integer ) elements_de_control_jugadors[4][1] ) + " fitxes,", 160, 90 ); g.drawString( "i utilitzant " + ( ( Integer ) elements_de_control_jugadors[1][1] ) + " pistes.", 160, 110 ); g.drawString( "Per a continuar, pitja el botó Abandona partida.", 160, 150); } }
diff --git a/src/main/java/suite/parser/WhitespaceProcessor.java b/src/main/java/suite/parser/WhitespaceProcessor.java index c0eafc5fc..8428a9e31 100644 --- a/src/main/java/suite/parser/WhitespaceProcessor.java +++ b/src/main/java/suite/parser/WhitespaceProcessor.java @@ -1,46 +1,40 @@ package suite.parser; import java.util.Set; import suite.util.FunUtil.Fun; import suite.util.ParseUtil; /** * Unify all whitespaces to the space bar space (ASCII code 32). * * @author ywsing */ public class WhitespaceProcessor implements Fun<String, String> { private Set<Character> whitespaces; public WhitespaceProcessor(Set<Character> whitespaces) { this.whitespaces = whitespaces; } @Override public String apply(String in) { StringBuilder sb = new StringBuilder(); int pos = 0; int quote = 0; while (pos < in.length()) { char ch = in.charAt(pos++); if (ch != '`') { quote = ParseUtil.getQuoteChange(quote, ch); - if (quote == 0) - if (whitespaces.contains(ch)) - sb.append(" "); - else - sb.append(ch); - else - sb.append(ch); + sb.append(quote == 0 && whitespaces.contains(ch) ? " " : ch); } else - sb.append(" ` "); + sb.append(quote == 0 ? " ` " : ch); } return sb.toString(); } }
false
true
public String apply(String in) { StringBuilder sb = new StringBuilder(); int pos = 0; int quote = 0; while (pos < in.length()) { char ch = in.charAt(pos++); if (ch != '`') { quote = ParseUtil.getQuoteChange(quote, ch); if (quote == 0) if (whitespaces.contains(ch)) sb.append(" "); else sb.append(ch); else sb.append(ch); } else sb.append(" ` "); } return sb.toString(); }
public String apply(String in) { StringBuilder sb = new StringBuilder(); int pos = 0; int quote = 0; while (pos < in.length()) { char ch = in.charAt(pos++); if (ch != '`') { quote = ParseUtil.getQuoteChange(quote, ch); sb.append(quote == 0 && whitespaces.contains(ch) ? " " : ch); } else sb.append(quote == 0 ? " ` " : ch); } return sb.toString(); }
diff --git a/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java b/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java index db1dd67ff..0433f2166 100644 --- a/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java +++ b/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java @@ -1,2663 +1,2664 @@ /** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.kmelia.servlets; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.fileupload.FileItem; import org.xml.sax.SAXException; import com.silverpeas.form.DataRecord; import com.silverpeas.form.Form; import com.silverpeas.form.FormException; import com.silverpeas.form.PagesContext; import com.silverpeas.form.RecordSet; import com.silverpeas.kmelia.KmeliaConstants; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelper; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelperContext; import com.silverpeas.pdc.web.PdcClassificationEntity; import com.silverpeas.publicationTemplate.PublicationTemplate; import com.silverpeas.publicationTemplate.PublicationTemplateException; import com.silverpeas.publicationTemplate.PublicationTemplateImpl; import com.silverpeas.publicationTemplate.PublicationTemplateManager; import com.silverpeas.thumbnail.ThumbnailRuntimeException; import com.silverpeas.thumbnail.control.ThumbnailController; import com.silverpeas.thumbnail.model.ThumbnailDetail; import com.silverpeas.util.FileUtil; import com.silverpeas.util.ForeignPK; import com.silverpeas.util.MimeTypes; import com.silverpeas.util.StringUtil; import com.silverpeas.util.ZipManager; import com.silverpeas.util.i18n.I18NHelper; import com.silverpeas.util.web.servlet.FileUploadUtil; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter; import com.stratelia.silverpeas.selection.Selection; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.silverpeas.versioning.model.DocumentVersion; import com.stratelia.silverpeas.wysiwyg.control.WysiwygController; import com.stratelia.webactiv.SilverpeasRole; import com.stratelia.webactiv.beans.admin.ProfileInst; import com.stratelia.webactiv.kmelia.KmeliaSecurity; import com.stratelia.webactiv.kmelia.control.KmeliaSessionController; import com.stratelia.webactiv.kmelia.control.ejb.KmeliaHelper; import com.stratelia.webactiv.kmelia.model.FileFolder; import com.stratelia.webactiv.kmelia.model.KmeliaPublication; import com.stratelia.webactiv.kmelia.model.TopicDetail; import com.stratelia.webactiv.kmelia.model.updatechain.FieldUpdateChainDescriptor; import com.stratelia.webactiv.kmelia.model.updatechain.Fields; import com.stratelia.webactiv.kmelia.servlets.handlers.StatisticRequestHandler; import com.stratelia.webactiv.util.ClientBrowserUtil; import com.stratelia.webactiv.util.DateUtil; import com.stratelia.webactiv.util.FileRepositoryManager; import com.stratelia.webactiv.util.GeneralPropertiesManager; import com.stratelia.webactiv.util.ResourceLocator; import com.stratelia.webactiv.util.WAAttributeValuePair; import com.stratelia.webactiv.util.fileFolder.FileFolderManager; import com.stratelia.webactiv.util.node.model.NodeDetail; import com.stratelia.webactiv.util.node.model.NodePK; import com.stratelia.webactiv.util.publication.info.model.InfoDetail; import com.stratelia.webactiv.util.publication.info.model.InfoImageDetail; import com.stratelia.webactiv.util.publication.info.model.InfoTextDetail; import com.stratelia.webactiv.util.publication.info.model.ModelDetail; import com.stratelia.webactiv.util.publication.model.Alias; import com.stratelia.webactiv.util.publication.model.CompletePublication; import com.stratelia.webactiv.util.publication.model.PublicationDetail; public class KmeliaRequestRouter extends ComponentRequestRouter<KmeliaSessionController> { private static final long serialVersionUID = 1L; private static final StatisticRequestHandler statisticRequestHandler = new StatisticRequestHandler(); /** * This method creates a KmeliaSessionController instance * @param mainSessionCtrl The MainSessionController instance * @param context Context of current component instance * @return a KmeliaSessionController instance */ @Override public KmeliaSessionController createComponentSessionController( MainSessionController mainSessionCtrl, ComponentContext context) { return new KmeliaSessionController(mainSessionCtrl, context); } /** * This method has to be implemented in the component request rooter class. returns the session * control bean name to be put in the request object ex : for almanach, returns "almanach" */ @Override public String getSessionControlBeanName() { return "kmelia"; } /** * This method has to be implemented by the component request rooter it has to compute a * destination page * @param function The entering request function ( : "Main.jsp") * @param kmelia The component Session Control, build and initialised. * @param request The entering request. The request rooter need it to get parameters * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, KmeliaSessionController kmelia, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", kmaxMode); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("validateClassification")) { String[] publicationIds = request.getParameterValues("pubid"); Collection<KmeliaPublication> publications = kmelia.getPublications(asPks(kmelia. getComponentId(), publicationIds)); request.setAttribute("Context", URLManager.getApplicationURL()); request.setAttribute("PublicationsDetails", publications); destination = rootDestination + "validateImportedFilesClassification.jsp"; } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = kmelia.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = NodePK.ROOT_NODE_ID; } } kmelia.setCurrentFolderId(topicId, true); resetWizard(kmelia); request.setAttribute("CurrentFolderId", topicId); request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis()); request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled()); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", kmelia.isTopicHaveUpdateChainDescriptor()); request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", kmelia.getUserDetail().isAccessGuest()); request.setAttribute("RightsOnTopicsEnabled", kmelia.isRightsOnTopicsEnabled()); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeviewUsed()) { destination = rootDestination + "treeview.jsp"; } else if (kmelia.isTreeStructure()) { destination = rootDestination + "oneLevel.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } else if (function.equals("GoToCurrentTopic")) { if (!NodePK.ROOT_NODE_ID.equals(kmelia.getCurrentFolderId())) { request.setAttribute("Id", kmelia.getCurrentFolderId()); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type != null && ("Publication".equals(type) || "com.stratelia.webactiv.calendar.backbone.TodoDetail".equals(type) || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { processPath(kmelia, id); if ("Attachment".equals(type)) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if ("Document".equals(type)) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { // we have to find which page contains the right publication List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); KmeliaPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getDetail().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if ("Node".equals(type)) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", kmelia, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if ("Wysiwyg".equals(type)) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); kmelia.setSessionPublication(kmeliaPublication); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String id = request.getParameter("PubId"); if (StringUtil.isDefined(id)) { request.setAttribute("PubId", id); } request.setAttribute("Wizard", kmelia.getWizard()); List<NodeDetail> path = kmelia.getTopicPath(kmelia.getCurrentFolderId()); request.setAttribute("Path", path); request.setAttribute("Profile", kmelia.getProfile()); String action = (String) request.getAttribute("Action"); if (!StringUtil.isDefined(action)) { action = "UpdateView"; request.setAttribute("Action", action); } if ("UpdateView".equals(action)) { request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } else { // case of creation request.setAttribute("TaxonomyOK", true); request.setAttribute("ValidatorsOK", true); } destination = rootDestination + "publicationManager.jsp"; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK(). getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getCurrentFolder(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); KmeliaPublication kmeliaPublication = kmelia.getPublication(cloneId); kmelia.setSessionClone(kmeliaPublication); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } if (!kmaxMode) { boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath || KmeliaHelper.isToValidateFolder(kmelia.getCurrentFolderId())) { processPath(kmelia, id); } else { processPath(kmelia, null); } } KmeliaPublication kmeliaPublication = null; if (StringUtil.isDefined(id)) { kmeliaPublication = kmelia.getPublication(id, true); kmelia.setSessionPublication(kmeliaPublication); PublicationDetail pubDetail = kmeliaPublication.getDetail(); if (pubDetail.haveGotClone()) { KmeliaPublication clone = kmelia.getPublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { kmeliaPublication = kmelia.getSessionPublication(); id = kmeliaPublication.getDetail().getPK().getId(); } if (toolboxMode) { request.setAttribute("PubId", id); destination = getDestination("publicationManager.jsp", kmelia, request); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, kmeliaPublication. getDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = kmeliaPublication.getCompleteDetail().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("PubId", id); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", kmelia.getValidationType()); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", kmelia.isWriterApproval(id)); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // check is requested publication is an alias checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); + request.setAttribute("TaxonomyOK", false); + request.setAttribute("ValidatorsOK", false); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", kmelia.getRang()); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size()); } else { request.setAttribute("NbPublis", 1); } - putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), - kmelia, request); + putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); // option Actualités décentralisées request.setAttribute("NewsManage", kmelia.isNewsManage()); if (kmelia.isNewsManage()) { request.setAttribute("DelegatedNews", kmelia.getDelegatedNews(id)); request .setAttribute("IsBasket", NodePK.BIN_NODE_ID.equals(kmelia.getCurrentFolderId())); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", kmelia, request); } else { String pubId = kmelia.getSessionPubliOrClone().getDetail().getPK().getId(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, kmelia, request); } else { request.setAttribute("PubId", pubId); destination = getDestination("publicationManager.jsp", kmelia, request); } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias KmeliaPublication kmeliaPublication = kmelia.getSessionPublication(); checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { request.setAttribute("Action", "New"); destination = getDestination("publicationManager", kmelia, request); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication String positions = FileUploadUtil.getParameter(parameters, "Positions"); PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification(); if (StringUtil.isDefined(positions)) { withClassification = PdcClassificationEntity.fromJSON(positions); } PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail, withClassification); // create vignette if exists processVignette(parameters, kmelia, pubDetail); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { KmeliaPublication kmeliaPublication = kmelia.getPublication(newPubId); kmelia.setSessionPublication(kmeliaPublication); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); if (toolboxMode) { request.setAttribute("Topics", kmelia.getAllTopics()); } else { List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("Components", kmelia.getComponents(aliases)); } destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); for (Alias oldAlias : oldAliases) { if (!loadedComponentIds.contains(oldAlias.getInstanceId())) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportPublications")) { String selectedIds = request.getParameter("SelectedIds"); String notSelectedIds = request.getParameter("NotSelectedIds"); List<String> ids = kmelia.processSelectedPublicationIds(selectedIds, notSelectedIds); List<WAAttributeValuePair> publicationIds = new ArrayList<WAAttributeValuePair>(); for (String id : ids) { publicationIds.add(new WAAttributeValuePair(id, kmelia.getComponentId())); } request.setAttribute("selectedResultsWa", publicationIds); kmelia.resetSelectedPublicationIds(); // Go to importExportPeas destination = "/RimportExportPeas/jsp/SelectExportMode"; } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (StringUtil.isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template request.setAttribute("Name", modelId); destination = getDestination("GoToXMLForm", kmelia, request); } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { setTemplatesUsedIntoRequest(kmelia, request); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { request.setAttribute("XMLForms", kmelia.getForms()); // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if ("ChangeTemplate".equals(function)) { kmelia.removePublicationContent(); destination = getDestination("ToPubliContent", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getDetail().getPK(). getId())) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone(). getCompleteDetail()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); for (FileItem item : parameters) { if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = Integer.parseInt(item.getFieldName().substring(8, item.getFieldName().length())); textDetails.add(new InfoTextDetail(null, Integer.toString(textOrder), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = Long.toString(System.currentTimeMillis()) + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if ("gif".equalsIgnoreCase(type) || "jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type)) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, Integer.toString(imageOrder), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); if (!StringUtil.isDefined(xmlFormName)) { xmlFormName = (String) request.getAttribute("Name"); } setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); // template can be changed only if current topic is using at least two templates setTemplatesUsedIntoRequest(kmelia, request); @SuppressWarnings("unchecked") Collection<PublicationTemplate> templates = (Collection<PublicationTemplate>) request.getAttribute("XMLForms"); boolean wysiwygUsable = (Boolean) request.getAttribute("WysiwygValid"); request.setAttribute("IsChangingTemplateAllowed", templates.size() >= 2 || (!templates.isEmpty() && wysiwygUsable)); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate( kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia .getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getCurrentFolderId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, true, 3)); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", kmelia, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } else if (function.equals("SuggestDelegatedNews")) { String pubId = kmelia.addDelegatedNews(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); }/*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia.getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", kmelia, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxViewUnbalanced")) { List<KmeliaPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<KmeliaPublication> publications = (List<KmeliaPublication>) basket. getKmeliaPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<KmeliaPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !"X".equals(timeCriteria)) { publications = kmelia.search(combination, Integer.parseInt(timeCriteria)); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia.getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else if ("statistics".equals(function)) { destination = rootDestination + statisticRequestHandler.handleRequest(request, function, kmelia); }else if("statSelectionGroup".equals(function)) { destination = statisticRequestHandler.handleRequest(request, function, kmelia); } else { destination = rootDestination + function; } if (profileError) { destination = GeneralPropertiesManager.getString("sessionTimeout"); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; } private String getDocumentNotFoundDestination(KmeliaSessionController kmelia, HttpServletRequest request) { request.setAttribute("ComponentId", kmelia.getComponentId()); return "/admin/jsp/documentNotFound.jsp"; } private PublicationDetail getPublicationDetail(List<FileItem> parameters, KmeliaSessionController kmelia) throws Exception { String id = FileUploadUtil.getParameter(parameters, "PubId"); String status = FileUploadUtil.getParameter(parameters, "Status"); String name = FileUploadUtil.getParameter(parameters, "Name"); String description = FileUploadUtil.getParameter(parameters, "Description"); String keywords = FileUploadUtil.getParameter(parameters, "Keywords"); String beginDate = FileUploadUtil.getParameter(parameters, "BeginDate"); String endDate = FileUploadUtil.getParameter(parameters, "EndDate"); String version = FileUploadUtil.getParameter(parameters, "Version"); String importance = FileUploadUtil.getParameter(parameters, "Importance"); String beginHour = FileUploadUtil.getParameter(parameters, "BeginHour"); String endHour = FileUploadUtil.getParameter(parameters, "EndHour"); String author = FileUploadUtil.getParameter(parameters, "Author"); String targetValidatorId = FileUploadUtil.getParameter(parameters, "ValideurId"); String tempId = FileUploadUtil.getParameter(parameters, "TempId"); String infoId = FileUploadUtil.getParameter(parameters, "InfoId"); String draftOutDate = FileUploadUtil.getParameter(parameters, "DraftOutDate"); Date jBeginDate = null; Date jEndDate = null; Date jDraftOutDate = null; if (StringUtil.isDefined(beginDate)) { jBeginDate = DateUtil.stringToDate(beginDate, kmelia.getLanguage()); } if (StringUtil.isDefined(endDate)) { jEndDate = DateUtil.stringToDate(endDate, kmelia.getLanguage()); } if (StringUtil.isDefined(draftOutDate)) { jDraftOutDate = DateUtil.stringToDate(draftOutDate, kmelia.getLanguage()); } String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, importance, version, keywords, "", status, "", author); pubDetail.setBeginHour(beginHour); pubDetail.setEndHour(endHour); pubDetail.setStatus(status); pubDetail.setDraftOutDate(jDraftOutDate); if (StringUtil.isDefined(targetValidatorId)) { pubDetail.setTargetValidatorId(targetValidatorId); } pubDetail.setCloneId(tempId); if (StringUtil.isDefined(infoId)) { pubDetail.setInfoId(infoId); } I18NHelper.setI18NInfo(pubDetail, parameters); return pubDetail; } private void processVignette(List<FileItem> parameters, KmeliaSessionController kmelia, PublicationDetail publication) throws Exception { // First, check if image have been uploaded FileItem file = FileUploadUtil.getFile(parameters, "WAIMGVAR0"); String mimeType = null; String physicalName = null; if (file != null) { String logicalName = file.getName().replace('\\', '/'); if (logicalName != null) { logicalName = logicalName.substring(logicalName.lastIndexOf('/') + 1, logicalName.length()); mimeType = FileUtil.getMimeType(logicalName); String type = FileRepositoryManager.getFileExtension(logicalName); if (FileUtil.isImage(logicalName)) { physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type; File dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + kmelia.getPublicationSettings().getString("imagesSubDirectory")); if (!dir.exists()) { dir.mkdirs(); } File target = new File(dir, physicalName); file.write(target); } } } // If no image have been uploaded, check if one have been picked up from a gallery if (physicalName == null) { // on a pas d'image, regarder s'il y a une provenant de la galerie String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery"); if (StringUtil.isDefined(nameImageFromGallery)) { physicalName = nameImageFromGallery; mimeType = "image/jpeg"; } } // If one image is defined, save it through Thumbnail service if (StringUtil.isDefined(physicalName)) { ThumbnailDetail detail = new ThumbnailDetail(kmelia.getComponentId(), Integer.parseInt(publication.getPK().getId()), ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE); detail.setOriginalFileName(physicalName); detail.setMimeType(mimeType); try { int[] thumbnailSize = kmelia.getThumbnailWidthAndHeight(); ThumbnailController.updateThumbnail(detail, thumbnailSize[0], thumbnailSize[1]); // force indexation to taking into account new thumbnail if (publication.isIndexable()) { kmelia.getPublicationBm().createIndex(publication.getPK()); } } catch (ThumbnailRuntimeException e) { SilverTrace.error("Thumbnail", "ThumbnailRequestRouter.addThumbnail", "root.MSG_GEN_PARAM_VALUE", e); try { ThumbnailController.deleteThumbnail(detail); } catch (Exception exp) { SilverTrace.info("Thumbnail", "ThumbnailRequestRouter.addThumbnail - remove after error", "root.MSG_GEN_PARAM_VALUE", exp); } } } } /** * Process Form Upload for publications import * @param kmeliaScc * @param request * @param routeDestination * @return destination */ private String processFormUpload(KmeliaSessionController kmeliaScc, HttpServletRequest request, String routeDestination, boolean isMassiveMode) { String destination = ""; String topicId = ""; String importMode = KmeliaSessionController.UNITARY_IMPORT_MODE; boolean draftMode = false; String logicalName = ""; String message = ""; String tempFolderName = ""; String tempFolderPath = ""; String fileType = ""; long fileSize = 0; long processStart = new Date().getTime(); ResourceLocator attachmentResourceLocator = new ResourceLocator( "com.stratelia.webactiv.util.attachment.multilang.attachment", kmeliaScc.getLanguage()); FileItem fileItem = null; int versionType = DocumentVersion.TYPE_DEFAULT_VERSION; try { List<FileItem> items = FileUploadUtil.parseRequest(request); topicId = FileUploadUtil.getParameter(items, "topicId"); importMode = FileUploadUtil.getParameter(items, "opt_importmode"); String sVersionType = FileUploadUtil.getParameter(items, "opt_versiontype"); if (StringUtil.isDefined(sVersionType)) { versionType = Integer.parseInt(sVersionType); } String sDraftMode = FileUploadUtil.getParameter(items, "chk_draft"); if (StringUtil.isDefined(sDraftMode)) { draftMode = StringUtil.getBooleanValue(sDraftMode); } fileItem = FileUploadUtil.getFile(items, "file_name"); if (fileItem != null) { logicalName = fileItem.getName(); if (logicalName != null) { boolean runOnUnix = !FileUtil.isWindows(); if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.processFormUpload", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); // Name of temp folder: timestamp and userId tempFolderName = Long.toString(System.currentTimeMillis()) + "_" + kmeliaScc.getUserId(); // Mime type of the file fileType = fileItem.getContentType(); // Zip contentType not detected under Firefox ! if (!ClientBrowserUtil.isInternetExplorer(request)) { fileType = MimeTypes.ARCHIVE_MIME_TYPE; } fileSize = fileItem.getSize(); // Directory Temp for the uploaded file tempFolderPath = FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName; if (!new File(tempFolderPath).exists()) { FileRepositoryManager.createAbsolutePath(kmeliaScc.getComponentId(), GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName); } // Creation of the file in the temp folder File fileUploaded = new File(FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName + File.separator + logicalName); fileItem.write(fileUploaded); // Is a real file ? if (fileSize > 0) { SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize=" + fileSize + " fileType=" + fileType + " importMode=" + importMode + " draftMode=" + draftMode); int nbFiles = 1; // Compute nbFiles only in unitary Import mode if (!importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE) && fileUploaded.getName().toLowerCase().endsWith(".zip")) { nbFiles = ZipManager.getNbFiles(fileUploaded); } // Import !! List<PublicationDetail> publicationDetails = kmeliaScc.importFile(fileUploaded, fileType, topicId, importMode, draftMode, versionType); long processDuration = new Date().getTime() - processStart; // Title for popup report String importModeTitle = ""; if (importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) { importModeTitle = kmeliaScc.getString("kmelia.ImportModeUnitaireTitre"); } else { importModeTitle = kmeliaScc.getString("kmelia.ImportModeMassifTitre"); } SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "nbFiles = " + nbFiles + " publicationDetails=" + publicationDetails + " ProcessDuration=" + processDuration + " ImportMode=" + importMode + " Draftmode=" + draftMode + " Title=" + importModeTitle); request.setAttribute("PublicationsDetails", publicationDetails); request.setAttribute("NbFiles", nbFiles); request.setAttribute("ProcessDuration", FileRepositoryManager.formatFileUploadTime( processDuration)); request.setAttribute("ImportMode", importMode); request.setAttribute("DraftMode", draftMode); request.setAttribute("Title", importModeTitle); request.setAttribute("Context", URLManager.getApplicationURL()); destination = routeDestination + "reportImportFiles.jsp"; String componentId = publicationDetails.get(0).getComponentInstanceId(); if (kmeliaScc.isDefaultClassificationModifiable(topicId, componentId)) { destination = routeDestination + "validateImportedFilesClassification.jsp"; } } else { // File access failed message = attachmentResourceLocator.getString("liaisonInaccessible"); request.setAttribute("Message", message); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } FileFolderManager.deleteFolder(tempFolderPath); } else { // the field did not contain a file request.setAttribute("Message", attachmentResourceLocator .getString("liaisonInaccessible")); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } } } /* * catch (IOException e) { //File size exceeds Maximum file size message = * attachmentResourceLocator.getString("fichierTropGrand")+ " (" + * FileRepositoryManager.formatFileSize(maxFileSize) + "&nbsp;" + * attachmentResourceLocator.getString("maximum") +") !!"; * request.setAttribute("Message",message); request.setAttribute("TopicId",topicId); * destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) destination = * routeDestination + "importMultiFiles.jsp"; } */catch (Exception e) { // Other exception request.setAttribute("Message", e.getMessage()); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } SilverTrace.warn("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED", e); } return destination; } private void processPath(KmeliaSessionController kmeliaSC, String id) throws RemoteException { if (!kmeliaSC.isKmaxMode) { NodePK pk = null; if (!StringUtil.isDefined(id)) { pk = kmeliaSC.getCurrentFolderPK(); } else { pk = kmeliaSC.getAllowedPublicationFather(id); // get publication parent kmeliaSC.setCurrentFolderId(pk.getId(), true); } Collection<NodeDetail> pathColl = kmeliaSC.getTopicPath(pk.getId()); String linkedPathString = kmeliaSC.displayPath(pathColl, true, 3); String pathString = kmeliaSC.displayPath(pathColl, false, 3); kmeliaSC.setSessionPath(linkedPathString); kmeliaSC.setSessionPathString(pathString); } } private void putXMLDisplayerIntoRequest(PublicationDetail pubDetail, KmeliaSessionController kmelia, HttpServletRequest request) throws PublicationTemplateException, FormException { String infoId = pubDetail.getInfoId(); String pubId = pubDetail.getPK().getId(); if (!StringUtil.isInteger(infoId)) { PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate( pubDetail. getPK().getInstanceId() + ":" + infoId); // RecordTemplate recordTemplate = pubTemplate.getRecordTemplate(); Form formView = pubTemplate.getViewForm(); // get displayed language String language = checkLanguage(kmelia, pubDetail); RecordSet recordSet = pubTemplate.getRecordSet(); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("XMLForm", formView); request.setAttribute("XMLData", data); } } private String processWizard(String function, KmeliaSessionController kmeliaSC, HttpServletRequest request, String rootDestination) throws RemoteException, PublicationTemplateException, FormException { String destination = ""; if (function.equals("WizardStart")) { // récupération de l'id du thème dans lequel on veux mettre la // publication // si on ne viens pas d'un theme-tracker String topicId = request.getParameter("TopicId"); if (StringUtil.isDefined(topicId)) { TopicDetail topic = kmeliaSC.getTopic(topicId); kmeliaSC.setSessionTopic(topic); } // recherche du dernier onglet String wizardLast = "1"; List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if (kmeliaSC.isKmaxMode) { wizardLast = "4"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { wizardLast = "3"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { wizardLast = "2"; } kmeliaSC.setWizardLast(wizardLast); request.setAttribute("WizardLast", wizardLast); kmeliaSC.setWizard("progress"); request.setAttribute("Action", "Wizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardHeader")) { // passage des paramètres String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } request.setAttribute("WizardRow", kmeliaSC.getWizardRow()); request.setAttribute("WizardLast", kmeliaSC.getWizardLast()); request.setAttribute("Action", "UpdateWizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); request.setAttribute("PubId", id); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardNext")) { // redirige vers l'onglet suivant de l'assistant de publication String position = request.getParameter("Position"); if (!StringUtil.isDefined(position)) { position = (String) request.getAttribute("Position"); } String next = "End"; String wizardRow = kmeliaSC.getWizardRow(); request.setAttribute("WizardRow", wizardRow); int numRow = 0; if (StringUtil.isDefined(wizardRow)) { numRow = Integer.parseInt(wizardRow); } List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if (position.equals("View")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { // on passe à la page du contenu next = "Content"; if (numRow <= 2) { wizardRow = "2"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Content")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Attachment")) { if (kmeliaSC.isKmaxMode) { next = "KmaxClassification"; } else { next = "End"; } if (!next.equals("End")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } } else if (position.equals("KmaxClassification")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "End"; } // mise à jour du rang en cours kmeliaSC.setWizardRow(wizardRow); // passage des paramètres setWizardParams(request, kmeliaSC); if (next.equals("View")) { destination = getDestination("WizardStart", kmeliaSC, request); } else if (next.equals("Content")) { destination = getDestination("ToPubliContent", kmeliaSC, request); } else if (next.equals("Attachment")) { destination = getDestination("ViewAttachments", kmeliaSC, request); } else if (next.equals("KmaxClassification")) { destination = getDestination("KmaxViewCombination", kmeliaSC, request); } else if (next.equals("End")) { // terminer la publication : la sortir du mode brouillon kmeliaSC.setWizard("finish"); kmeliaSC.draftOutPublication(); destination = getDestination("ViewPublication", kmeliaSC, request); } } return destination; } private void setWizardParams(HttpServletRequest request, KmeliaSessionController kmelia) { // Paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("WizardRow", kmelia.getWizardRow()); request.setAttribute("WizardLast", kmelia.getWizardLast()); } private void resetWizard(KmeliaSessionController kmelia) { kmelia.setWizard("none"); kmelia.setWizardLast("0"); kmelia.setWizardRow("0"); } private void setXMLForm(HttpServletRequest request, KmeliaSessionController kmelia, String xmlFormName) throws PublicationTemplateException, FormException { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); String pubId = pubDetail.getPK().getId(); String xmlFormShortName = null; if (!StringUtil.isDefined(xmlFormName)) { xmlFormShortName = pubDetail.getInfoId(); xmlFormName = null; } else { xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); SilverTrace.info("kmelia", "KmeliaRequestRouter.setXMLForm()", "root.MSG_GEN_PARAM_VALUE", "xmlFormShortName = " + xmlFormShortName); // register xmlForm to publication getPublicationTemplateManager().addDynamicPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName, xmlFormName); } PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate( kmelia. getComponentId() + ":" + xmlFormShortName, xmlFormName); Form formUpdate = pubTemplate.getUpdateForm(); RecordSet recordSet = pubTemplate.getRecordSet(); // get displayed language String language = checkLanguage(kmelia, pubDetail); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("Form", formUpdate); request.setAttribute("Data", data); request.setAttribute("XMLFormName", xmlFormName); } private void setLanguage(HttpServletRequest request, KmeliaSessionController kmelia) { String language = request.getParameter("SwitchLanguage"); if (StringUtil.isDefined(language)) { kmelia.setCurrentLanguage(language); } request.setAttribute("Language", kmelia.getCurrentLanguage()); } private String checkLanguage(KmeliaSessionController kmelia) { return checkLanguage(kmelia, kmelia.getSessionPublication().getDetail()); } private String checkLanguage(KmeliaSessionController kmelia, PublicationDetail pubDetail) { return pubDetail.getLanguageToDisplay(kmelia.getCurrentLanguage()); } private void checkAlias(KmeliaSessionController kmelia, KmeliaPublication publication) { if (!kmelia.getComponentId().equals( publication.getDetail().getPK().getInstanceId())) { publication.asAlias(); } } private void updatePubliDuringUpdateChain(String id, HttpServletRequest request, KmeliaSessionController kmelia) throws RemoteException { // enregistrement des modifications de la publi String name = request.getParameter("Name"); String description = request.getParameter("Description"); String keywords = request.getParameter("Keywords"); String tree = request.getParameter("Tree"); String[] topics = request.getParameterValues("topicChoice"); // sauvegarde des données Fields fields = kmelia.getFieldUpdateChain(); FieldUpdateChainDescriptor field = kmelia.getFieldUpdateChain().getName(); field.setName("Name"); field.setValue(name); fields.setName(field); field = kmelia.getFieldUpdateChain().getDescription(); field.setName("Description"); field.setValue(description); fields.setDescription(field); field = kmelia.getFieldUpdateChain().getKeywords(); field.setName("Keywords"); field.setValue(keywords); fields.setKeywords(field); field = kmelia.getFieldUpdateChain().getTree(); if (field != null) { field.setName("Topics"); field.setValue(tree); fields.setTree(field); } fields.setTopics(topics); kmelia.setFieldUpdateChain(fields); Date jBeginDate = null; Date jEndDate = null; String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, "0", "", keywords, "", "", "", ""); pubDetail.setStatus("Valid"); I18NHelper.setI18NInfo(pubDetail, request); try { // Execute helper String helperClassName = kmelia.getFieldUpdateChain().getHelper(); UpdateChainHelper helper; helper = (UpdateChainHelper) Class.forName(helperClassName).newInstance(); UpdateChainHelperContext uchc = new UpdateChainHelperContext(pubDetail, kmelia); uchc.setAllTopics(kmelia.getAllTopics()); helper.execute(uchc); pubDetail = uchc.getPubDetail(); // mettre à jour les emplacements si necessaire String[] calculedTopics = uchc.getTopics(); if (calculedTopics != null) { topics = calculedTopics; } } catch (Exception e) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, e.getMessage(), e); } kmelia.updatePublication(pubDetail); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } kmelia.setAliases(pubDetail.getPK(), aliases); } private String processUpdateChainOperation(String rootDestination, String function, KmeliaSessionController kmelia, HttpServletRequest request) throws IOException, ClassNotFoundException, SAXException, ParserConfigurationException { if (function.equals("UpdateChainInit")) { // récupération du descripteur kmelia.initUpdateChainDescriptor(); // Modification par chaine de toutes les publications du thème : // positionnement sur la première publi String pubId = kmelia.getFirst(); request.setAttribute("PubId", pubId); // initialiser le topic en cours kmelia.initUpdateChainTopicChoice(pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainPublications")) { String id = (String) request.getAttribute("PubId"); request.setAttribute("Action", "UpdateChain"); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("PubId", id); request.setAttribute("SaveFields", kmelia.getFieldUpdateChain()); if (StringUtil.isDefined(id)) { request.setAttribute("Rang", kmelia.getRang()); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size()); } else { request.setAttribute("NbPublis", 1); } // request.setAttribute("PathList",kmelia.getPublicationFathers(id)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getUpdateChainTopics()); // mise à jour de la publication en session pour récupérer les alias KmeliaPublication kmeliaPublication = kmelia.getPublication(id); kmelia.setSessionPublication(kmeliaPublication); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); // url du fichier joint request.setAttribute("FileUrl", kmelia.getFirstAttachmentURLOfCurrentPublication()); return rootDestination + "updateByChain.jsp"; } } else if (function.equals("UpdateChainNextUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // récupération de la publication suivante String nextPubId = kmelia.getNext(); request.setAttribute("PubId", nextPubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainLastUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getCurrentFolderId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainSkipUpdate")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainEndUpdate")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getCurrentFolderId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainUpdateAll")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getCurrentFolderId()); // enregistrement des modifications sur toutes les publications restantes // publication courante String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // passer à la suivante si elle existe int rang = kmelia.getRang(); int nbPublis = kmelia.getSessionPublicationsList().size(); while (rang < nbPublis - 1) { String pubId = kmelia.getNext(); updatePubliDuringUpdateChain(pubId, request, kmelia); rang = kmelia.getRang(); } // retour au thème return getDestination("GoToTopic", kmelia, request); } return ""; } /** * Gets an instance of PublicationTemplateManager. * @return an instance of PublicationTemplateManager. */ public PublicationTemplateManager getPublicationTemplateManager() { return PublicationTemplateManager.getInstance(); } private void setTemplatesUsedIntoRequest(KmeliaSessionController kmelia, HttpServletRequest request) throws RemoteException { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = kmelia.getForms(); // recherche de la liste des modèles utilisables for (PublicationTemplate template : templates) { PublicationTemplate xmlForm = template; // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); for (ModelDetail modelDetail : dbForms) { // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", wysiwygValid); // s'il n'y a pas de modèles selectionnés, les présenter tous if ((listModelXml == null || listModelXml.isEmpty()) && (listModelForm == null || listModelForm.isEmpty()) && !wysiwygValid) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } } /** * Converts the specified identifier into a Silverpeas content primary key. * @param instanceId the unique identifier of the component instance to which the contents * belongs. * @param ids one or several identifiers of Silverpeas contents. * @return a list of one or several Silverpeas primary keys, each of them corresponding to one * specified identifier. */ private List<ForeignPK> asPks(String instanceId, String... ids) { List<ForeignPK> pks = new ArrayList<ForeignPK>(); for (String oneId : ids) { pks.add(new ForeignPK(oneId, instanceId)); } return pks; } }
false
true
public String getDestination(String function, KmeliaSessionController kmelia, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", kmaxMode); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("validateClassification")) { String[] publicationIds = request.getParameterValues("pubid"); Collection<KmeliaPublication> publications = kmelia.getPublications(asPks(kmelia. getComponentId(), publicationIds)); request.setAttribute("Context", URLManager.getApplicationURL()); request.setAttribute("PublicationsDetails", publications); destination = rootDestination + "validateImportedFilesClassification.jsp"; } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = kmelia.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = NodePK.ROOT_NODE_ID; } } kmelia.setCurrentFolderId(topicId, true); resetWizard(kmelia); request.setAttribute("CurrentFolderId", topicId); request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis()); request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled()); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", kmelia.isTopicHaveUpdateChainDescriptor()); request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", kmelia.getUserDetail().isAccessGuest()); request.setAttribute("RightsOnTopicsEnabled", kmelia.isRightsOnTopicsEnabled()); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeviewUsed()) { destination = rootDestination + "treeview.jsp"; } else if (kmelia.isTreeStructure()) { destination = rootDestination + "oneLevel.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } else if (function.equals("GoToCurrentTopic")) { if (!NodePK.ROOT_NODE_ID.equals(kmelia.getCurrentFolderId())) { request.setAttribute("Id", kmelia.getCurrentFolderId()); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type != null && ("Publication".equals(type) || "com.stratelia.webactiv.calendar.backbone.TodoDetail".equals(type) || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { processPath(kmelia, id); if ("Attachment".equals(type)) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if ("Document".equals(type)) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { // we have to find which page contains the right publication List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); KmeliaPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getDetail().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if ("Node".equals(type)) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", kmelia, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if ("Wysiwyg".equals(type)) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); kmelia.setSessionPublication(kmeliaPublication); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String id = request.getParameter("PubId"); if (StringUtil.isDefined(id)) { request.setAttribute("PubId", id); } request.setAttribute("Wizard", kmelia.getWizard()); List<NodeDetail> path = kmelia.getTopicPath(kmelia.getCurrentFolderId()); request.setAttribute("Path", path); request.setAttribute("Profile", kmelia.getProfile()); String action = (String) request.getAttribute("Action"); if (!StringUtil.isDefined(action)) { action = "UpdateView"; request.setAttribute("Action", action); } if ("UpdateView".equals(action)) { request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } else { // case of creation request.setAttribute("TaxonomyOK", true); request.setAttribute("ValidatorsOK", true); } destination = rootDestination + "publicationManager.jsp"; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK(). getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getCurrentFolder(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); KmeliaPublication kmeliaPublication = kmelia.getPublication(cloneId); kmelia.setSessionClone(kmeliaPublication); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } if (!kmaxMode) { boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath || KmeliaHelper.isToValidateFolder(kmelia.getCurrentFolderId())) { processPath(kmelia, id); } else { processPath(kmelia, null); } } KmeliaPublication kmeliaPublication = null; if (StringUtil.isDefined(id)) { kmeliaPublication = kmelia.getPublication(id, true); kmelia.setSessionPublication(kmeliaPublication); PublicationDetail pubDetail = kmeliaPublication.getDetail(); if (pubDetail.haveGotClone()) { KmeliaPublication clone = kmelia.getPublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { kmeliaPublication = kmelia.getSessionPublication(); id = kmeliaPublication.getDetail().getPK().getId(); } if (toolboxMode) { request.setAttribute("PubId", id); destination = getDestination("publicationManager.jsp", kmelia, request); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, kmeliaPublication. getDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = kmeliaPublication.getCompleteDetail().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("PubId", id); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", kmelia.getValidationType()); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", kmelia.isWriterApproval(id)); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // check is requested publication is an alias checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", kmelia.getRang()); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size()); } else { request.setAttribute("NbPublis", 1); } putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); // option Actualités décentralisées request.setAttribute("NewsManage", kmelia.isNewsManage()); if (kmelia.isNewsManage()) { request.setAttribute("DelegatedNews", kmelia.getDelegatedNews(id)); request .setAttribute("IsBasket", NodePK.BIN_NODE_ID.equals(kmelia.getCurrentFolderId())); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", kmelia, request); } else { String pubId = kmelia.getSessionPubliOrClone().getDetail().getPK().getId(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, kmelia, request); } else { request.setAttribute("PubId", pubId); destination = getDestination("publicationManager.jsp", kmelia, request); } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias KmeliaPublication kmeliaPublication = kmelia.getSessionPublication(); checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { request.setAttribute("Action", "New"); destination = getDestination("publicationManager", kmelia, request); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication String positions = FileUploadUtil.getParameter(parameters, "Positions"); PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification(); if (StringUtil.isDefined(positions)) { withClassification = PdcClassificationEntity.fromJSON(positions); } PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail, withClassification); // create vignette if exists processVignette(parameters, kmelia, pubDetail); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { KmeliaPublication kmeliaPublication = kmelia.getPublication(newPubId); kmelia.setSessionPublication(kmeliaPublication); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); if (toolboxMode) { request.setAttribute("Topics", kmelia.getAllTopics()); } else { List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("Components", kmelia.getComponents(aliases)); } destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); for (Alias oldAlias : oldAliases) { if (!loadedComponentIds.contains(oldAlias.getInstanceId())) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportPublications")) { String selectedIds = request.getParameter("SelectedIds"); String notSelectedIds = request.getParameter("NotSelectedIds"); List<String> ids = kmelia.processSelectedPublicationIds(selectedIds, notSelectedIds); List<WAAttributeValuePair> publicationIds = new ArrayList<WAAttributeValuePair>(); for (String id : ids) { publicationIds.add(new WAAttributeValuePair(id, kmelia.getComponentId())); } request.setAttribute("selectedResultsWa", publicationIds); kmelia.resetSelectedPublicationIds(); // Go to importExportPeas destination = "/RimportExportPeas/jsp/SelectExportMode"; } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (StringUtil.isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template request.setAttribute("Name", modelId); destination = getDestination("GoToXMLForm", kmelia, request); } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { setTemplatesUsedIntoRequest(kmelia, request); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { request.setAttribute("XMLForms", kmelia.getForms()); // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if ("ChangeTemplate".equals(function)) { kmelia.removePublicationContent(); destination = getDestination("ToPubliContent", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getDetail().getPK(). getId())) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone(). getCompleteDetail()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); for (FileItem item : parameters) { if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = Integer.parseInt(item.getFieldName().substring(8, item.getFieldName().length())); textDetails.add(new InfoTextDetail(null, Integer.toString(textOrder), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = Long.toString(System.currentTimeMillis()) + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if ("gif".equalsIgnoreCase(type) || "jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type)) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, Integer.toString(imageOrder), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); if (!StringUtil.isDefined(xmlFormName)) { xmlFormName = (String) request.getAttribute("Name"); } setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); // template can be changed only if current topic is using at least two templates setTemplatesUsedIntoRequest(kmelia, request); @SuppressWarnings("unchecked") Collection<PublicationTemplate> templates = (Collection<PublicationTemplate>) request.getAttribute("XMLForms"); boolean wysiwygUsable = (Boolean) request.getAttribute("WysiwygValid"); request.setAttribute("IsChangingTemplateAllowed", templates.size() >= 2 || (!templates.isEmpty() && wysiwygUsable)); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate( kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia .getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getCurrentFolderId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, true, 3)); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", kmelia, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } else if (function.equals("SuggestDelegatedNews")) { String pubId = kmelia.addDelegatedNews(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); }/*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia.getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", kmelia, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxViewUnbalanced")) { List<KmeliaPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<KmeliaPublication> publications = (List<KmeliaPublication>) basket. getKmeliaPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<KmeliaPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !"X".equals(timeCriteria)) { publications = kmelia.search(combination, Integer.parseInt(timeCriteria)); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia.getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else if ("statistics".equals(function)) { destination = rootDestination + statisticRequestHandler.handleRequest(request, function, kmelia); }else if("statSelectionGroup".equals(function)) { destination = statisticRequestHandler.handleRequest(request, function, kmelia); } else { destination = rootDestination + function; } if (profileError) { destination = GeneralPropertiesManager.getString("sessionTimeout"); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
public String getDestination(String function, KmeliaSessionController kmelia, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", kmaxMode); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("validateClassification")) { String[] publicationIds = request.getParameterValues("pubid"); Collection<KmeliaPublication> publications = kmelia.getPublications(asPks(kmelia. getComponentId(), publicationIds)); request.setAttribute("Context", URLManager.getApplicationURL()); request.setAttribute("PublicationsDetails", publications); destination = rootDestination + "validateImportedFilesClassification.jsp"; } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = kmelia.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = NodePK.ROOT_NODE_ID; } } kmelia.setCurrentFolderId(topicId, true); resetWizard(kmelia); request.setAttribute("CurrentFolderId", topicId); request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis()); request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled()); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", kmelia.isTopicHaveUpdateChainDescriptor()); request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", kmelia.getUserDetail().isAccessGuest()); request.setAttribute("RightsOnTopicsEnabled", kmelia.isRightsOnTopicsEnabled()); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeviewUsed()) { destination = rootDestination + "treeview.jsp"; } else if (kmelia.isTreeStructure()) { destination = rootDestination + "oneLevel.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } else if (function.equals("GoToCurrentTopic")) { if (!NodePK.ROOT_NODE_ID.equals(kmelia.getCurrentFolderId())) { request.setAttribute("Id", kmelia.getCurrentFolderId()); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type != null && ("Publication".equals(type) || "com.stratelia.webactiv.calendar.backbone.TodoDetail".equals(type) || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { processPath(kmelia, id); if ("Attachment".equals(type)) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if ("Document".equals(type)) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { // we have to find which page contains the right publication List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); KmeliaPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getDetail().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if ("Node".equals(type)) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", kmelia, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if ("Wysiwyg".equals(type)) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", kmelia, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); kmelia.setSessionPublication(kmeliaPublication); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String id = request.getParameter("PubId"); if (StringUtil.isDefined(id)) { request.setAttribute("PubId", id); } request.setAttribute("Wizard", kmelia.getWizard()); List<NodeDetail> path = kmelia.getTopicPath(kmelia.getCurrentFolderId()); request.setAttribute("Path", path); request.setAttribute("Profile", kmelia.getProfile()); String action = (String) request.getAttribute("Action"); if (!StringUtil.isDefined(action)) { action = "UpdateView"; request.setAttribute("Action", action); } if ("UpdateView".equals(action)) { request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } else { // case of creation request.setAttribute("TaxonomyOK", true); request.setAttribute("ValidatorsOK", true); } destination = rootDestination + "publicationManager.jsp"; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK(). getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getCurrentFolder(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); KmeliaPublication kmeliaPublication = kmelia.getPublication(cloneId); kmelia.setSessionClone(kmeliaPublication); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } if (!kmaxMode) { boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath || KmeliaHelper.isToValidateFolder(kmelia.getCurrentFolderId())) { processPath(kmelia, id); } else { processPath(kmelia, null); } } KmeliaPublication kmeliaPublication = null; if (StringUtil.isDefined(id)) { kmeliaPublication = kmelia.getPublication(id, true); kmelia.setSessionPublication(kmeliaPublication); PublicationDetail pubDetail = kmeliaPublication.getDetail(); if (pubDetail.haveGotClone()) { KmeliaPublication clone = kmelia.getPublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { kmeliaPublication = kmelia.getSessionPublication(); id = kmeliaPublication.getDetail().getPK().getId(); } if (toolboxMode) { request.setAttribute("PubId", id); destination = getDestination("publicationManager.jsp", kmelia, request); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, kmeliaPublication. getDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = kmeliaPublication.getCompleteDetail().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("PubId", id); request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication()); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", kmelia.getValidationType()); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", kmelia.isWriterApproval(id)); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // check is requested publication is an alias checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("TaxonomyOK", false); request.setAttribute("ValidatorsOK", false); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK()); request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", kmelia.getRang()); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size()); } else { request.setAttribute("NbPublis", 1); } putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } // Attachments area must be displayed or not ? request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled()); // option Actualités décentralisées request.setAttribute("NewsManage", kmelia.isNewsManage()); if (kmelia.isNewsManage()) { request.setAttribute("DelegatedNews", kmelia.getDelegatedNews(id)); request .setAttribute("IsBasket", NodePK.BIN_NODE_ID.equals(kmelia.getCurrentFolderId())); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et // alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", kmelia, request); } else { String pubId = kmelia.getSessionPubliOrClone().getDetail().getPK().getId(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, kmelia, request); } else { request.setAttribute("PubId", pubId); destination = getDestination("publicationManager.jsp", kmelia, request); } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias KmeliaPublication kmeliaPublication = kmelia.getSessionPublication(); checkAlias(kmelia, kmeliaPublication); if (kmeliaPublication.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { request.setAttribute("Action", "New"); destination = getDestination("publicationManager", kmelia, request); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication String positions = FileUploadUtil.getParameter(parameters, "Positions"); PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification(); if (StringUtil.isDefined(positions)) { withClassification = PdcClassificationEntity.fromJSON(positions); } PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail, withClassification); // create vignette if exists processVignette(parameters, kmelia, pubDetail); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { KmeliaPublication kmeliaPublication = kmelia.getPublication(newPubId); kmelia.setSessionPublication(kmeliaPublication); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { KmeliaPublication kmeliaPublication = kmelia.getPublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", kmeliaPublication); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); if (toolboxMode) { request.setAttribute("Topics", kmelia.getAllTopics()); } else { List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("Components", kmelia.getComponents(aliases)); } destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); for (Alias oldAlias : oldAliases) { if (!loadedComponentIds.contains(oldAlias.getInstanceId())) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportPublications")) { String selectedIds = request.getParameter("SelectedIds"); String notSelectedIds = request.getParameter("NotSelectedIds"); List<String> ids = kmelia.processSelectedPublicationIds(selectedIds, notSelectedIds); List<WAAttributeValuePair> publicationIds = new ArrayList<WAAttributeValuePair>(); for (String id : ids) { publicationIds.add(new WAAttributeValuePair(id, kmelia.getComponentId())); } request.setAttribute("selectedResultsWa", publicationIds); kmelia.resetSelectedPublicationIds(); // Go to importExportPeas destination = "/RimportExportPeas/jsp/SelectExportMode"; } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (StringUtil.isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template request.setAttribute("Name", modelId); destination = getDestination("GoToXMLForm", kmelia, request); } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { setTemplatesUsedIntoRequest(kmelia, request); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { request.setAttribute("XMLForms", kmelia.getForms()); // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if ("ChangeTemplate".equals(function)) { kmelia.removePublicationContent(); destination = getDestination("ToPubliContent", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getDetail().getPK(). getId())) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone(). getCompleteDetail()); request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); for (FileItem item : parameters) { if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = Integer.parseInt(item.getFieldName().substring(8, item.getFieldName().length())); textDetails.add(new InfoTextDetail(null, Integer.toString(textOrder), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = Long.toString(System.currentTimeMillis()) + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if ("gif".equalsIgnoreCase(type) || "jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type)) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, Integer.toString(imageOrder), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getCompleteDetail(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); if (!StringUtil.isDefined(xmlFormName)) { xmlFormName = (String) request.getAttribute("Name"); } setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getDetail()); // Parametres du Wizard setWizardParams(request, kmelia); // template can be changed only if current topic is using at least two templates setTemplatesUsedIntoRequest(kmelia, request); @SuppressWarnings("unchecked") Collection<PublicationTemplate> templates = (Collection<PublicationTemplate>) request.getAttribute("XMLForms"); boolean wysiwygUsable = (Boolean) request.getAttribute("WysiwygValid"); request.setAttribute("IsChangingTemplateAllowed", templates.size() >= 2 || (!templates.isEmpty() && wysiwygUsable)); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate( kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia .getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getCurrentFolderId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<KmeliaPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, true, 3)); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", kmelia, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } else if (function.equals("SuggestDelegatedNews")) { String pubId = kmelia.addDelegatedNews(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); }/*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia.getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", kmelia, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", kmelia, request); } else if (function.equals("KmaxViewUnbalanced")) { List<KmeliaPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<KmeliaPublication> publications = (List<KmeliaPublication>) basket. getKmeliaPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<KmeliaPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !"X".equals(timeCriteria)) { publications = kmelia.search(combination, Integer.parseInt(timeCriteria)); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia.getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else if ("statistics".equals(function)) { destination = rootDestination + statisticRequestHandler.handleRequest(request, function, kmelia); }else if("statSelectionGroup".equals(function)) { destination = statisticRequestHandler.handleRequest(request, function, kmelia); } else { destination = rootDestination + function; } if (profileError) { destination = GeneralPropertiesManager.getString("sessionTimeout"); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
diff --git a/weasis-base/weasis-base-viewer2d/src/main/java/org/weasis/base/viewer2d/OpenImageAction.java b/weasis-base/weasis-base-viewer2d/src/main/java/org/weasis/base/viewer2d/OpenImageAction.java index fd142376..4ca8d363 100644 --- a/weasis-base/weasis-base-viewer2d/src/main/java/org/weasis/base/viewer2d/OpenImageAction.java +++ b/weasis-base/weasis-base-viewer2d/src/main/java/org/weasis/base/viewer2d/OpenImageAction.java @@ -1,96 +1,96 @@ /******************************************************************************* * Copyright (c) 2010 Nicolas Roduit. * 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: * Nicolas Roduit - initial API and implementation ******************************************************************************/ package org.weasis.base.viewer2d; import java.awt.Component; import java.awt.event.ActionEvent; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.weasis.core.api.gui.util.FileFormatFilter; import org.weasis.core.api.media.MimeInspector; import org.weasis.core.api.media.data.Codec; import org.weasis.core.api.media.data.MediaElement; import org.weasis.core.api.media.data.MediaReader; import org.weasis.core.api.media.data.MediaSeries; import org.weasis.core.api.service.BundleTools; import org.weasis.core.ui.editor.ViewerPluginBuilder; import org.weasis.core.ui.util.AbstractUIAction; public class OpenImageAction extends AbstractUIAction { /** The singleton instance of this singleton class. */ private static OpenImageAction openAction = null; /** Return the singleton instance */ public static OpenImageAction getInstance() { if (openAction == null) { openAction = new OpenImageAction(); } return openAction; } private OpenImageAction() { super("Image"); setDescription("Open image files"); } @Override public void actionPerformed(ActionEvent e) { String directory = BundleTools.LOCAL_PERSISTENCE.getProperty("last.open.image.dir", "");//$NON-NLS-1$ JFileChooser fileChooser = new JFileChooser(directory); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(true); // TODO add format from plugins FileFormatFilter.setImageDecodeFilters(fileChooser); File[] selectedFiles = null; if (fileChooser.showOpenDialog(EventManager.getInstance().getSelectedView2dContainer()) != JFileChooser.APPROVE_OPTION || (selectedFiles = fileChooser.getSelectedFiles()) == null) { return; } else { MediaSeries series = null; for (File file : selectedFiles) { String mimeType = MimeInspector.getMimeType(file); if (mimeType != null && mimeType.startsWith("image")) { Codec codec = BundleTools.getCodec(mimeType, null); if (codec != null) { MediaReader reader = codec.getMediaIO(file.toURI(), mimeType, null); if (reader != null) { if (series == null) { // TODO improve group model for image, uid for group ? series = reader.getMediaSeries(); } else { MediaElement[] elements = reader.getMediaElement(); if (elements != null) { for (MediaElement media : elements) { series.addMedia(media); } } } } } } } - if (series != null && series.size(null) > 1) { + if (series != null && series.size(null) > 0) { ViewerPluginBuilder.openSequenceInDefaultPlugin(series, ViewerPluginBuilder.DefaultDataModel, true, false); } else { Component c = e.getSource() instanceof Component ? (Component) e.getSource() : null; JOptionPane.showMessageDialog(c, "Cannot open the requested files!", getDescription(), JOptionPane.WARNING_MESSAGE); } BundleTools.LOCAL_PERSISTENCE.setProperty("last.open.image.dir", selectedFiles[0].getParent()); } } }
true
true
public void actionPerformed(ActionEvent e) { String directory = BundleTools.LOCAL_PERSISTENCE.getProperty("last.open.image.dir", "");//$NON-NLS-1$ JFileChooser fileChooser = new JFileChooser(directory); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(true); // TODO add format from plugins FileFormatFilter.setImageDecodeFilters(fileChooser); File[] selectedFiles = null; if (fileChooser.showOpenDialog(EventManager.getInstance().getSelectedView2dContainer()) != JFileChooser.APPROVE_OPTION || (selectedFiles = fileChooser.getSelectedFiles()) == null) { return; } else { MediaSeries series = null; for (File file : selectedFiles) { String mimeType = MimeInspector.getMimeType(file); if (mimeType != null && mimeType.startsWith("image")) { Codec codec = BundleTools.getCodec(mimeType, null); if (codec != null) { MediaReader reader = codec.getMediaIO(file.toURI(), mimeType, null); if (reader != null) { if (series == null) { // TODO improve group model for image, uid for group ? series = reader.getMediaSeries(); } else { MediaElement[] elements = reader.getMediaElement(); if (elements != null) { for (MediaElement media : elements) { series.addMedia(media); } } } } } } } if (series != null && series.size(null) > 1) { ViewerPluginBuilder.openSequenceInDefaultPlugin(series, ViewerPluginBuilder.DefaultDataModel, true, false); } else { Component c = e.getSource() instanceof Component ? (Component) e.getSource() : null; JOptionPane.showMessageDialog(c, "Cannot open the requested files!", getDescription(), JOptionPane.WARNING_MESSAGE); } BundleTools.LOCAL_PERSISTENCE.setProperty("last.open.image.dir", selectedFiles[0].getParent()); } }
public void actionPerformed(ActionEvent e) { String directory = BundleTools.LOCAL_PERSISTENCE.getProperty("last.open.image.dir", "");//$NON-NLS-1$ JFileChooser fileChooser = new JFileChooser(directory); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(true); // TODO add format from plugins FileFormatFilter.setImageDecodeFilters(fileChooser); File[] selectedFiles = null; if (fileChooser.showOpenDialog(EventManager.getInstance().getSelectedView2dContainer()) != JFileChooser.APPROVE_OPTION || (selectedFiles = fileChooser.getSelectedFiles()) == null) { return; } else { MediaSeries series = null; for (File file : selectedFiles) { String mimeType = MimeInspector.getMimeType(file); if (mimeType != null && mimeType.startsWith("image")) { Codec codec = BundleTools.getCodec(mimeType, null); if (codec != null) { MediaReader reader = codec.getMediaIO(file.toURI(), mimeType, null); if (reader != null) { if (series == null) { // TODO improve group model for image, uid for group ? series = reader.getMediaSeries(); } else { MediaElement[] elements = reader.getMediaElement(); if (elements != null) { for (MediaElement media : elements) { series.addMedia(media); } } } } } } } if (series != null && series.size(null) > 0) { ViewerPluginBuilder.openSequenceInDefaultPlugin(series, ViewerPluginBuilder.DefaultDataModel, true, false); } else { Component c = e.getSource() instanceof Component ? (Component) e.getSource() : null; JOptionPane.showMessageDialog(c, "Cannot open the requested files!", getDescription(), JOptionPane.WARNING_MESSAGE); } BundleTools.LOCAL_PERSISTENCE.setProperty("last.open.image.dir", selectedFiles[0].getParent()); } }
diff --git a/bohnanza.standard/src/bohnanza/standard/core/states/TurnState.java b/bohnanza.standard/src/bohnanza/standard/core/states/TurnState.java index 9c86030..d418ab8 100644 --- a/bohnanza.standard/src/bohnanza/standard/core/states/TurnState.java +++ b/bohnanza.standard/src/bohnanza/standard/core/states/TurnState.java @@ -1,95 +1,95 @@ package bohnanza.standard.core.states; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import bohnanza.standard.core.*; import bohnanza.standard.core.actions.*; public abstract class TurnState { /** * @uml.property name="actions" */ private Map<Player, List<Class<? extends Action>>> actions = new HashMap<Player, List<Class<? extends Action>>>(); /** * @uml.property name="transitions" */ private Map<Class<? extends Action>, TurnState> transitions = new HashMap<Class<? extends Action>, TurnState>(); /** * @uml.property name="context" * @uml.associationEnd inverse="currentState:main.Game" */ protected final Game context; public TurnState(final Game context) { this.context = context; for(Player player: context.getPlayers()) actions.put(player, new ArrayList<Class<? extends Action>>()); reset(); } public final void handle(Action action) throws IllegalActionException { List<Class<? extends Action>> playerActions = actions.get(action.getInitiator()); if(playerActions == null || !playerActions.contains(action.getClass())) throw new IllegalActionException("Action not permitted for this player in current state"); action.handle(); - if(handled(action)) { + if(handled(action) && transitions.containsKey(action)) { try { TurnState nextState = transitions.get(action); nextState.reset(); context.setCurrentState(nextState); } catch (Exception e) { e.printStackTrace(); } } } /** * Resets the states internal state, called when the game enters this state */ protected abstract void reset(); public List<Class<? extends Action>> getActions(Player player) { return actions.get(player); } /** * Update internal state of this TurnState, called after action was successfully executed with parameters args * @return true if action advances the game to a new TurnState */ protected abstract boolean handled(Action action); /**Adds action to the list of possible actions for initiator in the current state.*/ protected void addAction(Player initiator, Class<? extends Action> action) { actions.get(initiator).add(action); } /**Adds action to the list of possible actions for the active player in the current state.*/ protected void addAction(Class<? extends Action> action) { actions.get(context.getActivePlayer()).add(action); } /**Remove action from the list of possible actions for the active player in the current state.*/ protected void removeAction(Class<? extends Action> action) { actions.get(context.getActivePlayer()).remove(action); } /**Remove action from the list of possible actions for initiator in the current state.*/ protected void removeAction(Player initiator, Class<? extends Action> action) { actions.get(initiator).remove(action); } /**Remove all actions in the current state.*/ protected void removeAllActions() { for(List<Class<? extends Action>> playeractions: actions.values()) { playeractions.clear(); } } /**To be used only by the game factory. Adds state as the next state the game will be in if action ends the current state.*/ public void addTransition(Class<? extends Action> action, TurnState state) { transitions.put(action, state); } }
true
true
public final void handle(Action action) throws IllegalActionException { List<Class<? extends Action>> playerActions = actions.get(action.getInitiator()); if(playerActions == null || !playerActions.contains(action.getClass())) throw new IllegalActionException("Action not permitted for this player in current state"); action.handle(); if(handled(action)) { try { TurnState nextState = transitions.get(action); nextState.reset(); context.setCurrentState(nextState); } catch (Exception e) { e.printStackTrace(); } } }
public final void handle(Action action) throws IllegalActionException { List<Class<? extends Action>> playerActions = actions.get(action.getInitiator()); if(playerActions == null || !playerActions.contains(action.getClass())) throw new IllegalActionException("Action not permitted for this player in current state"); action.handle(); if(handled(action) && transitions.containsKey(action)) { try { TurnState nextState = transitions.get(action); nextState.reset(); context.setCurrentState(nextState); } catch (Exception e) { e.printStackTrace(); } } }
diff --git a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/HgRepositoryHookEvent.java b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/HgRepositoryHookEvent.java index a14b37bad..43f31694c 100644 --- a/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/HgRepositoryHookEvent.java +++ b/scm-plugins/scm-hg-plugin/src/main/java/sonia/scm/repository/HgRepositoryHookEvent.java @@ -1,170 +1,170 @@ /** * Copyright (c) 2010, Sebastian Sdorra * 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. Neither the name of SCM-Manager; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- import org.slf4j.Logger; import org.slf4j.LoggerFactory; //~--- JDK imports ------------------------------------------------------------ import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; /** * * @author Sebastian Sdorra */ public class HgRepositoryHookEvent extends AbstractRepositoryHookEvent { /** Field description */ public static final String REV_TIP = "tip"; /** the logger for HgRepositoryHookEvent */ private static final Logger logger = LoggerFactory.getLogger(HgRepositoryHookEvent.class); //~--- constructors --------------------------------------------------------- /** * Constructs ... * * * @param handler * @param repositoryName * @param startRev * @param type */ public HgRepositoryHookEvent(HgRepositoryHandler handler, String repositoryName, String startRev, RepositoryHookType type) { this.handler = handler; this.repositoryName = repositoryName; this.startRev = startRev; this.type = type; } //~--- get methods ---------------------------------------------------------- /** * Method description * * * @return */ @Override public Collection<Changeset> getChangesets() { if (changesets == null) { try { boolean pending = type == RepositoryHookType.PRE_RECEIVE; if (logger.isDebugEnabled()) { String pendingString = ""; if (pending) { pendingString = "pending "; } - logger.debug("load {}changesets for hook {}", type, pendingString); + logger.debug("load {}changesets for hook {}", pendingString, type); } changesets = createChangesetViewer().getChangesets(startRev, REV_TIP, pending); } catch (IOException ex) { logger.error("could not load changesets", ex); } } return changesets; } /** * Method description * * * @return */ @Override public RepositoryHookType getType() { return type; } //~--- methods -------------------------------------------------------------- /** * Method description * * * @return */ private HgChangesetViewer createChangesetViewer() { File directory = handler.getConfig().getRepositoryDirectory(); File repositoryDirectory = new File(directory, repositoryName); return new HgChangesetViewer(handler, repositoryDirectory.getAbsolutePath()); } //~--- fields --------------------------------------------------------------- /** Field description */ private List<Changeset> changesets; /** Field description */ private HgRepositoryHandler handler; /** Field description */ private String repositoryName; /** Field description */ private String startRev; /** Field description */ private RepositoryHookType type; }
true
true
public Collection<Changeset> getChangesets() { if (changesets == null) { try { boolean pending = type == RepositoryHookType.PRE_RECEIVE; if (logger.isDebugEnabled()) { String pendingString = ""; if (pending) { pendingString = "pending "; } logger.debug("load {}changesets for hook {}", type, pendingString); } changesets = createChangesetViewer().getChangesets(startRev, REV_TIP, pending); } catch (IOException ex) { logger.error("could not load changesets", ex); } } return changesets; }
public Collection<Changeset> getChangesets() { if (changesets == null) { try { boolean pending = type == RepositoryHookType.PRE_RECEIVE; if (logger.isDebugEnabled()) { String pendingString = ""; if (pending) { pendingString = "pending "; } logger.debug("load {}changesets for hook {}", pendingString, type); } changesets = createChangesetViewer().getChangesets(startRev, REV_TIP, pending); } catch (IOException ex) { logger.error("could not load changesets", ex); } } return changesets; }
diff --git a/src/org/mozilla/javascript/NativeGlobal.java b/src/org/mozilla/javascript/NativeGlobal.java index ff66f681..917e8369 100644 --- a/src/org/mozilla/javascript/NativeGlobal.java +++ b/src/org/mozilla/javascript/NativeGlobal.java @@ -1,827 +1,826 @@ /* -*- 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-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Mike McCabe * * 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; import java.io.Serializable; import org.mozilla.javascript.xml.XMLLib; /** * This class implements the global native object (function and value * properties only). * * See ECMA 15.1.[12]. * * @author Mike Shaver */ public class NativeGlobal implements Serializable, IdFunctionCall { static final long serialVersionUID = 6080442165748707530L; public static void init(Context cx, Scriptable scope, boolean sealed) { NativeGlobal obj = new NativeGlobal(); for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) { String name; int arity = 1; switch (id) { case Id_decodeURI: name = "decodeURI"; break; case Id_decodeURIComponent: name = "decodeURIComponent"; break; case Id_encodeURI: name = "encodeURI"; break; case Id_encodeURIComponent: name = "encodeURIComponent"; break; case Id_escape: name = "escape"; break; case Id_eval: name = "eval"; break; case Id_isFinite: name = "isFinite"; break; case Id_isNaN: name = "isNaN"; break; case Id_isXMLName: name = "isXMLName"; break; case Id_parseFloat: name = "parseFloat"; break; case Id_parseInt: name = "parseInt"; arity = 2; break; case Id_unescape: name = "unescape"; break; case Id_uneval: name = "uneval"; break; default: throw Kit.codeBug(); } IdFunctionObject f = new IdFunctionObject(obj, FTAG, id, name, arity, scope); if (sealed) { f.sealObject(); } f.exportAsScopeProperty(); } ScriptableObject.defineProperty( scope, "NaN", ScriptRuntime.NaNobj, ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "Infinity", ScriptRuntime.wrapNumber(Double.POSITIVE_INFINITY), ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "undefined", Undefined.instance, ScriptableObject.DONTENUM); String[] errorMethods = { "ConversionError", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "InternalError", "JavaException" }; /* Each error constructor gets its own Error object as a prototype, with the 'name' property set to the name of the error. */ for (int i = 0; i < errorMethods.length; i++) { String name = errorMethods[i]; - Scriptable errorProto = ScriptRuntime. - newObject(cx, scope, "Error", + ScriptableObject errorProto = + (ScriptableObject) ScriptRuntime.newObject(cx, scope, "Error", ScriptRuntime.emptyArgs); errorProto.put("name", errorProto, name); - if (sealed) { - if (errorProto instanceof ScriptableObject) { - ((ScriptableObject)errorProto).sealObject(); - } - } + errorProto.put("message", errorProto, ""); IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_new_CommonError, name, 1, scope); ctor.markAsConstructor(errorProto); + errorProto.put("constructor", errorProto, ctor); + errorProto.setAttributes("constructor", ScriptableObject.DONTENUM); if (sealed) { + errorProto.sealObject(); ctor.sealObject(); } ctor.exportAsScopeProperty(); } } public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (f.hasTag(FTAG)) { int methodId = f.methodId(); switch (methodId) { case Id_decodeURI: case Id_decodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return decode(str, methodId == Id_decodeURI); } case Id_encodeURI: case Id_encodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return encode(str, methodId == Id_encodeURI); } case Id_escape: return js_escape(args); case Id_eval: return js_eval(cx, scope, thisObj, args); case Id_isFinite: { boolean result; if (args.length < 1) { result = false; } else { double d = ScriptRuntime.toNumber(args[0]); result = (d == d && d != Double.POSITIVE_INFINITY && d != Double.NEGATIVE_INFINITY); } return ScriptRuntime.wrapBoolean(result); } case Id_isNaN: { // The global method isNaN, as per ECMA-262 15.1.2.6. boolean result; if (args.length < 1) { result = true; } else { double d = ScriptRuntime.toNumber(args[0]); result = (d != d); } return ScriptRuntime.wrapBoolean(result); } case Id_isXMLName: { Object name = (args.length == 0) ? Undefined.instance : args[0]; XMLLib xmlLib = XMLLib.extractFromScope(scope); return ScriptRuntime.wrapBoolean( xmlLib.isXMLName(cx, name)); } case Id_parseFloat: return js_parseFloat(args); case Id_parseInt: return js_parseInt(args); case Id_unescape: return js_unescape(args); case Id_uneval: { Object value = (args.length != 0) ? args[0] : Undefined.instance; return ScriptRuntime.uneval(cx, scope, value); } case Id_new_CommonError: // The implementation of all the ECMA error constructors // (SyntaxError, TypeError, etc.) return NativeError.make(cx, scope, f, args); } } throw f.unknown(); } /** * The global method parseInt, as per ECMA-262 15.1.2.2. */ private Object js_parseInt(Object[] args) { String s = ScriptRuntime.toString(args, 0); int radix = ScriptRuntime.toInt32(args, 1); int len = s.length(); if (len == 0) return ScriptRuntime.NaNobj; boolean negative = false; int start = 0; char c; do { c = s.charAt(start); if (!isStrWhiteSpaceChar(c)) break; start++; } while (start < len); if (c == '+' || (negative = (c == '-'))) start++; final int NO_RADIX = -1; if (radix == 0) { radix = NO_RADIX; } else if (radix < 2 || radix > 36) { return ScriptRuntime.NaNobj; } else if (radix == 16 && len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') start += 2; } if (radix == NO_RADIX) { radix = 10; if (len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') { radix = 16; start += 2; } else if ('0' <= c && c <= '9') { radix = 8; start++; } } } double d = ScriptRuntime.stringToNumber(s, start, radix); return ScriptRuntime.wrapNumber(negative ? -d : d); } /** * Indicates if the character is a Str whitespace char according to ECMA spec: * StrWhiteSpaceChar ::: <TAB> <SP> <NBSP> <FF> <VT> <CR> <LF> <LS> <PS> <USP> */ static boolean isStrWhiteSpaceChar(char c) { switch (c) { case '\t': // <TAB> case ' ': // <SP> case '\u00A0': // <NBSP> case '\u000C': // <FF> case '\u000B': // <VT> case '\r': // <CR> case '\n': // <LF> case '\u2028': // <LS> case '\u2029': // <PS> return true; default: return Character.getType(c) == Character.SPACE_SEPARATOR; } } /** * The global method parseFloat, as per ECMA-262 15.1.2.3. * * @param args the arguments to parseFloat, ignoring args[>=1] */ private Object js_parseFloat(Object[] args) { if (args.length < 1) return ScriptRuntime.NaNobj; String s = ScriptRuntime.toString(args[0]); int len = s.length(); int start = 0; // Scan forward to skip whitespace char c; for (;;) { if (start == len) { return ScriptRuntime.NaNobj; } c = s.charAt(start); if (!isStrWhiteSpaceChar(c)) { break; } ++start; } int i = start; if (c == '+' || c == '-') { ++i; if (i == len) { return ScriptRuntime.NaNobj; } c = s.charAt(i); } if (c == 'I') { // check for "Infinity" if (i+8 <= len && s.regionMatches(i, "Infinity", 0, 8)) { double d; if (s.charAt(start) == '-') { d = Double.NEGATIVE_INFINITY; } else { d = Double.POSITIVE_INFINITY; } return ScriptRuntime.wrapNumber(d); } return ScriptRuntime.NaNobj; } // Find the end of the legal bit int decimal = -1; int exponent = -1; for (; i < len; i++) { switch (s.charAt(i)) { case '.': if (decimal != -1) // Only allow a single decimal point. break; decimal = i; continue; case 'e': case 'E': if (exponent != -1) break; exponent = i; continue; case '+': case '-': // Only allow '+' or '-' after 'e' or 'E' if (exponent != i-1) break; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; default: break; } break; } s = s.substring(start, i); try { return Double.valueOf(s); } catch (NumberFormatException ex) { return ScriptRuntime.NaNobj; } } /** * The global method escape, as per ECMA-262 15.1.2.4. * Includes code for the 'mask' argument supported by the C escape * method, which used to be part of the browser imbedding. Blame * for the strange constant names should be directed there. */ private Object js_escape(Object[] args) { final int URL_XALPHAS = 1, URL_XPALPHAS = 2, URL_PATH = 4; String s = ScriptRuntime.toString(args, 0); int mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH; if (args.length > 1) { // the 'mask' argument. Non-ECMA. double d = ScriptRuntime.toNumber(args[1]); if (d != d || ((mask = (int) d) != d) || 0 != (mask & ~(URL_XALPHAS | URL_XPALPHAS | URL_PATH))) { throw Context.reportRuntimeError0("msg.bad.esc.mask"); } } StringBuffer sb = null; for (int k = 0, L = s.length(); k != L; ++k) { int c = s.charAt(k); if (mask != 0 && ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '@' || c == '*' || c == '_' || c == '-' || c == '.' || (0 != (mask & URL_PATH) && (c == '/' || c == '+')))) { if (sb != null) { sb.append((char)c); } } else { if (sb == null) { sb = new StringBuffer(L + 3); sb.append(s); sb.setLength(k); } int hexSize; if (c < 256) { if (c == ' ' && mask == URL_XPALPHAS) { sb.append('+'); continue; } sb.append('%'); hexSize = 2; } else { sb.append('%'); sb.append('u'); hexSize = 4; } // append hexadecimal form of c left-padded with 0 for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) { int digit = 0xf & (c >> shift); int hc = (digit < 10) ? '0' + digit : 'A' - 10 + digit; sb.append((char)hc); } } } return (sb == null) ? s : sb.toString(); } /** * The global unescape method, as per ECMA-262 15.1.2.5. */ private Object js_unescape(Object[] args) { String s = ScriptRuntime.toString(args, 0); int firstEscapePos = s.indexOf('%'); if (firstEscapePos >= 0) { int L = s.length(); char[] buf = s.toCharArray(); int destination = firstEscapePos; for (int k = firstEscapePos; k != L;) { char c = buf[k]; ++k; if (c == '%' && k != L) { int end, start; if (buf[k] == 'u') { start = k + 1; end = k + 5; } else { start = k; end = k + 2; } if (end <= L) { int x = 0; for (int i = start; i != end; ++i) { x = Kit.xDigitToInt(buf[i], x); } if (x >= 0) { c = (char)x; k = end; } } } buf[destination] = c; ++destination; } s = new String(buf, 0, destination); } return s; } private Object js_eval(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (thisObj.getParentScope() == null) { // We allow indirect calls to eval as long as the script will execute in // the global scope. return ScriptRuntime.evalSpecial(cx, scope, thisObj, args, "eval code", 1); } String m = ScriptRuntime.getMessage1("msg.cant.call.indirect", "eval"); throw NativeGlobal.constructError(cx, "EvalError", m, scope); } static boolean isEvalFunction(Object functionObj) { if (functionObj instanceof IdFunctionObject) { IdFunctionObject function = (IdFunctionObject)functionObj; if (function.hasTag(FTAG) && function.methodId() == Id_eval) { return true; } } return false; } /** * @deprecated Use {@link ScriptRuntime#constructError(String,String)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope) { return ScriptRuntime.constructError(error, message); } /** * @deprecated Use * {@link ScriptRuntime#constructError(String,String,String,int,String,int)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope, String sourceName, int lineNumber, int columnNumber, String lineSource) { return ScriptRuntime.constructError(error, message, sourceName, lineNumber, lineSource, columnNumber); } /* * ECMA 3, 15.1.3 URI Handling Function Properties * * The following are implementations of the algorithms * given in the ECMA specification for the hidden functions * 'Encode' and 'Decode'. */ private static String encode(String str, boolean fullUri) { byte[] utf8buf = null; StringBuffer sb = null; for (int k = 0, length = str.length(); k != length; ++k) { char C = str.charAt(k); if (encodeUnescaped(C, fullUri)) { if (sb != null) { sb.append(C); } } else { if (sb == null) { sb = new StringBuffer(length + 3); sb.append(str); sb.setLength(k); utf8buf = new byte[6]; } if (0xDC00 <= C && C <= 0xDFFF) { throw Context.reportRuntimeError0("msg.bad.uri"); } int V; if (C < 0xD800 || 0xDBFF < C) { V = C; } else { k++; if (k == length) { throw Context.reportRuntimeError0("msg.bad.uri"); } char C2 = str.charAt(k); if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) { throw Context.reportRuntimeError0("msg.bad.uri"); } V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000; } int L = oneUcs4ToUtf8Char(utf8buf, V); for (int j = 0; j < L; j++) { int d = 0xff & utf8buf[j]; sb.append('%'); sb.append(toHexChar(d >>> 4)); sb.append(toHexChar(d & 0xf)); } } } return (sb == null) ? str : sb.toString(); } private static char toHexChar(int i) { if (i >> 4 != 0) Kit.codeBug(); return (char)((i < 10) ? i + '0' : i - 10 + 'A'); } private static int unHex(char c) { if ('A' <= c && c <= 'F') { return c - 'A' + 10; } else if ('a' <= c && c <= 'f') { return c - 'a' + 10; } else if ('0' <= c && c <= '9') { return c - '0'; } else { return -1; } } private static int unHex(char c1, char c2) { int i1 = unHex(c1); int i2 = unHex(c2); if (i1 >= 0 && i2 >= 0) { return (i1 << 4) | i2; } return -1; } private static String decode(String str, boolean fullUri) { char[] buf = null; int bufTop = 0; for (int k = 0, length = str.length(); k != length;) { char C = str.charAt(k); if (C != '%') { if (buf != null) { buf[bufTop++] = C; } ++k; } else { if (buf == null) { // decode always compress so result can not be bigger then // str.length() buf = new char[length]; str.getChars(0, k, buf, 0); bufTop = k; } int start = k; if (k + 3 > length) throw Context.reportRuntimeError0("msg.bad.uri"); int B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0) throw Context.reportRuntimeError0("msg.bad.uri"); k += 3; if ((B & 0x80) == 0) { C = (char)B; } else { // Decode UTF-8 sequence into ucs4Char and encode it into // UTF-16 int utf8Tail, ucs4Char, minUcs4Char; if ((B & 0xC0) == 0x80) { // First UTF-8 should be ouside 0x80..0xBF throw Context.reportRuntimeError0("msg.bad.uri"); } else if ((B & 0x20) == 0) { utf8Tail = 1; ucs4Char = B & 0x1F; minUcs4Char = 0x80; } else if ((B & 0x10) == 0) { utf8Tail = 2; ucs4Char = B & 0x0F; minUcs4Char = 0x800; } else if ((B & 0x08) == 0) { utf8Tail = 3; ucs4Char = B & 0x07; minUcs4Char = 0x10000; } else if ((B & 0x04) == 0) { utf8Tail = 4; ucs4Char = B & 0x03; minUcs4Char = 0x200000; } else if ((B & 0x02) == 0) { utf8Tail = 5; ucs4Char = B & 0x01; minUcs4Char = 0x4000000; } else { // First UTF-8 can not be 0xFF or 0xFE throw Context.reportRuntimeError0("msg.bad.uri"); } if (k + 3 * utf8Tail > length) throw Context.reportRuntimeError0("msg.bad.uri"); for (int j = 0; j != utf8Tail; j++) { if (str.charAt(k) != '%') throw Context.reportRuntimeError0("msg.bad.uri"); B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0 || (B & 0xC0) != 0x80) throw Context.reportRuntimeError0("msg.bad.uri"); ucs4Char = (ucs4Char << 6) | (B & 0x3F); k += 3; } // Check for overlongs and other should-not-present codes if (ucs4Char < minUcs4Char || ucs4Char == 0xFFFE || ucs4Char == 0xFFFF) { ucs4Char = 0xFFFD; } if (ucs4Char >= 0x10000) { ucs4Char -= 0x10000; if (ucs4Char > 0xFFFFF) throw Context.reportRuntimeError0("msg.bad.uri"); char H = (char)((ucs4Char >>> 10) + 0xD800); C = (char)((ucs4Char & 0x3FF) + 0xDC00); buf[bufTop++] = H; } else { C = (char)ucs4Char; } } if (fullUri && URI_DECODE_RESERVED.indexOf(C) >= 0) { for (int x = start; x != k; x++) { buf[bufTop++] = str.charAt(x); } } else { buf[bufTop++] = C; } } } return (buf == null) ? str : new String(buf, 0, bufTop); } private static boolean encodeUnescaped(char c, boolean fullUri) { if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')) { return true; } if ("-_.!~*'()".indexOf(c) >= 0) return true; if (fullUri) { return URI_DECODE_RESERVED.indexOf(c) >= 0; } return false; } private static final String URI_DECODE_RESERVED = ";/?:@&=+$,#"; /* Convert one UCS-4 char and write it into a UTF-8 buffer, which must be * at least 6 bytes long. Return the number of UTF-8 bytes of data written. */ private static int oneUcs4ToUtf8Char(byte[] utf8Buffer, int ucs4Char) { int utf8Length = 1; //JS_ASSERT(ucs4Char <= 0x7FFFFFFF); if ((ucs4Char & ~0x7F) == 0) utf8Buffer[0] = (byte)ucs4Char; else { int i; int a = ucs4Char >>> 11; utf8Length = 2; while (a != 0) { a >>>= 5; utf8Length++; } i = utf8Length; while (--i > 0) { utf8Buffer[i] = (byte)((ucs4Char & 0x3F) | 0x80); ucs4Char >>>= 6; } utf8Buffer[0] = (byte)(0x100 - (1 << (8-utf8Length)) + ucs4Char); } return utf8Length; } private static final Object FTAG = "Global"; private static final int Id_decodeURI = 1, Id_decodeURIComponent = 2, Id_encodeURI = 3, Id_encodeURIComponent = 4, Id_escape = 5, Id_eval = 6, Id_isFinite = 7, Id_isNaN = 8, Id_isXMLName = 9, Id_parseFloat = 10, Id_parseInt = 11, Id_unescape = 12, Id_uneval = 13, LAST_SCOPE_FUNCTION_ID = 13, Id_new_CommonError = 14; }
false
true
public static void init(Context cx, Scriptable scope, boolean sealed) { NativeGlobal obj = new NativeGlobal(); for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) { String name; int arity = 1; switch (id) { case Id_decodeURI: name = "decodeURI"; break; case Id_decodeURIComponent: name = "decodeURIComponent"; break; case Id_encodeURI: name = "encodeURI"; break; case Id_encodeURIComponent: name = "encodeURIComponent"; break; case Id_escape: name = "escape"; break; case Id_eval: name = "eval"; break; case Id_isFinite: name = "isFinite"; break; case Id_isNaN: name = "isNaN"; break; case Id_isXMLName: name = "isXMLName"; break; case Id_parseFloat: name = "parseFloat"; break; case Id_parseInt: name = "parseInt"; arity = 2; break; case Id_unescape: name = "unescape"; break; case Id_uneval: name = "uneval"; break; default: throw Kit.codeBug(); } IdFunctionObject f = new IdFunctionObject(obj, FTAG, id, name, arity, scope); if (sealed) { f.sealObject(); } f.exportAsScopeProperty(); } ScriptableObject.defineProperty( scope, "NaN", ScriptRuntime.NaNobj, ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "Infinity", ScriptRuntime.wrapNumber(Double.POSITIVE_INFINITY), ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "undefined", Undefined.instance, ScriptableObject.DONTENUM); String[] errorMethods = { "ConversionError", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "InternalError", "JavaException" }; /* Each error constructor gets its own Error object as a prototype, with the 'name' property set to the name of the error. */ for (int i = 0; i < errorMethods.length; i++) { String name = errorMethods[i]; Scriptable errorProto = ScriptRuntime. newObject(cx, scope, "Error", ScriptRuntime.emptyArgs); errorProto.put("name", errorProto, name); if (sealed) { if (errorProto instanceof ScriptableObject) { ((ScriptableObject)errorProto).sealObject(); } } IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_new_CommonError, name, 1, scope); ctor.markAsConstructor(errorProto); if (sealed) { ctor.sealObject(); } ctor.exportAsScopeProperty(); } }
public static void init(Context cx, Scriptable scope, boolean sealed) { NativeGlobal obj = new NativeGlobal(); for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) { String name; int arity = 1; switch (id) { case Id_decodeURI: name = "decodeURI"; break; case Id_decodeURIComponent: name = "decodeURIComponent"; break; case Id_encodeURI: name = "encodeURI"; break; case Id_encodeURIComponent: name = "encodeURIComponent"; break; case Id_escape: name = "escape"; break; case Id_eval: name = "eval"; break; case Id_isFinite: name = "isFinite"; break; case Id_isNaN: name = "isNaN"; break; case Id_isXMLName: name = "isXMLName"; break; case Id_parseFloat: name = "parseFloat"; break; case Id_parseInt: name = "parseInt"; arity = 2; break; case Id_unescape: name = "unescape"; break; case Id_uneval: name = "uneval"; break; default: throw Kit.codeBug(); } IdFunctionObject f = new IdFunctionObject(obj, FTAG, id, name, arity, scope); if (sealed) { f.sealObject(); } f.exportAsScopeProperty(); } ScriptableObject.defineProperty( scope, "NaN", ScriptRuntime.NaNobj, ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "Infinity", ScriptRuntime.wrapNumber(Double.POSITIVE_INFINITY), ScriptableObject.DONTENUM); ScriptableObject.defineProperty( scope, "undefined", Undefined.instance, ScriptableObject.DONTENUM); String[] errorMethods = { "ConversionError", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "InternalError", "JavaException" }; /* Each error constructor gets its own Error object as a prototype, with the 'name' property set to the name of the error. */ for (int i = 0; i < errorMethods.length; i++) { String name = errorMethods[i]; ScriptableObject errorProto = (ScriptableObject) ScriptRuntime.newObject(cx, scope, "Error", ScriptRuntime.emptyArgs); errorProto.put("name", errorProto, name); errorProto.put("message", errorProto, ""); IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_new_CommonError, name, 1, scope); ctor.markAsConstructor(errorProto); errorProto.put("constructor", errorProto, ctor); errorProto.setAttributes("constructor", ScriptableObject.DONTENUM); if (sealed) { errorProto.sealObject(); ctor.sealObject(); } ctor.exportAsScopeProperty(); } }
diff --git a/jbpm-flow/src/main/java/org/jbpm/marshalling/impl/AbstractProtobufProcessInstanceMarshaller.java b/jbpm-flow/src/main/java/org/jbpm/marshalling/impl/AbstractProtobufProcessInstanceMarshaller.java index 356111715..c7ec218fd 100644 --- a/jbpm-flow/src/main/java/org/jbpm/marshalling/impl/AbstractProtobufProcessInstanceMarshaller.java +++ b/jbpm-flow/src/main/java/org/jbpm/marshalling/impl/AbstractProtobufProcessInstanceMarshaller.java @@ -1,604 +1,604 @@ /** * Copyright 2010 JBoss 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.jbpm.marshalling.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.common.InternalRuleBase; import org.drools.common.InternalWorkingMemory; import org.drools.definition.process.Process; import org.drools.marshalling.impl.MarshallerReaderContext; import org.drools.marshalling.impl.MarshallerWriteContext; import org.drools.marshalling.impl.PersisterHelper; import org.drools.marshalling.impl.ProtobufMessages.Header; import org.drools.runtime.process.NodeInstance; import org.drools.runtime.process.NodeInstanceContainer; import org.drools.runtime.process.ProcessInstance; import org.drools.runtime.process.WorkflowProcessInstance; import org.jbpm.marshalling.impl.JBPMMessages.ProcessInstance.NodeInstanceContent; import org.jbpm.marshalling.impl.JBPMMessages.ProcessInstance.NodeInstanceType; import org.jbpm.process.core.Context; import org.jbpm.process.core.context.exclusive.ExclusiveGroup; import org.jbpm.process.core.context.swimlane.SwimlaneContext; import org.jbpm.process.core.context.variable.VariableScope; import org.jbpm.process.instance.ContextInstance; import org.jbpm.process.instance.context.exclusive.ExclusiveGroupInstance; import org.jbpm.process.instance.context.swimlane.SwimlaneContextInstance; import org.jbpm.process.instance.context.variable.VariableScopeInstance; import org.jbpm.workflow.instance.impl.NodeInstanceImpl; import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl; import org.jbpm.workflow.instance.node.CompositeContextNodeInstance; import org.jbpm.workflow.instance.node.DynamicNodeInstance; import org.jbpm.workflow.instance.node.EventNodeInstance; import org.jbpm.workflow.instance.node.ForEachNodeInstance; import org.jbpm.workflow.instance.node.HumanTaskNodeInstance; import org.jbpm.workflow.instance.node.JoinInstance; import org.jbpm.workflow.instance.node.MilestoneNodeInstance; import org.jbpm.workflow.instance.node.RuleSetNodeInstance; import org.jbpm.workflow.instance.node.StateNodeInstance; import org.jbpm.workflow.instance.node.SubProcessNodeInstance; import org.jbpm.workflow.instance.node.TimerNodeInstance; import org.jbpm.workflow.instance.node.WorkItemNodeInstance; import com.google.protobuf.ExtensionRegistry; /** * Default implementation of a process instance marshaller. * */ public abstract class AbstractProtobufProcessInstanceMarshaller implements ProcessInstanceMarshaller { // Output methods public JBPMMessages.ProcessInstance writeProcessInstance(MarshallerWriteContext context, ProcessInstance processInstance) throws IOException { WorkflowProcessInstanceImpl workFlow = (WorkflowProcessInstanceImpl) processInstance; JBPMMessages.ProcessInstance.Builder _instance = JBPMMessages.ProcessInstance.newBuilder() .setId( workFlow.getId() ) .setProcessId( workFlow.getProcessId() ) .setState( workFlow.getState() ) .setNodeInstanceCounter( workFlow.getNodeInstanceCounter() ) .setProcessType( workFlow.getProcess().getType() ); SwimlaneContextInstance swimlaneContextInstance = (SwimlaneContextInstance) workFlow.getContextInstance( SwimlaneContext.SWIMLANE_SCOPE ); if ( swimlaneContextInstance != null ) { Map<String, String> swimlaneActors = swimlaneContextInstance.getSwimlaneActors(); for ( Map.Entry<String, String> entry : swimlaneActors.entrySet() ) { _instance.addSwimlaneContext( JBPMMessages.ProcessInstance.SwimlaneContextInstance.newBuilder() .setSwimlane( entry.getKey() ) .setActorId( entry.getValue() ) .build() ); } } List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>( workFlow.getNodeInstances() ); Collections.sort( nodeInstances, new Comparator<NodeInstance>() { public int compare(NodeInstance o1, NodeInstance o2) { return (int) (o1.getId() - o2.getId()); } } ); for ( NodeInstance nodeInstance : nodeInstances ) { _instance.addNodeInstance( writeNodeInstance( context, nodeInstance ) ); } List<ContextInstance> exclusiveGroupInstances = workFlow.getContextInstances( ExclusiveGroup.EXCLUSIVE_GROUP ); if ( exclusiveGroupInstances != null ) { for ( ContextInstance contextInstance : exclusiveGroupInstances ) { JBPMMessages.ProcessInstance.ExclusiveGroupInstance.Builder _exclusive = JBPMMessages.ProcessInstance.ExclusiveGroupInstance.newBuilder(); ExclusiveGroupInstance exclusiveGroupInstance = (ExclusiveGroupInstance) contextInstance; Collection<NodeInstance> groupNodeInstances = exclusiveGroupInstance.getNodeInstances(); for ( NodeInstance nodeInstance : groupNodeInstances ) { _exclusive.addGroupNodeInstanceId( nodeInstance.getId() ); } _instance.addExclusiveGroup( _exclusive.build() ); } } VariableScopeInstance variableScopeInstance = (VariableScopeInstance) workFlow.getContextInstance( VariableScope.VARIABLE_SCOPE ); List<Map.Entry<String, Object>> variables = new ArrayList<Map.Entry<String, Object>>( variableScopeInstance.getVariables().entrySet() ); Collections.sort( variables, new Comparator<Map.Entry<String, Object>>() { public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) { return o1.getKey().compareTo( o2.getKey() ); } } ); for ( Map.Entry<String, Object> variable : variables ) { if ( variable.getValue() != null ) { _instance.addVariable( ProtobufProcessMarshaller.marshallVariable( context, variable.getKey(), variable.getValue() ) ); } } return _instance.build(); } public JBPMMessages.ProcessInstance.NodeInstance writeNodeInstance(MarshallerWriteContext context, NodeInstance nodeInstance) throws IOException { JBPMMessages.ProcessInstance.NodeInstance.Builder _node = JBPMMessages.ProcessInstance.NodeInstance.newBuilder() .setId( nodeInstance.getId() ) .setNodeId( nodeInstance.getNodeId() ); _node.setContent( writeNodeInstanceContent( _node, nodeInstance, context ) ); return _node.build(); } protected JBPMMessages.ProcessInstance.NodeInstanceContent writeNodeInstanceContent(JBPMMessages.ProcessInstance.NodeInstance.Builder _node, NodeInstance nodeInstance, MarshallerWriteContext context) throws IOException { JBPMMessages.ProcessInstance.NodeInstanceContent.Builder _content = null; if ( nodeInstance instanceof RuleSetNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.RULE_SET_NODE ); List<Long> timerInstances = ((RuleSetNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { JBPMMessages.ProcessInstance.NodeInstanceContent.RuleSetNode.Builder _ruleSet = JBPMMessages.ProcessInstance.NodeInstanceContent.RuleSetNode.newBuilder(); for ( Long id : timerInstances ) { _ruleSet.addTimerInstanceId( id ); } _content.setRuleSet( _ruleSet.build() ); } } else if ( nodeInstance instanceof HumanTaskNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.HumanTaskNode.Builder _task = JBPMMessages.ProcessInstance.NodeInstanceContent.HumanTaskNode.newBuilder() .setWorkItemId( ((HumanTaskNodeInstance) nodeInstance).getWorkItemId() ); List<Long> timerInstances = ((HumanTaskNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _task.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.HUMAN_TASK_NODE ) .setHumanTask( _task.build() ); } else if ( nodeInstance instanceof WorkItemNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.WorkItemNode.Builder _wi = JBPMMessages.ProcessInstance.NodeInstanceContent.WorkItemNode.newBuilder() .setWorkItemId( ((WorkItemNodeInstance) nodeInstance).getWorkItemId() ); List<Long> timerInstances = ((WorkItemNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _wi.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.WORK_ITEM_NODE ) .setWorkItem( _wi.build() ); } else if ( nodeInstance instanceof SubProcessNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.SubProcessNode.Builder _sp = JBPMMessages.ProcessInstance.NodeInstanceContent.SubProcessNode.newBuilder() .setProcessInstanceId( ((SubProcessNodeInstance) nodeInstance).getProcessInstanceId() ); List<Long> timerInstances = ((SubProcessNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _sp.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.SUBPROCESS_NODE ) .setSubProcess( _sp.build() ); } else if ( nodeInstance instanceof MilestoneNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.MilestoneNode.Builder _ms = JBPMMessages.ProcessInstance.NodeInstanceContent.MilestoneNode.newBuilder(); List<Long> timerInstances = ((MilestoneNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _ms.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.MILESTONE_NODE ) .setMilestone( _ms.build() ); } else if ( nodeInstance instanceof EventNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.EVENT_NODE ); } else if ( nodeInstance instanceof TimerNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.TIMER_NODE ) .setTimer( JBPMMessages.ProcessInstance.NodeInstanceContent.TimerNode.newBuilder() .setTimerId( ((TimerNodeInstance) nodeInstance).getTimerId() ) .build() ); } else if ( nodeInstance instanceof JoinInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.Builder _join = JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.newBuilder(); Map<Long, Integer> triggers = ((JoinInstance) nodeInstance).getTriggers(); List<Long> keys = new ArrayList<Long>( triggers.keySet() ); Collections.sort( keys, new Comparator<Long>() { public int compare(Long o1, Long o2) { return o1.compareTo( o2 ); } } ); for ( Long key : keys ) { _join.addTrigger( JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.JoinTrigger.newBuilder() .setNodeId( key ) .setCounter( triggers.get( key ) ) .build() ); } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.JOIN_NODE ) .setJoin( _join.build() ); } else if ( nodeInstance instanceof StateNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.StateNode.Builder _state = JBPMMessages.ProcessInstance.NodeInstanceContent.StateNode.newBuilder(); List<Long> timerInstances = ((StateNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _state.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.STATE_NODE ) .setState( _state.build() ); } else if ( nodeInstance instanceof CompositeContextNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.CompositeContextNode.Builder _composite = JBPMMessages.ProcessInstance.NodeInstanceContent.CompositeContextNode.newBuilder(); JBPMMessages.ProcessInstance.NodeInstanceType _type = ( nodeInstance instanceof DynamicNodeInstance ) ? JBPMMessages.ProcessInstance.NodeInstanceType.DYNAMIC_NODE : JBPMMessages.ProcessInstance.NodeInstanceType.COMPOSITE_CONTEXT_NODE; CompositeContextNodeInstance compositeNodeInstance = (CompositeContextNodeInstance) nodeInstance; List<Long> timerInstances = ((CompositeContextNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _composite.addTimerInstanceId( id ); } } VariableScopeInstance variableScopeInstance = (VariableScopeInstance) compositeNodeInstance.getContextInstance( VariableScope.VARIABLE_SCOPE ); if ( variableScopeInstance != null ) { List<Map.Entry<String, Object>> variables = new ArrayList<Map.Entry<String, Object>>( variableScopeInstance.getVariables().entrySet() ); Collections.sort( variables, new Comparator<Map.Entry<String, Object>>() { public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) { return o1.getKey().compareTo( o2.getKey() ); } } ); for ( Map.Entry<String, Object> variable : variables ) { - _composite.addVariable( ProtobufProcessMarshaller.marshallVariableSerializableStrategy( context, variable.getKey(), variable.getValue() ) ); + _composite.addVariable( ProtobufProcessMarshaller.marshallVariable( context, variable.getKey(), variable.getValue() ) ); } } List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>( compositeNodeInstance.getNodeInstances() ); Collections.sort( nodeInstances, new Comparator<NodeInstance>() { public int compare(NodeInstance o1, NodeInstance o2) { return (int) (o1.getId() - o2.getId()); } } ); for ( NodeInstance subNodeInstance : nodeInstances ) { _composite.addNodeInstance( writeNodeInstance( context, subNodeInstance ) ); } List<ContextInstance> exclusiveGroupInstances = compositeNodeInstance.getContextInstances( ExclusiveGroup.EXCLUSIVE_GROUP ); if ( exclusiveGroupInstances != null ) { for ( ContextInstance contextInstance : exclusiveGroupInstances ) { JBPMMessages.ProcessInstance.ExclusiveGroupInstance.Builder _excl = JBPMMessages.ProcessInstance.ExclusiveGroupInstance.newBuilder(); ExclusiveGroupInstance exclusiveGroupInstance = (ExclusiveGroupInstance) contextInstance; Collection<NodeInstance> groupNodeInstances = exclusiveGroupInstance.getNodeInstances(); for ( NodeInstance groupNodeInstance : groupNodeInstances ) { _excl.addGroupNodeInstanceId( groupNodeInstance.getId() ); } _composite.addExclusiveGroup( _excl.build() ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( _type ) .setComposite( _composite.build() ); } else if ( nodeInstance instanceof ForEachNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.ForEachNode.Builder _foreach = JBPMMessages.ProcessInstance.NodeInstanceContent.ForEachNode.newBuilder(); ForEachNodeInstance forEachNodeInstance = (ForEachNodeInstance) nodeInstance; List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>( forEachNodeInstance.getNodeInstances() ); Collections.sort( nodeInstances, new Comparator<NodeInstance>() { public int compare(NodeInstance o1, NodeInstance o2) { return (int) (o1.getId() - o2.getId()); } } ); for ( NodeInstance subNodeInstance : nodeInstances ) { if ( subNodeInstance instanceof CompositeContextNodeInstance ) { _foreach.addNodeInstance( writeNodeInstance( context, subNodeInstance ) ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.FOR_EACH_NODE ) .setForEach( _foreach.build() ); } else { throw new IllegalArgumentException( "Unknown node instance type: " + nodeInstance ); } return _content.build(); } // Input methods public ProcessInstance readProcessInstance(MarshallerReaderContext context) throws IOException { InternalRuleBase ruleBase = context.ruleBase; InternalWorkingMemory wm = context.wm; JBPMMessages.ProcessInstance _instance = (org.jbpm.marshalling.impl.JBPMMessages.ProcessInstance) context.parameterObject; if( _instance == null ) { // try to parse from the stream ExtensionRegistry registry = PersisterHelper.buildRegistry( context, null ); Header _header = PersisterHelper.readFromStreamWithHeader( context, registry ); _instance = JBPMMessages.ProcessInstance.parseFrom( _header.getPayload(), registry ); } WorkflowProcessInstanceImpl processInstance = createProcessInstance(); processInstance.setId( _instance.getId() ); String processId = _instance.getProcessId(); processInstance.setProcessId( processId ); Process process = ruleBase.getProcess( processId ); if ( ruleBase != null ) { processInstance.setProcess( process ); } processInstance.setState( _instance.getState() ); long nodeInstanceCounter = _instance.getNodeInstanceCounter(); processInstance.setKnowledgeRuntime( wm.getKnowledgeRuntime() ); if ( _instance.getSwimlaneContextCount() > 0 ) { Context swimlaneContext = ((org.jbpm.process.core.Process) process).getDefaultContext( SwimlaneContext.SWIMLANE_SCOPE ); SwimlaneContextInstance swimlaneContextInstance = (SwimlaneContextInstance) processInstance.getContextInstance( swimlaneContext ); for ( JBPMMessages.ProcessInstance.SwimlaneContextInstance _swimlane : _instance.getSwimlaneContextList() ) { swimlaneContextInstance.setActorId( _swimlane.getSwimlane(), _swimlane.getActorId() ); } } for ( JBPMMessages.ProcessInstance.NodeInstance _node : _instance.getNodeInstanceList() ) { context.parameterObject = _node; readNodeInstance( context, processInstance, processInstance ); } for ( JBPMMessages.ProcessInstance.ExclusiveGroupInstance _excl : _instance.getExclusiveGroupList() ) { ExclusiveGroupInstance exclusiveGroupInstance = new ExclusiveGroupInstance(); processInstance.addContextInstance( ExclusiveGroup.EXCLUSIVE_GROUP, exclusiveGroupInstance ); for ( Long nodeInstanceId : _excl.getGroupNodeInstanceIdList() ) { NodeInstance nodeInstance = processInstance.getNodeInstance( nodeInstanceId ); if ( nodeInstance == null ) { throw new IllegalArgumentException( "Could not find node instance when deserializing exclusive group instance: " + nodeInstanceId ); } exclusiveGroupInstance.addNodeInstance( nodeInstance ); } } if ( _instance.getVariableCount() > 0 ) { Context variableScope = ((org.jbpm.process.core.Process) process) .getDefaultContext( VariableScope.VARIABLE_SCOPE ); VariableScopeInstance variableScopeInstance = (VariableScopeInstance) processInstance .getContextInstance( variableScope ); for ( JBPMMessages.Variable _variable : _instance.getVariableList() ) { try { Object _value = ProtobufProcessMarshaller.unmarshallVariableValue( context, _variable ); variableScopeInstance.internalSetVariable( _variable.getName(), _value ); } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException( "Could not reload variable " + _variable.getName() ); } } } processInstance.internalSetNodeInstanceCounter( nodeInstanceCounter ); if ( wm != null ) { processInstance.reconnect(); } return processInstance; } protected abstract WorkflowProcessInstanceImpl createProcessInstance(); public NodeInstance readNodeInstance(MarshallerReaderContext context, NodeInstanceContainer nodeInstanceContainer, WorkflowProcessInstance processInstance) throws IOException { JBPMMessages.ProcessInstance.NodeInstance _node = (JBPMMessages.ProcessInstance.NodeInstance) context.parameterObject; NodeInstanceImpl nodeInstance = readNodeInstanceContent( _node, context, processInstance ); nodeInstance.setNodeId( _node.getNodeId() ); nodeInstance.setNodeInstanceContainer( nodeInstanceContainer ); nodeInstance.setProcessInstance( (org.jbpm.workflow.instance.WorkflowProcessInstance) processInstance ); nodeInstance.setId( _node.getId() ); switch ( _node.getContent().getType() ) { case COMPOSITE_CONTEXT_NODE : case DYNAMIC_NODE : if ( _node.getContent().getComposite().getVariableCount() > 0 ) { Context variableScope = ((org.jbpm.process.core.Process) ((org.jbpm.process.instance.ProcessInstance) processInstance).getProcess()).getDefaultContext( VariableScope.VARIABLE_SCOPE ); VariableScopeInstance variableScopeInstance = (VariableScopeInstance) ((CompositeContextNodeInstance) nodeInstance).getContextInstance( variableScope ); for ( JBPMMessages.Variable _variable : _node.getContent().getComposite().getVariableList() ) { try { Object _value = ProtobufProcessMarshaller.unmarshallVariableValue( context, _variable ); variableScopeInstance.internalSetVariable( _variable.getName(), _value ); } catch ( ClassNotFoundException e ) { throw new IllegalArgumentException( "Could not reload variable " + _variable.getName() ); } } } for ( JBPMMessages.ProcessInstance.NodeInstance _instance : _node.getContent().getComposite().getNodeInstanceList() ) { context.parameterObject = _instance; readNodeInstance( context, (CompositeContextNodeInstance) nodeInstance, processInstance ); } for ( JBPMMessages.ProcessInstance.ExclusiveGroupInstance _excl : _node.getContent().getComposite().getExclusiveGroupList() ) { ExclusiveGroupInstance exclusiveGroupInstance = new ExclusiveGroupInstance(); ((org.jbpm.process.instance.ProcessInstance) processInstance).addContextInstance( ExclusiveGroup.EXCLUSIVE_GROUP, exclusiveGroupInstance ); for ( Long nodeInstanceId : _excl.getGroupNodeInstanceIdList() ) { NodeInstance groupNodeInstance = processInstance.getNodeInstance( nodeInstanceId ); if ( groupNodeInstance == null ) { throw new IllegalArgumentException( "Could not find node instance when deserializing exclusive group instance: " + nodeInstanceId ); } exclusiveGroupInstance.addNodeInstance( groupNodeInstance ); } } break; case FOR_EACH_NODE : for ( JBPMMessages.ProcessInstance.NodeInstance _instance : _node.getContent().getForEach().getNodeInstanceList() ) { context.parameterObject = _instance; readNodeInstance( context, (ForEachNodeInstance) nodeInstance, processInstance ); } break; default : // do nothing } return nodeInstance; } protected NodeInstanceImpl readNodeInstanceContent(JBPMMessages.ProcessInstance.NodeInstance _node, MarshallerReaderContext context, WorkflowProcessInstance processInstance) throws IOException { NodeInstanceImpl nodeInstance = null; NodeInstanceContent _content = _node.getContent(); switch ( _content.getType() ) { case RULE_SET_NODE: nodeInstance = new RuleSetNodeInstance(); if ( _content.getRuleSet().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getRuleSet().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((RuleSetNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; case HUMAN_TASK_NODE : nodeInstance = new HumanTaskNodeInstance(); ((HumanTaskNodeInstance) nodeInstance).internalSetWorkItemId( _content.getHumanTask().getWorkItemId() ); if ( _content.getHumanTask().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getHumanTask().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((HumanTaskNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; case WORK_ITEM_NODE : nodeInstance = new WorkItemNodeInstance(); ((WorkItemNodeInstance) nodeInstance).internalSetWorkItemId( _content.getWorkItem().getWorkItemId() ); if ( _content.getWorkItem().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getWorkItem().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((WorkItemNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; case SUBPROCESS_NODE : nodeInstance = new SubProcessNodeInstance(); ((SubProcessNodeInstance) nodeInstance).internalSetProcessInstanceId( _content.getSubProcess().getProcessInstanceId() ); if ( _content.getSubProcess().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getSubProcess().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((SubProcessNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; case MILESTONE_NODE : nodeInstance = new MilestoneNodeInstance(); if ( _content.getMilestone().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getMilestone().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((MilestoneNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; case TIMER_NODE : nodeInstance = new TimerNodeInstance(); ((TimerNodeInstance) nodeInstance).internalSetTimerId( _content.getTimer().getTimerId() ); break; case EVENT_NODE : nodeInstance = new EventNodeInstance(); break; case JOIN_NODE : nodeInstance = new JoinInstance(); if ( _content.getJoin().getTriggerCount() > 0 ) { Map<Long, Integer> triggers = new HashMap<Long, Integer>(); for ( JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.JoinTrigger _join : _content.getJoin().getTriggerList() ) { triggers.put( _join.getNodeId(), _join.getCounter() ); } ((JoinInstance) nodeInstance).internalSetTriggers( triggers ); } break; case COMPOSITE_CONTEXT_NODE : nodeInstance = new CompositeContextNodeInstance(); if ( _content.getComposite().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getComposite().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((CompositeContextNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; case FOR_EACH_NODE : nodeInstance = new ForEachNodeInstance(); break; case DYNAMIC_NODE : nodeInstance = new DynamicNodeInstance(); if ( _content.getComposite().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getComposite().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((CompositeContextNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; case STATE_NODE : nodeInstance = new StateNodeInstance(); if ( _content.getState().getTimerInstanceIdCount() > 0 ) { List<Long> timerInstances = new ArrayList<Long>(); for ( Long _timerId : _content.getState().getTimerInstanceIdList() ) { timerInstances.add( _timerId ); } ((CompositeContextNodeInstance) nodeInstance).internalSetTimerInstances( timerInstances ); } break; default : throw new IllegalArgumentException( "Unknown node type: " + _content.getType() ); } return nodeInstance; } }
true
true
protected JBPMMessages.ProcessInstance.NodeInstanceContent writeNodeInstanceContent(JBPMMessages.ProcessInstance.NodeInstance.Builder _node, NodeInstance nodeInstance, MarshallerWriteContext context) throws IOException { JBPMMessages.ProcessInstance.NodeInstanceContent.Builder _content = null; if ( nodeInstance instanceof RuleSetNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.RULE_SET_NODE ); List<Long> timerInstances = ((RuleSetNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { JBPMMessages.ProcessInstance.NodeInstanceContent.RuleSetNode.Builder _ruleSet = JBPMMessages.ProcessInstance.NodeInstanceContent.RuleSetNode.newBuilder(); for ( Long id : timerInstances ) { _ruleSet.addTimerInstanceId( id ); } _content.setRuleSet( _ruleSet.build() ); } } else if ( nodeInstance instanceof HumanTaskNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.HumanTaskNode.Builder _task = JBPMMessages.ProcessInstance.NodeInstanceContent.HumanTaskNode.newBuilder() .setWorkItemId( ((HumanTaskNodeInstance) nodeInstance).getWorkItemId() ); List<Long> timerInstances = ((HumanTaskNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _task.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.HUMAN_TASK_NODE ) .setHumanTask( _task.build() ); } else if ( nodeInstance instanceof WorkItemNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.WorkItemNode.Builder _wi = JBPMMessages.ProcessInstance.NodeInstanceContent.WorkItemNode.newBuilder() .setWorkItemId( ((WorkItemNodeInstance) nodeInstance).getWorkItemId() ); List<Long> timerInstances = ((WorkItemNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _wi.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.WORK_ITEM_NODE ) .setWorkItem( _wi.build() ); } else if ( nodeInstance instanceof SubProcessNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.SubProcessNode.Builder _sp = JBPMMessages.ProcessInstance.NodeInstanceContent.SubProcessNode.newBuilder() .setProcessInstanceId( ((SubProcessNodeInstance) nodeInstance).getProcessInstanceId() ); List<Long> timerInstances = ((SubProcessNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _sp.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.SUBPROCESS_NODE ) .setSubProcess( _sp.build() ); } else if ( nodeInstance instanceof MilestoneNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.MilestoneNode.Builder _ms = JBPMMessages.ProcessInstance.NodeInstanceContent.MilestoneNode.newBuilder(); List<Long> timerInstances = ((MilestoneNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _ms.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.MILESTONE_NODE ) .setMilestone( _ms.build() ); } else if ( nodeInstance instanceof EventNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.EVENT_NODE ); } else if ( nodeInstance instanceof TimerNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.TIMER_NODE ) .setTimer( JBPMMessages.ProcessInstance.NodeInstanceContent.TimerNode.newBuilder() .setTimerId( ((TimerNodeInstance) nodeInstance).getTimerId() ) .build() ); } else if ( nodeInstance instanceof JoinInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.Builder _join = JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.newBuilder(); Map<Long, Integer> triggers = ((JoinInstance) nodeInstance).getTriggers(); List<Long> keys = new ArrayList<Long>( triggers.keySet() ); Collections.sort( keys, new Comparator<Long>() { public int compare(Long o1, Long o2) { return o1.compareTo( o2 ); } } ); for ( Long key : keys ) { _join.addTrigger( JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.JoinTrigger.newBuilder() .setNodeId( key ) .setCounter( triggers.get( key ) ) .build() ); } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.JOIN_NODE ) .setJoin( _join.build() ); } else if ( nodeInstance instanceof StateNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.StateNode.Builder _state = JBPMMessages.ProcessInstance.NodeInstanceContent.StateNode.newBuilder(); List<Long> timerInstances = ((StateNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _state.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.STATE_NODE ) .setState( _state.build() ); } else if ( nodeInstance instanceof CompositeContextNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.CompositeContextNode.Builder _composite = JBPMMessages.ProcessInstance.NodeInstanceContent.CompositeContextNode.newBuilder(); JBPMMessages.ProcessInstance.NodeInstanceType _type = ( nodeInstance instanceof DynamicNodeInstance ) ? JBPMMessages.ProcessInstance.NodeInstanceType.DYNAMIC_NODE : JBPMMessages.ProcessInstance.NodeInstanceType.COMPOSITE_CONTEXT_NODE; CompositeContextNodeInstance compositeNodeInstance = (CompositeContextNodeInstance) nodeInstance; List<Long> timerInstances = ((CompositeContextNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _composite.addTimerInstanceId( id ); } } VariableScopeInstance variableScopeInstance = (VariableScopeInstance) compositeNodeInstance.getContextInstance( VariableScope.VARIABLE_SCOPE ); if ( variableScopeInstance != null ) { List<Map.Entry<String, Object>> variables = new ArrayList<Map.Entry<String, Object>>( variableScopeInstance.getVariables().entrySet() ); Collections.sort( variables, new Comparator<Map.Entry<String, Object>>() { public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) { return o1.getKey().compareTo( o2.getKey() ); } } ); for ( Map.Entry<String, Object> variable : variables ) { _composite.addVariable( ProtobufProcessMarshaller.marshallVariableSerializableStrategy( context, variable.getKey(), variable.getValue() ) ); } } List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>( compositeNodeInstance.getNodeInstances() ); Collections.sort( nodeInstances, new Comparator<NodeInstance>() { public int compare(NodeInstance o1, NodeInstance o2) { return (int) (o1.getId() - o2.getId()); } } ); for ( NodeInstance subNodeInstance : nodeInstances ) { _composite.addNodeInstance( writeNodeInstance( context, subNodeInstance ) ); } List<ContextInstance> exclusiveGroupInstances = compositeNodeInstance.getContextInstances( ExclusiveGroup.EXCLUSIVE_GROUP ); if ( exclusiveGroupInstances != null ) { for ( ContextInstance contextInstance : exclusiveGroupInstances ) { JBPMMessages.ProcessInstance.ExclusiveGroupInstance.Builder _excl = JBPMMessages.ProcessInstance.ExclusiveGroupInstance.newBuilder(); ExclusiveGroupInstance exclusiveGroupInstance = (ExclusiveGroupInstance) contextInstance; Collection<NodeInstance> groupNodeInstances = exclusiveGroupInstance.getNodeInstances(); for ( NodeInstance groupNodeInstance : groupNodeInstances ) { _excl.addGroupNodeInstanceId( groupNodeInstance.getId() ); } _composite.addExclusiveGroup( _excl.build() ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( _type ) .setComposite( _composite.build() ); } else if ( nodeInstance instanceof ForEachNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.ForEachNode.Builder _foreach = JBPMMessages.ProcessInstance.NodeInstanceContent.ForEachNode.newBuilder(); ForEachNodeInstance forEachNodeInstance = (ForEachNodeInstance) nodeInstance; List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>( forEachNodeInstance.getNodeInstances() ); Collections.sort( nodeInstances, new Comparator<NodeInstance>() { public int compare(NodeInstance o1, NodeInstance o2) { return (int) (o1.getId() - o2.getId()); } } ); for ( NodeInstance subNodeInstance : nodeInstances ) { if ( subNodeInstance instanceof CompositeContextNodeInstance ) { _foreach.addNodeInstance( writeNodeInstance( context, subNodeInstance ) ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.FOR_EACH_NODE ) .setForEach( _foreach.build() ); } else { throw new IllegalArgumentException( "Unknown node instance type: " + nodeInstance ); } return _content.build(); }
protected JBPMMessages.ProcessInstance.NodeInstanceContent writeNodeInstanceContent(JBPMMessages.ProcessInstance.NodeInstance.Builder _node, NodeInstance nodeInstance, MarshallerWriteContext context) throws IOException { JBPMMessages.ProcessInstance.NodeInstanceContent.Builder _content = null; if ( nodeInstance instanceof RuleSetNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.RULE_SET_NODE ); List<Long> timerInstances = ((RuleSetNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { JBPMMessages.ProcessInstance.NodeInstanceContent.RuleSetNode.Builder _ruleSet = JBPMMessages.ProcessInstance.NodeInstanceContent.RuleSetNode.newBuilder(); for ( Long id : timerInstances ) { _ruleSet.addTimerInstanceId( id ); } _content.setRuleSet( _ruleSet.build() ); } } else if ( nodeInstance instanceof HumanTaskNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.HumanTaskNode.Builder _task = JBPMMessages.ProcessInstance.NodeInstanceContent.HumanTaskNode.newBuilder() .setWorkItemId( ((HumanTaskNodeInstance) nodeInstance).getWorkItemId() ); List<Long> timerInstances = ((HumanTaskNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _task.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.HUMAN_TASK_NODE ) .setHumanTask( _task.build() ); } else if ( nodeInstance instanceof WorkItemNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.WorkItemNode.Builder _wi = JBPMMessages.ProcessInstance.NodeInstanceContent.WorkItemNode.newBuilder() .setWorkItemId( ((WorkItemNodeInstance) nodeInstance).getWorkItemId() ); List<Long> timerInstances = ((WorkItemNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _wi.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.WORK_ITEM_NODE ) .setWorkItem( _wi.build() ); } else if ( nodeInstance instanceof SubProcessNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.SubProcessNode.Builder _sp = JBPMMessages.ProcessInstance.NodeInstanceContent.SubProcessNode.newBuilder() .setProcessInstanceId( ((SubProcessNodeInstance) nodeInstance).getProcessInstanceId() ); List<Long> timerInstances = ((SubProcessNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _sp.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.SUBPROCESS_NODE ) .setSubProcess( _sp.build() ); } else if ( nodeInstance instanceof MilestoneNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.MilestoneNode.Builder _ms = JBPMMessages.ProcessInstance.NodeInstanceContent.MilestoneNode.newBuilder(); List<Long> timerInstances = ((MilestoneNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _ms.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.MILESTONE_NODE ) .setMilestone( _ms.build() ); } else if ( nodeInstance instanceof EventNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.EVENT_NODE ); } else if ( nodeInstance instanceof TimerNodeInstance ) { _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.TIMER_NODE ) .setTimer( JBPMMessages.ProcessInstance.NodeInstanceContent.TimerNode.newBuilder() .setTimerId( ((TimerNodeInstance) nodeInstance).getTimerId() ) .build() ); } else if ( nodeInstance instanceof JoinInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.Builder _join = JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.newBuilder(); Map<Long, Integer> triggers = ((JoinInstance) nodeInstance).getTriggers(); List<Long> keys = new ArrayList<Long>( triggers.keySet() ); Collections.sort( keys, new Comparator<Long>() { public int compare(Long o1, Long o2) { return o1.compareTo( o2 ); } } ); for ( Long key : keys ) { _join.addTrigger( JBPMMessages.ProcessInstance.NodeInstanceContent.JoinNode.JoinTrigger.newBuilder() .setNodeId( key ) .setCounter( triggers.get( key ) ) .build() ); } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.JOIN_NODE ) .setJoin( _join.build() ); } else if ( nodeInstance instanceof StateNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.StateNode.Builder _state = JBPMMessages.ProcessInstance.NodeInstanceContent.StateNode.newBuilder(); List<Long> timerInstances = ((StateNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _state.addTimerInstanceId( id ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.STATE_NODE ) .setState( _state.build() ); } else if ( nodeInstance instanceof CompositeContextNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.CompositeContextNode.Builder _composite = JBPMMessages.ProcessInstance.NodeInstanceContent.CompositeContextNode.newBuilder(); JBPMMessages.ProcessInstance.NodeInstanceType _type = ( nodeInstance instanceof DynamicNodeInstance ) ? JBPMMessages.ProcessInstance.NodeInstanceType.DYNAMIC_NODE : JBPMMessages.ProcessInstance.NodeInstanceType.COMPOSITE_CONTEXT_NODE; CompositeContextNodeInstance compositeNodeInstance = (CompositeContextNodeInstance) nodeInstance; List<Long> timerInstances = ((CompositeContextNodeInstance) nodeInstance).getTimerInstances(); if ( timerInstances != null ) { for ( Long id : timerInstances ) { _composite.addTimerInstanceId( id ); } } VariableScopeInstance variableScopeInstance = (VariableScopeInstance) compositeNodeInstance.getContextInstance( VariableScope.VARIABLE_SCOPE ); if ( variableScopeInstance != null ) { List<Map.Entry<String, Object>> variables = new ArrayList<Map.Entry<String, Object>>( variableScopeInstance.getVariables().entrySet() ); Collections.sort( variables, new Comparator<Map.Entry<String, Object>>() { public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) { return o1.getKey().compareTo( o2.getKey() ); } } ); for ( Map.Entry<String, Object> variable : variables ) { _composite.addVariable( ProtobufProcessMarshaller.marshallVariable( context, variable.getKey(), variable.getValue() ) ); } } List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>( compositeNodeInstance.getNodeInstances() ); Collections.sort( nodeInstances, new Comparator<NodeInstance>() { public int compare(NodeInstance o1, NodeInstance o2) { return (int) (o1.getId() - o2.getId()); } } ); for ( NodeInstance subNodeInstance : nodeInstances ) { _composite.addNodeInstance( writeNodeInstance( context, subNodeInstance ) ); } List<ContextInstance> exclusiveGroupInstances = compositeNodeInstance.getContextInstances( ExclusiveGroup.EXCLUSIVE_GROUP ); if ( exclusiveGroupInstances != null ) { for ( ContextInstance contextInstance : exclusiveGroupInstances ) { JBPMMessages.ProcessInstance.ExclusiveGroupInstance.Builder _excl = JBPMMessages.ProcessInstance.ExclusiveGroupInstance.newBuilder(); ExclusiveGroupInstance exclusiveGroupInstance = (ExclusiveGroupInstance) contextInstance; Collection<NodeInstance> groupNodeInstances = exclusiveGroupInstance.getNodeInstances(); for ( NodeInstance groupNodeInstance : groupNodeInstances ) { _excl.addGroupNodeInstanceId( groupNodeInstance.getId() ); } _composite.addExclusiveGroup( _excl.build() ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( _type ) .setComposite( _composite.build() ); } else if ( nodeInstance instanceof ForEachNodeInstance ) { JBPMMessages.ProcessInstance.NodeInstanceContent.ForEachNode.Builder _foreach = JBPMMessages.ProcessInstance.NodeInstanceContent.ForEachNode.newBuilder(); ForEachNodeInstance forEachNodeInstance = (ForEachNodeInstance) nodeInstance; List<NodeInstance> nodeInstances = new ArrayList<NodeInstance>( forEachNodeInstance.getNodeInstances() ); Collections.sort( nodeInstances, new Comparator<NodeInstance>() { public int compare(NodeInstance o1, NodeInstance o2) { return (int) (o1.getId() - o2.getId()); } } ); for ( NodeInstance subNodeInstance : nodeInstances ) { if ( subNodeInstance instanceof CompositeContextNodeInstance ) { _foreach.addNodeInstance( writeNodeInstance( context, subNodeInstance ) ); } } _content = JBPMMessages.ProcessInstance.NodeInstanceContent.newBuilder() .setType( NodeInstanceType.FOR_EACH_NODE ) .setForEach( _foreach.build() ); } else { throw new IllegalArgumentException( "Unknown node instance type: " + nodeInstance ); } return _content.build(); }
diff --git a/src/net/miz_hi/smileessence/listener/TimelineRefreshListener.java b/src/net/miz_hi/smileessence/listener/TimelineRefreshListener.java index b11d45d..43bba1f 100644 --- a/src/net/miz_hi/smileessence/listener/TimelineRefreshListener.java +++ b/src/net/miz_hi/smileessence/listener/TimelineRefreshListener.java @@ -1,112 +1,112 @@ package net.miz_hi.smileessence.listener; import android.widget.ListView; import com.handmark.pulltorefresh.library.PullToRefreshBase; import net.miz_hi.smileessence.core.MyExecutor; import net.miz_hi.smileessence.model.statuslist.timeline.Timeline; import net.miz_hi.smileessence.notification.Notificator; import net.miz_hi.smileessence.util.UiHandler; public class TimelineRefreshListener implements PullToRefreshBase.OnRefreshListener2<ListView> { Timeline timeline; public TimelineRefreshListener(Timeline timeline) { this.timeline = timeline; } @Override public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) { final int old = timeline.getCount(); MyExecutor.execute(new Runnable() { @Override public void run() { try { timeline.loadNewer(new Runnable() { @Override public void run() { final int current = timeline.getCount(); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); - refreshView.getRefreshableView().setSelectionFromTop(current - old + 1, 0); + refreshView.getRefreshableView().setSelectionFromTop(current - old, 0); Notificator.info((current - old) + "件読み込みました"); } }.post(); } }).get(); } catch (Exception e) { e.printStackTrace(); Notificator.alert("更新に失敗しました"); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); } }.post(); } } }); } @Override public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) { final int old = timeline.getCount(); MyExecutor.execute(new Runnable() { @Override public void run() { try { timeline.loadOlder(new Runnable() { @Override public void run() { final int current = timeline.getCount(); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); Notificator.info((current - old) + "件読み込みました"); } }.post(); } }).get(); } catch (Exception e) { e.printStackTrace(); Notificator.alert("更新に失敗しました"); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); } }.post(); } } }); } }
true
true
public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) { final int old = timeline.getCount(); MyExecutor.execute(new Runnable() { @Override public void run() { try { timeline.loadNewer(new Runnable() { @Override public void run() { final int current = timeline.getCount(); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); refreshView.getRefreshableView().setSelectionFromTop(current - old + 1, 0); Notificator.info((current - old) + "件読み込みました"); } }.post(); } }).get(); } catch (Exception e) { e.printStackTrace(); Notificator.alert("更新に失敗しました"); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); } }.post(); } } }); }
public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) { final int old = timeline.getCount(); MyExecutor.execute(new Runnable() { @Override public void run() { try { timeline.loadNewer(new Runnable() { @Override public void run() { final int current = timeline.getCount(); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); refreshView.getRefreshableView().setSelectionFromTop(current - old, 0); Notificator.info((current - old) + "件読み込みました"); } }.post(); } }).get(); } catch (Exception e) { e.printStackTrace(); Notificator.alert("更新に失敗しました"); new UiHandler() { @Override public void run() { refreshView.onRefreshComplete(); } }.post(); } } }); }
diff --git a/Server/DirectoryServerConnection.java b/Server/DirectoryServerConnection.java index 7f29f5a..35572f8 100644 --- a/Server/DirectoryServerConnection.java +++ b/Server/DirectoryServerConnection.java @@ -1,121 +1,122 @@ import java.util.*; import java.io.*; import java.net.*; public class DirectoryServerConnection implements Runnable { private DirectoryServer _host = null; private Socket _clientSocket = null; DirectoryServerConnection(DirectoryServer host, Socket clientSocket) { _host = host; _clientSocket = clientSocket; } public void run() { try { System.out.println("Thread for connection started."); // load in the stream data InputStream is = _clientSocket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); - // read each line + // request data String line; String userName, addIP; String sendIP; String acceptIP; String hangupIP; + // read each line while ((line = br.readLine()) != null) { // AddUser request if (line.startsWith("<AddUser>")) { userName = br.readLine(); userName = userName.substring(10, userName.length() - 11); addIP = br.readLine(); addIP = addIP.substring(11, addIP.length() - 12); System.out.println("\nAddUser Request"); System.out.println("---------------"); System.out.println("New user: " + userName); System.out.println("IP Address: " + addIP); User u = new User(userName, addIP); _host._directory.add(u); // when user adds themself, they should also receive // existing directory (+ themself) PrintWriter out = new PrintWriter(_clientSocket.getOutputStream(), true); out.println("<DirectoryListing>"); for (User o : _host._directory) { out.println("<User>"); out.println("<Username>" + o.getUsername() + "</Username>"); out.println("<IPAddress>" + o.getIPAddress() + "</IPAddress>"); out.println("</User>"); } out.println("</DirectoryListing>"); } // GetDirectory request else if (line.startsWith("<GetDirectory>")) { System.out.println("\nGetDirectory Request"); PrintWriter out = new PrintWriter(_clientSocket.getOutputStream(), true); out.println("<Directory>"); for (User u : _host._directory) { out.println("<User>"); out.println("<Username>" + u.getUsername() + "</Username>"); out.println("<IPAddress>" + u.getIPAddress() + "</IPAddress>"); out.println("</User>"); } out.println("</Directory>"); out.close(); } // SendCall request else if (line.startsWith("<SendCall>")) { sendIP = br.readLine(); sendIP = sendIP.substring(11, sendIP.length() - 12); System.out.println("\nSendCall Request"); System.out.println("----------------"); System.out.println("IP Address: " + sendIP); } // AcceptCall request else if (line.startsWith("<AcceptCall>")) { acceptIP = br.readLine(); acceptIP = acceptIP.substring(11, acceptIP.length() - 12); System.out.println("\nAcceptCall Request"); System.out.println("------------------"); System.out.println("IP Address: " + acceptIP); } // Hangup request else if (line.startsWith("<Hangup>")) { hangupIP = br.readLine(); hangupIP = hangupIP.substring(11, hangupIP.length() - 12); System.out.println("\nHangup Request"); System.out.println("--------------"); System.out.println("IP Address: " + hangupIP); } // Something else else { // ignore } } } catch (IOException ex) { // TODO: handle this exception } } }
false
true
public void run() { try { System.out.println("Thread for connection started."); // load in the stream data InputStream is = _clientSocket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); // read each line String line; String userName, addIP; String sendIP; String acceptIP; String hangupIP; while ((line = br.readLine()) != null) { // AddUser request if (line.startsWith("<AddUser>")) { userName = br.readLine(); userName = userName.substring(10, userName.length() - 11); addIP = br.readLine(); addIP = addIP.substring(11, addIP.length() - 12); System.out.println("\nAddUser Request"); System.out.println("---------------"); System.out.println("New user: " + userName); System.out.println("IP Address: " + addIP); User u = new User(userName, addIP); _host._directory.add(u); // when user adds themself, they should also receive // existing directory (+ themself) PrintWriter out = new PrintWriter(_clientSocket.getOutputStream(), true); out.println("<DirectoryListing>"); for (User o : _host._directory) { out.println("<User>"); out.println("<Username>" + o.getUsername() + "</Username>"); out.println("<IPAddress>" + o.getIPAddress() + "</IPAddress>"); out.println("</User>"); } out.println("</DirectoryListing>"); } // GetDirectory request else if (line.startsWith("<GetDirectory>")) { System.out.println("\nGetDirectory Request"); PrintWriter out = new PrintWriter(_clientSocket.getOutputStream(), true); out.println("<Directory>"); for (User u : _host._directory) { out.println("<User>"); out.println("<Username>" + u.getUsername() + "</Username>"); out.println("<IPAddress>" + u.getIPAddress() + "</IPAddress>"); out.println("</User>"); } out.println("</Directory>"); out.close(); } // SendCall request else if (line.startsWith("<SendCall>")) { sendIP = br.readLine(); sendIP = sendIP.substring(11, sendIP.length() - 12); System.out.println("\nSendCall Request"); System.out.println("----------------"); System.out.println("IP Address: " + sendIP); } // AcceptCall request else if (line.startsWith("<AcceptCall>")) { acceptIP = br.readLine(); acceptIP = acceptIP.substring(11, acceptIP.length() - 12); System.out.println("\nAcceptCall Request"); System.out.println("------------------"); System.out.println("IP Address: " + acceptIP); } // Hangup request else if (line.startsWith("<Hangup>")) { hangupIP = br.readLine(); hangupIP = hangupIP.substring(11, hangupIP.length() - 12); System.out.println("\nHangup Request"); System.out.println("--------------"); System.out.println("IP Address: " + hangupIP); } // Something else else { // ignore } } } catch (IOException ex) { // TODO: handle this exception } }
public void run() { try { System.out.println("Thread for connection started."); // load in the stream data InputStream is = _clientSocket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); // request data String line; String userName, addIP; String sendIP; String acceptIP; String hangupIP; // read each line while ((line = br.readLine()) != null) { // AddUser request if (line.startsWith("<AddUser>")) { userName = br.readLine(); userName = userName.substring(10, userName.length() - 11); addIP = br.readLine(); addIP = addIP.substring(11, addIP.length() - 12); System.out.println("\nAddUser Request"); System.out.println("---------------"); System.out.println("New user: " + userName); System.out.println("IP Address: " + addIP); User u = new User(userName, addIP); _host._directory.add(u); // when user adds themself, they should also receive // existing directory (+ themself) PrintWriter out = new PrintWriter(_clientSocket.getOutputStream(), true); out.println("<DirectoryListing>"); for (User o : _host._directory) { out.println("<User>"); out.println("<Username>" + o.getUsername() + "</Username>"); out.println("<IPAddress>" + o.getIPAddress() + "</IPAddress>"); out.println("</User>"); } out.println("</DirectoryListing>"); } // GetDirectory request else if (line.startsWith("<GetDirectory>")) { System.out.println("\nGetDirectory Request"); PrintWriter out = new PrintWriter(_clientSocket.getOutputStream(), true); out.println("<Directory>"); for (User u : _host._directory) { out.println("<User>"); out.println("<Username>" + u.getUsername() + "</Username>"); out.println("<IPAddress>" + u.getIPAddress() + "</IPAddress>"); out.println("</User>"); } out.println("</Directory>"); out.close(); } // SendCall request else if (line.startsWith("<SendCall>")) { sendIP = br.readLine(); sendIP = sendIP.substring(11, sendIP.length() - 12); System.out.println("\nSendCall Request"); System.out.println("----------------"); System.out.println("IP Address: " + sendIP); } // AcceptCall request else if (line.startsWith("<AcceptCall>")) { acceptIP = br.readLine(); acceptIP = acceptIP.substring(11, acceptIP.length() - 12); System.out.println("\nAcceptCall Request"); System.out.println("------------------"); System.out.println("IP Address: " + acceptIP); } // Hangup request else if (line.startsWith("<Hangup>")) { hangupIP = br.readLine(); hangupIP = hangupIP.substring(11, hangupIP.length() - 12); System.out.println("\nHangup Request"); System.out.println("--------------"); System.out.println("IP Address: " + hangupIP); } // Something else else { // ignore } } } catch (IOException ex) { // TODO: handle this exception } }
diff --git a/eclipse/plugins/net.sf.orcc.graphiti.ui/src/net/sf/orcc/graphiti/ui/properties/ModelPropertySource.java b/eclipse/plugins/net.sf.orcc.graphiti.ui/src/net/sf/orcc/graphiti/ui/properties/ModelPropertySource.java index 68f09b10d..7e4bd634f 100644 --- a/eclipse/plugins/net.sf.orcc.graphiti.ui/src/net/sf/orcc/graphiti/ui/properties/ModelPropertySource.java +++ b/eclipse/plugins/net.sf.orcc.graphiti.ui/src/net/sf/orcc/graphiti/ui/properties/ModelPropertySource.java @@ -1,228 +1,226 @@ /* * Copyright (c) 2008-2011, IETR/INSA of Rennes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the IETR/INSA of Rennes nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.graphiti.ui.properties; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.sf.orcc.graphiti.model.AbstractObject; import net.sf.orcc.graphiti.model.Edge; import net.sf.orcc.graphiti.model.Graph; import net.sf.orcc.graphiti.model.ObjectType; import net.sf.orcc.graphiti.model.Parameter; import net.sf.orcc.graphiti.model.Vertex; import net.sf.orcc.graphiti.ui.commands.ParameterChangeValueCommand; import net.sf.orcc.graphiti.ui.editors.GraphEditor; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.views.properties.IPropertyDescriptor; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.IPropertySource; import org.eclipse.ui.views.properties.PropertySheet; import org.eclipse.ui.views.properties.PropertySheetPage; import org.eclipse.ui.views.properties.TextPropertyDescriptor; import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage; /** * This class implements a property source for the different objects of our * model. * * @author Matthieu Wipliez * */ public class ModelPropertySource implements IPropertySource, PropertyChangeListener { private IPropertyDescriptor[] descs; private boolean doRefresh; private AbstractObject model; private ObjectType type; public ModelPropertySource(AbstractObject model) { this.model = model; model.addPropertyChangeListener(this); this.type = model.getType(); List<IPropertyDescriptor> descs = new ArrayList<IPropertyDescriptor>(); for (Parameter parameter : type.getParameters()) { if (!(parameter.getType() == List.class || parameter.getType() == Map.class)) { String name = parameter.getName(); TextPropertyDescriptor desc = new TextPropertyDescriptor(name, name); descs.add(desc); } } this.descs = descs.toArray(new IPropertyDescriptor[0]); } @Override public Object getEditableValue() { return null; } @Override public IPropertyDescriptor[] getPropertyDescriptors() { return descs; } @Override public Object getPropertyValue(Object id) { Object value = model.getValue((String) id); if (value == null) { return ""; } return String.valueOf(value); } @Override public boolean isPropertySet(Object id) { Object value = model.getValue((String) id); Object defaultValue = model.getParameter((String) id).getDefault(); return value != defaultValue; } @Override public void propertyChange(PropertyChangeEvent evt) { if (!doRefresh) { return; } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage page = workbench.getActiveWorkbenchWindow() .getActivePage(); // show properties try { IViewPart part = page.showView(IPageLayout.ID_PROP_SHEET); if (part instanceof PropertySheet) { IPropertySheetPage propPage = (IPropertySheetPage) ((PropertySheet) part) .getCurrentPage(); if (propPage instanceof PropertySheetPage) { ((PropertySheetPage) propPage).refresh(); } else if (propPage instanceof TabbedPropertySheetPage) { ((TabbedPropertySheetPage) propPage).refresh(); } } } catch (PartInitException e) { e.printStackTrace(); } } @Override public void resetPropertyValue(Object id) { Object defaultValue = model.getParameter((String) id).getDefault(); if (defaultValue == null) { defaultValue = ""; } model.setValue((String) id, defaultValue); } @Override public void setPropertyValue(Object id, Object value) { Graph graph; if (model instanceof Vertex) { graph = ((Vertex) model).getParent(); } else if (model instanceof Edge) { graph = ((Edge) model).getParent(); } else { graph = (Graph) model; } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage page = workbench.getActiveWorkbenchWindow() .getActivePage(); try { IEditorPart part = IDE.openEditor(page, graph.getFile()); if (part instanceof GraphEditor) { String parameterName = (String) id; // only update value if it is different than before Object oldValue = model.getValue(parameterName); String str = (String) value; if (oldValue == null && str.isEmpty() || String.valueOf(oldValue).equals(value)) { return; } - // For instance name - if ("id".equals(id)) { - // update only if another instance has not the same - if (graph.vertexExistsCaseInsensitive(str)) { - return; - } + // Ensure that "id" property is unique in the graph (in case + // insensitive mode) + if ("id".equals(id) && graph.vertexExistsCaseInsensitive(str)) { + return; } ParameterChangeValueCommand command = new ParameterChangeValueCommand( model, "Change value"); Class<?> parameterType = model.getParameter((String) id) .getType(); if (str.isEmpty()) { // get default value value = model.getParameter(parameterName).getDefault(); } else { try { if (parameterType == Integer.class) { value = Integer.valueOf(str); } else if (parameterType == Float.class) { value = Float.valueOf(str); } else if (parameterType == Boolean.class) { if (!"true".equals(value) && !"false".equals(value)) { throw new IllegalArgumentException(); } value = Boolean.valueOf(str); } } catch (RuntimeException e) { value = "invalid \"" + value + "\" value for " + parameterType.getSimpleName(); } } command.setValue(parameterName, value); doRefresh = false; ((GraphEditor) part).executeCommand(command); doRefresh = true; } } catch (PartInitException e) { e.printStackTrace(); } } }
true
true
public void setPropertyValue(Object id, Object value) { Graph graph; if (model instanceof Vertex) { graph = ((Vertex) model).getParent(); } else if (model instanceof Edge) { graph = ((Edge) model).getParent(); } else { graph = (Graph) model; } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage page = workbench.getActiveWorkbenchWindow() .getActivePage(); try { IEditorPart part = IDE.openEditor(page, graph.getFile()); if (part instanceof GraphEditor) { String parameterName = (String) id; // only update value if it is different than before Object oldValue = model.getValue(parameterName); String str = (String) value; if (oldValue == null && str.isEmpty() || String.valueOf(oldValue).equals(value)) { return; } // For instance name if ("id".equals(id)) { // update only if another instance has not the same if (graph.vertexExistsCaseInsensitive(str)) { return; } } ParameterChangeValueCommand command = new ParameterChangeValueCommand( model, "Change value"); Class<?> parameterType = model.getParameter((String) id) .getType(); if (str.isEmpty()) { // get default value value = model.getParameter(parameterName).getDefault(); } else { try { if (parameterType == Integer.class) { value = Integer.valueOf(str); } else if (parameterType == Float.class) { value = Float.valueOf(str); } else if (parameterType == Boolean.class) { if (!"true".equals(value) && !"false".equals(value)) { throw new IllegalArgumentException(); } value = Boolean.valueOf(str); } } catch (RuntimeException e) { value = "invalid \"" + value + "\" value for " + parameterType.getSimpleName(); } } command.setValue(parameterName, value); doRefresh = false; ((GraphEditor) part).executeCommand(command); doRefresh = true; } } catch (PartInitException e) { e.printStackTrace(); } }
public void setPropertyValue(Object id, Object value) { Graph graph; if (model instanceof Vertex) { graph = ((Vertex) model).getParent(); } else if (model instanceof Edge) { graph = ((Edge) model).getParent(); } else { graph = (Graph) model; } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage page = workbench.getActiveWorkbenchWindow() .getActivePage(); try { IEditorPart part = IDE.openEditor(page, graph.getFile()); if (part instanceof GraphEditor) { String parameterName = (String) id; // only update value if it is different than before Object oldValue = model.getValue(parameterName); String str = (String) value; if (oldValue == null && str.isEmpty() || String.valueOf(oldValue).equals(value)) { return; } // Ensure that "id" property is unique in the graph (in case // insensitive mode) if ("id".equals(id) && graph.vertexExistsCaseInsensitive(str)) { return; } ParameterChangeValueCommand command = new ParameterChangeValueCommand( model, "Change value"); Class<?> parameterType = model.getParameter((String) id) .getType(); if (str.isEmpty()) { // get default value value = model.getParameter(parameterName).getDefault(); } else { try { if (parameterType == Integer.class) { value = Integer.valueOf(str); } else if (parameterType == Float.class) { value = Float.valueOf(str); } else if (parameterType == Boolean.class) { if (!"true".equals(value) && !"false".equals(value)) { throw new IllegalArgumentException(); } value = Boolean.valueOf(str); } } catch (RuntimeException e) { value = "invalid \"" + value + "\" value for " + parameterType.getSimpleName(); } } command.setValue(parameterName, value); doRefresh = false; ((GraphEditor) part).executeCommand(command); doRefresh = true; } } catch (PartInitException e) { e.printStackTrace(); } }
diff --git a/src/java/com/android/internal/telephony/cat/CatService.java b/src/java/com/android/internal/telephony/cat/CatService.java index 6b7c7d7b..4044bca7 100755 --- a/src/java/com/android/internal/telephony/cat/CatService.java +++ b/src/java/com/android/internal/telephony/cat/CatService.java @@ -1,1053 +1,1051 @@ /* * Copyright (c) 2013, The Linux Foundation. All rights reserved. * Not a Contribution. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony.cat; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources.NotFoundException; import android.os.AsyncResult; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.SystemProperties; import com.android.internal.telephony.CommandsInterface; import com.android.internal.telephony.uicc.IccFileHandler; import com.android.internal.telephony.uicc.IccRecords; import com.android.internal.telephony.uicc.IccUtils; import com.android.internal.telephony.uicc.UiccCard; import com.android.internal.telephony.uicc.UiccCardApplication; import com.android.internal.telephony.uicc.IccCardStatus.CardState; import com.android.internal.telephony.uicc.IccRefreshResponse; import com.android.internal.telephony.uicc.UiccController; import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Locale; import static com.android.internal.telephony.cat.CatCmdMessage. SetupEventListConstants.IDLE_SCREEN_AVAILABLE_EVENT; import static com.android.internal.telephony.cat.CatCmdMessage. SetupEventListConstants.LANGUAGE_SELECTION_EVENT; class RilMessage { int mId; Object mData; ResultCode mResCode; RilMessage(int msgId, String rawData) { mId = msgId; mData = rawData; } RilMessage(RilMessage other) { mId = other.mId; mData = other.mData; mResCode = other.mResCode; } } /** * Class that implements SIM Toolkit Telephony Service. Interacts with the RIL * and application. * * {@hide} */ public class CatService extends Handler implements AppInterface { private static final boolean DBG = false; // Class members protected static IccRecords mIccRecords; protected static UiccCardApplication mUiccApplication; // Service members. // Protects singleton instance lazy initialization. protected static final Object sInstanceLock = new Object(); private static CatService sInstance; protected static HandlerThread mhandlerThread; protected CommandsInterface mCmdIf; protected Context mContext; protected CatCmdMessage mCurrntCmd = null; protected CatCmdMessage mMenuCmd = null; protected RilMessageDecoder mMsgDecoder = null; protected boolean mStkAppInstalled = false; protected UiccController mUiccController; protected CardState mCardState = CardState.CARDSTATE_ABSENT; // Service constants. protected static final int MSG_ID_SESSION_END = 1; protected static final int MSG_ID_PROACTIVE_COMMAND = 2; protected static final int MSG_ID_EVENT_NOTIFY = 3; protected static final int MSG_ID_CALL_SETUP = 4; static final int MSG_ID_REFRESH = 5; static final int MSG_ID_RESPONSE = 6; protected static final int MSG_ID_ICC_CHANGED = 7; protected static final int MSG_ID_ALPHA_NOTIFY = 8; static final int MSG_ID_RIL_MSG_DECODED = 10; // Events to signal SIM presence or absent in the device. protected static final int MSG_ID_ICC_RECORDS_LOADED = 20; //Events to signal SIM REFRESH notificatations protected static final int MSG_ID_ICC_REFRESH = 30; private static final int DEV_ID_KEYPAD = 0x01; private static final int DEV_ID_DISPLAY = 0x02; private static final int DEV_ID_UICC = 0x81; private static final int DEV_ID_TERMINAL = 0x82; private static final int DEV_ID_NETWORK = 0x83; static final String STK_DEFAULT = "Default Message"; /* Intentionally private for singleton */ private CatService(CommandsInterface ci, UiccCardApplication ca, IccRecords ir, Context context, IccFileHandler fh, UiccCard ic) { if (ci == null || ca == null || ir == null || context == null || fh == null || ic == null) { throw new NullPointerException( "Service: Input parameters must not be null"); } mCmdIf = ci; mContext = context; // Get the RilMessagesDecoder for decoding the messages. mMsgDecoder = RilMessageDecoder.getInstance(this, fh); // Register ril events handling. mCmdIf.setOnCatSessionEnd(this, MSG_ID_SESSION_END, null); mCmdIf.setOnCatProactiveCmd(this, MSG_ID_PROACTIVE_COMMAND, null); mCmdIf.setOnCatEvent(this, MSG_ID_EVENT_NOTIFY, null); mCmdIf.setOnCatCallSetUp(this, MSG_ID_CALL_SETUP, null); //mCmdIf.setOnSimRefresh(this, MSG_ID_REFRESH, null); mCmdIf.registerForIccRefresh(this, MSG_ID_ICC_REFRESH, null); mCmdIf.setOnCatCcAlphaNotify(this, MSG_ID_ALPHA_NOTIFY, null); mIccRecords = ir; mUiccApplication = ca; mIccRecords.registerForRecordsLoaded(this, MSG_ID_ICC_RECORDS_LOADED, null); mUiccController = UiccController.getInstance(); if (mUiccController != null) { mUiccController.registerForIccChanged(this, MSG_ID_ICC_CHANGED, null); } else { CatLog.e(this, "UiccController instance is null"); } // Check if STK application is availalbe mStkAppInstalled = isStkAppInstalled(); CatLog.d(this, "Running CAT service. STK app installed:" + mStkAppInstalled); } /* Add empty Constructor which is required for Multi SIM Functionaly */ protected CatService() { } public void dispose() { synchronized (sInstanceLock) { CatLog.d(this, "Disposing CatService object"); mIccRecords.unregisterForRecordsLoaded(this); // Clean up stk icon if dispose is called broadcastCardStateAndIccRefreshResp(CardState.CARDSTATE_ABSENT, null); mCmdIf.unSetOnCatSessionEnd(this); mCmdIf.unSetOnCatProactiveCmd(this); mCmdIf.unSetOnCatEvent(this); mCmdIf.unSetOnCatCallSetUp(this); mCmdIf.unregisterForIccRefresh(this); if (mUiccController != null) { mUiccController.unregisterForIccChanged(this); mUiccController = null; } if (mUiccApplication != null) { mUiccApplication.unregisterForReady(this); } mMsgDecoder.dispose(); mMsgDecoder = null; mCmdIf.unSetOnCatCcAlphaNotify(this); disposeHandlerThread(); sInstance = null; removeCallbacksAndMessages(null); } } protected void disposeHandlerThread() { mhandlerThread.quit(); mhandlerThread = null; } @Override protected void finalize() { CatLog.d(this, "Service finalized"); } private void handleRilMsg(RilMessage rilMsg) { if (rilMsg == null) { return; } // dispatch messages CommandParams cmdParams = null; switch (rilMsg.mId) { case MSG_ID_EVENT_NOTIFY: if (rilMsg.mResCode == ResultCode.OK) { cmdParams = (CommandParams) rilMsg.mData; if (cmdParams != null) { handleCommand(cmdParams, false); } } break; case MSG_ID_PROACTIVE_COMMAND: try { cmdParams = (CommandParams) rilMsg.mData; } catch (ClassCastException e) { // for error handling : cast exception CatLog.d(this, "Fail to parse proactive command"); // Don't send Terminal Resp if command detail is not available if (mCurrntCmd != null) { sendTerminalResponse(mCurrntCmd.mCmdDet, ResultCode.CMD_DATA_NOT_UNDERSTOOD, false, 0x00, null); } break; } if (cmdParams != null) { if (rilMsg.mResCode == ResultCode.OK) { handleCommand(cmdParams, true); } else { // for proactive commands that couldn't be decoded // successfully respond with the code generated by the // message decoder. sendTerminalResponse(cmdParams.mCmdDet, rilMsg.mResCode, false, 0, null); } } break; case MSG_ID_REFRESH: cmdParams = (CommandParams) rilMsg.mData; if (cmdParams != null) { handleCommand(cmdParams, false); } break; case MSG_ID_SESSION_END: handleSessionEnd(); break; case MSG_ID_CALL_SETUP: // prior event notify command supplied all the information // needed for set up call processing. break; } } /** * This function validates the events in SETUP_EVENT_LIST which are currently * supported by the Android framework. In case of SETUP_EVENT_LIST has NULL events * or no events, all the events need to be reset. */ private boolean isSupportedSetupEventCommand(CatCmdMessage cmdMsg) { boolean flag = true; for (int eventVal: cmdMsg.getSetEventList().eventList) { CatLog.d(this,"Event: " + eventVal); switch (eventVal) { /* Currently android is supporting only the below events in SetupEventList * Browser Termination, * Idle Screen Available and * Language Selection. */ case IDLE_SCREEN_AVAILABLE_EVENT: case LANGUAGE_SELECTION_EVENT: break; default: flag = false; } } return flag; } /** * Handles RIL_UNSOL_STK_EVENT_NOTIFY or RIL_UNSOL_STK_PROACTIVE_COMMAND command * from RIL. * Sends valid proactive command data to the application using intents. * RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE will be send back if the command is * from RIL_UNSOL_STK_PROACTIVE_COMMAND. */ private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) { CatLog.d(this, cmdParams.getCommandType().name()); CharSequence message; ResultCode resultCode; CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams); switch (cmdParams.getCommandType()) { case SET_UP_MENU: if (removeMenu(cmdMsg.getMenu())) { mMenuCmd = null; } else { mMenuCmd = cmdMsg; } resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet, resultCode, false, 0, null); break; case DISPLAY_TEXT: // when application is not required to respond, send an immediate response. if (!cmdMsg.geTextMessage().responseNeeded) { resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet, resultCode, false, 0, null); } break; case REFRESH: //Stk app service displays alpha id to user if it is present, nothing to do here CatLog.d(this, "Pass Refresh to Stk app"); break; case SET_UP_IDLE_MODE_TEXT: resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet,resultCode, false, 0, null); break; case SET_UP_EVENT_LIST: if (isSupportedSetupEventCommand(cmdMsg)) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } else { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, false, 0, null); } break; case PROVIDE_LOCAL_INFORMATION: ResponseData resp; switch (cmdParams.mCmdDet.commandQualifier) { case CommandParamsFactory.DTTZ_SETTING: resp = new DTTZResponseData(null); sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); break; case CommandParamsFactory.LANGUAGE_SETTING: resp = new LanguageResponseData(Locale.getDefault().getLanguage()); sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); break; default: sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } // No need to start STK app here. return; case LAUNCH_BROWSER: if ((((LaunchBrowserParams) cmdParams).mConfirmMsg.text != null) && (((LaunchBrowserParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.launchBrowserDefault); ((LaunchBrowserParams) cmdParams).mConfirmMsg.text = message.toString(); } break; case SELECT_ITEM: case GET_INPUT: case GET_INKEY: break; case SEND_DTMF: case SEND_SMS: case SEND_SS: case SEND_USSD: if ((((DisplayTextParams)cmdParams).mTextMsg.text != null) && (((DisplayTextParams)cmdParams).mTextMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.sending); ((DisplayTextParams)cmdParams).mTextMsg.text = message.toString(); } break; case PLAY_TONE: break; case SET_UP_CALL: if ((((CallSetupParams) cmdParams).mConfirmMsg.text != null) && (((CallSetupParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.SetupCallDefault); ((CallSetupParams) cmdParams).mConfirmMsg.text = message.toString(); } break; case OPEN_CHANNEL: case CLOSE_CHANNEL: case RECEIVE_DATA: case SEND_DATA: BIPClientParams cmd = (BIPClientParams) cmdParams; /* Per 3GPP specification 102.223, * if the alpha identifier is not provided by the UICC, * the terminal MAY give information to the user * noAlphaUsrCnf defines if you need to show user confirmation or not */ boolean noAlphaUsrCnf = false; try { noAlphaUsrCnf = mContext.getResources().getBoolean( com.android.internal.R.bool.config_stkNoAlphaUsrCnf); } catch (NotFoundException e) { noAlphaUsrCnf = false; } if ((cmd.mTextMsg.text == null) && (cmd.mHasAlphaId || noAlphaUsrCnf)) { CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id"); // If alpha length is zero, we just respond with OK. if (isProactiveCmd) { - if (cmdParams.getCommandType() == CommandType.OPEN_CHANNEL) { - mCmdIf.handleCallSetupRequestFromSim(true, null); - } else { - sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); - } + sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); + } else if (cmdParams.getCommandType() == CommandType.OPEN_CHANNEL) { + mCmdIf.handleCallSetupRequestFromSim(true, null); } return; } // Respond with permanent failure to avoid retry if STK app is not present. if (!mStkAppInstalled) { CatLog.d(this, "No STK application found."); if (isProactiveCmd) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, false, 0, null); return; } } /* * CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by * either PROACTIVE_COMMAND or EVENT_NOTIFY. * If PROACTIVE_COMMAND is used for those commands, send terminal * response here. */ if (isProactiveCmd && ((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL) || (cmdParams.getCommandType() == CommandType.RECEIVE_DATA) || (cmdParams.getCommandType() == CommandType.SEND_DATA))) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } break; default: CatLog.d(this, "Unsupported command"); return; } mCurrntCmd = cmdMsg; broadcastCatCmdIntent(cmdMsg); } protected void broadcastCatCmdIntent(CatCmdMessage cmdMsg) { Intent intent = new Intent(AppInterface.CAT_CMD_ACTION); intent.putExtra("STK CMD", cmdMsg); mContext.sendBroadcast(intent); } /** * Handles RIL_UNSOL_STK_SESSION_END unsolicited command from RIL. * */ protected void handleSessionEnd() { CatLog.d(this, "SESSION END"); mCurrntCmd = mMenuCmd; Intent intent = new Intent(AppInterface.CAT_SESSION_END_ACTION); mContext.sendBroadcast(intent); } private void sendTerminalResponse(CommandDetails cmdDet, ResultCode resultCode, boolean includeAdditionalInfo, int additionalInfo, ResponseData resp) { if (cmdDet == null) { return; } ByteArrayOutputStream buf = new ByteArrayOutputStream(); Input cmdInput = null; if (mCurrntCmd != null) { cmdInput = mCurrntCmd.geInput(); } // command details int tag = ComprehensionTlvTag.COMMAND_DETAILS.value(); if (cmdDet.compRequired) { tag |= 0x80; } buf.write(tag); buf.write(0x03); // length buf.write(cmdDet.commandNumber); buf.write(cmdDet.typeOfCommand); buf.write(cmdDet.commandQualifier); // device identities // According to TS102.223/TS31.111 section 6.8 Structure of // TERMINAL RESPONSE, "For all SIMPLE-TLV objects with Min=N, // the ME should set the CR(comprehension required) flag to // comprehension not required.(CR=0)" // Since DEVICE_IDENTITIES and DURATION TLVs have Min=N, // the CR flag is not set. tag = ComprehensionTlvTag.DEVICE_IDENTITIES.value(); buf.write(tag); buf.write(0x02); // length buf.write(DEV_ID_TERMINAL); // source device id buf.write(DEV_ID_UICC); // destination device id // result tag = ComprehensionTlvTag.RESULT.value(); if (cmdDet.compRequired) { tag |= 0x80; } buf.write(tag); int length = includeAdditionalInfo ? 2 : 1; buf.write(length); buf.write(resultCode.value()); // additional info if (includeAdditionalInfo) { buf.write(additionalInfo); } // Fill optional data for each corresponding command if (resp != null) { resp.format(buf); } else { encodeOptionalTags(cmdDet, resultCode, cmdInput, buf); } byte[] rawData = buf.toByteArray(); String hexString = IccUtils.bytesToHexString(rawData); if (DBG) { CatLog.d(this, "TERMINAL RESPONSE: " + hexString); } mCmdIf.sendTerminalResponse(hexString, null); } private void encodeOptionalTags(CommandDetails cmdDet, ResultCode resultCode, Input cmdInput, ByteArrayOutputStream buf) { CommandType cmdType = AppInterface.CommandType.fromInt(cmdDet.typeOfCommand); if (cmdType != null) { switch (cmdType) { case GET_INKEY: // ETSI TS 102 384,27.22.4.2.8.4.2. // If it is a response for GET_INKEY command and the response timeout // occured, then add DURATION TLV for variable timeout case. if ((resultCode.value() == ResultCode.NO_RESPONSE_FROM_USER.value()) && (cmdInput != null) && (cmdInput.duration != null)) { getInKeyResponse(buf, cmdInput); } break; case PROVIDE_LOCAL_INFORMATION: if ((cmdDet.commandQualifier == CommandParamsFactory.LANGUAGE_SETTING) && (resultCode.value() == ResultCode.OK.value())) { getPliResponse(buf); } break; default: CatLog.d(this, "encodeOptionalTags() Unsupported Cmd details=" + cmdDet); break; } } else { CatLog.d(this, "encodeOptionalTags() bad Cmd details=" + cmdDet); } } private void getInKeyResponse(ByteArrayOutputStream buf, Input cmdInput) { int tag = ComprehensionTlvTag.DURATION.value(); buf.write(tag); buf.write(0x02); // length buf.write(cmdInput.duration.timeUnit.SECOND.value()); // Time (Unit,Seconds) buf.write(cmdInput.duration.timeInterval); // Time Duration } private void getPliResponse(ByteArrayOutputStream buf) { // Locale Language Setting String lang = SystemProperties.get("persist.sys.language"); if (lang != null) { // tag int tag = ComprehensionTlvTag.LANGUAGE.value(); buf.write(tag); ResponseData.writeLength(buf, lang.length()); buf.write(lang.getBytes(), 0, lang.length()); } } private void sendMenuSelection(int menuId, boolean helpRequired) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); // tag int tag = BerTlv.BER_MENU_SELECTION_TAG; buf.write(tag); // length buf.write(0x00); // place holder // device identities tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value(); buf.write(tag); buf.write(0x02); // length buf.write(DEV_ID_KEYPAD); // source device id buf.write(DEV_ID_UICC); // destination device id // item identifier tag = 0x80 | ComprehensionTlvTag.ITEM_ID.value(); buf.write(tag); buf.write(0x01); // length buf.write(menuId); // menu identifier chosen // help request if (helpRequired) { tag = ComprehensionTlvTag.HELP_REQUEST.value(); buf.write(tag); buf.write(0x00); // length } byte[] rawData = buf.toByteArray(); // write real length int len = rawData.length - 2; // minus (tag + length) rawData[1] = (byte) len; String hexString = IccUtils.bytesToHexString(rawData); mCmdIf.sendEnvelope(hexString, null); } private void eventDownload(int event, int sourceId, int destinationId, byte[] additionalInfo, boolean oneShot) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); // tag int tag = BerTlv.BER_EVENT_DOWNLOAD_TAG; buf.write(tag); // length buf.write(0x00); // place holder, assume length < 128. // event list tag = 0x80 | ComprehensionTlvTag.EVENT_LIST.value(); buf.write(tag); buf.write(0x01); // length buf.write(event); // event value // device identities tag = 0x80 | ComprehensionTlvTag.DEVICE_IDENTITIES.value(); buf.write(tag); buf.write(0x02); // length buf.write(sourceId); // source device id buf.write(destinationId); // destination device id /* * Check for type of event download to be sent to UICC - Browser * termination,Idle screen available, User activity, Language selection * etc as mentioned under ETSI TS 102 223 section 7.5 */ /* * Currently the below events are supported: * Browser Termination, * Idle Screen Available and * Language Selection Event. * Other event download commands should be encoded similar way */ /* TODO: eventDownload should be extended for other Envelope Commands */ switch (event) { case IDLE_SCREEN_AVAILABLE_EVENT: CatLog.d(this, " Sending Idle Screen Available event download to ICC"); break; case LANGUAGE_SELECTION_EVENT: CatLog.d(this, " Sending Language Selection event download to ICC"); tag = 0x80 | ComprehensionTlvTag.LANGUAGE.value(); buf.write(tag); // Language length should be 2 byte buf.write(0x02); break; default: break; } // additional information if (additionalInfo != null) { for (byte b : additionalInfo) { buf.write(b); } } byte[] rawData = buf.toByteArray(); // write real length int len = rawData.length - 2; // minus (tag + length) rawData[1] = (byte) len; String hexString = IccUtils.bytesToHexString(rawData); CatLog.d(this, "ENVELOPE COMMAND: " + hexString); mCmdIf.sendEnvelope(hexString, null); } /** * Used for instantiating/updating the Service from the GsmPhone or CdmaPhone constructor. * * @param ci CommandsInterface object * @param context phone app context * @param ic Icc card * @return The only Service object in the system */ public static CatService getInstance(CommandsInterface ci, Context context, UiccCard ic) { UiccCardApplication ca = null; IccFileHandler fh = null; IccRecords ir = null; if (ic != null) { /* Since Cat is not tied to any application, but rather is Uicc application * in itself - just get first FileHandler and IccRecords object */ ca = ic.getApplicationIndex(0); if (ca != null) { fh = ca.getIccFileHandler(); ir = ca.getIccRecords(); } } synchronized (sInstanceLock) { if (sInstance == null) { if (ci == null || ca == null || ir == null || context == null || fh == null || ic == null) { return null; } mhandlerThread = new HandlerThread("Cat Telephony service"); mhandlerThread.start(); sInstance = new CatService(ci, ca, ir, context, fh, ic); CatLog.d(sInstance, "NEW sInstance"); } else if ((ir != null) && (mIccRecords != ir)) { if (mIccRecords != null) { mIccRecords.unregisterForRecordsLoaded(sInstance); } if (mUiccApplication != null) { mUiccApplication.unregisterForReady(sInstance); } CatLog.d(sInstance, "Reinitialize the Service with SIMRecords and UiccCardApplication"); mIccRecords = ir; mUiccApplication = ca; // re-Register for SIM ready event. mIccRecords.registerForRecordsLoaded(sInstance, MSG_ID_ICC_RECORDS_LOADED, null); CatLog.d(sInstance, "sr changed reinitialize and return current sInstance"); } else { CatLog.d(sInstance, "Return current sInstance"); } return sInstance; } } /** * Used by application to get an AppInterface object. * * @return The only Service object in the system */ public static AppInterface getInstance() { return getInstance(null, null, null); } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_ID_SESSION_END: case MSG_ID_PROACTIVE_COMMAND: case MSG_ID_EVENT_NOTIFY: case MSG_ID_REFRESH: CatLog.d(this, "ril message arrived"); String data = null; if (msg.obj != null) { AsyncResult ar = (AsyncResult) msg.obj; if (ar != null && ar.result != null) { try { data = (String) ar.result; } catch (ClassCastException e) { break; } } } mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, data)); break; case MSG_ID_CALL_SETUP: mMsgDecoder.sendStartDecodingMessageParams(new RilMessage(msg.what, null)); break; case MSG_ID_ICC_RECORDS_LOADED: break; case MSG_ID_RIL_MSG_DECODED: handleRilMsg((RilMessage) msg.obj); break; case MSG_ID_RESPONSE: handleCmdResponse((CatResponseMessage) msg.obj); break; case MSG_ID_ICC_CHANGED: CatLog.d(this, "MSG_ID_ICC_CHANGED"); updateIccAvailability(); break; case MSG_ID_ICC_REFRESH: if (msg.obj != null) { AsyncResult ar = (AsyncResult) msg.obj; if (ar != null && ar.result != null) { broadcastCardStateAndIccRefreshResp(CardState.CARDSTATE_PRESENT, (IccRefreshResponse) ar.result); } else { CatLog.e(this,"Icc REFRESH with exception: " + ar.exception); } } else { CatLog.e(this, "IccRefresh Message is null"); } break; case MSG_ID_ALPHA_NOTIFY: CatLog.d(this, "Received CAT CC Alpha message from card"); if (msg.obj != null) { AsyncResult ar = (AsyncResult) msg.obj; if (ar != null && ar.result != null) { broadcastAlphaMessage((String)ar.result); } else { CatLog.d(this, "CAT Alpha message: ar.result is null"); } } else { CatLog.d(this, "CAT Alpha message: msg.obj is null"); } break; default: throw new AssertionError("Unrecognized CAT command: " + msg.what); } } protected void broadcastAlphaMessage(String alphaString) { CatLog.d(this, "Broadcasting CAT Alpha message from card: " + alphaString); Intent intent = new Intent(AppInterface.CAT_ALPHA_NOTIFY_ACTION); intent.putExtra(AppInterface.ALPHA_STRING, alphaString); mContext.sendBroadcast(intent); } /** ** This function sends a CARD status (ABSENT, PRESENT, REFRESH) to STK_APP. ** This is triggered during ICC_REFRESH or CARD STATE changes. In case ** REFRESH, additional information is sent in 'refresh_result' ** **/ protected void broadcastCardStateAndIccRefreshResp(CardState cardState, IccRefreshResponse iccRefreshState) { Intent intent = new Intent(AppInterface.CAT_ICC_STATUS_CHANGE); boolean cardPresent = (cardState == CardState.CARDSTATE_PRESENT); if (iccRefreshState != null) { //This case is when MSG_ID_ICC_REFRESH is received. intent.putExtra(AppInterface.REFRESH_RESULT, iccRefreshState.refreshResult); CatLog.d(this, "Sending IccResult with Result: " + iccRefreshState.refreshResult); } // This sends an intent with CARD_ABSENT (0 - false) /CARD_PRESENT (1 - true). intent.putExtra(AppInterface.CARD_STATUS, cardPresent); CatLog.d(this, "Sending Card Status: " + cardState + " " + "cardPresent: " + cardPresent); mContext.sendBroadcast(intent); } @Override public synchronized void onCmdResponse(CatResponseMessage resMsg) { if (resMsg == null) { return; } // queue a response message. Message msg = obtainMessage(MSG_ID_RESPONSE, resMsg); msg.sendToTarget(); } private boolean validateResponse(CatResponseMessage resMsg) { boolean validResponse = false; if ((resMsg.mCmdDet.typeOfCommand == CommandType.SET_UP_EVENT_LIST.value()) || (resMsg.mCmdDet.typeOfCommand == CommandType.SET_UP_MENU.value())) { CatLog.d(this, "CmdType: " + resMsg.mCmdDet.typeOfCommand); validResponse = true; } else if (mCurrntCmd != null) { validResponse = resMsg.mCmdDet.compareTo(mCurrntCmd.mCmdDet); CatLog.d(this, "isResponse for last valid cmd: " + validResponse); } return validResponse; } private boolean removeMenu(Menu menu) { try { if (menu.items.size() == 1 && menu.items.get(0) == null) { return true; } } catch (NullPointerException e) { CatLog.d(this, "Unable to get Menu's items size"); return true; } return false; } private void handleCmdResponse(CatResponseMessage resMsg) { // Make sure the response details match the last valid command. An invalid // response is a one that doesn't have a corresponding proactive command // and sending it can "confuse" the baseband/ril. // One reason for out of order responses can be UI glitches. For example, // if the application launch an activity, and that activity is stored // by the framework inside the history stack. That activity will be // available for relaunch using the latest application dialog // (long press on the home button). Relaunching that activity can send // the same command's result again to the CatService and can cause it to // get out of sync with the SIM. This can happen in case of // non-interactive type Setup Event List and SETUP_MENU proactive commands. // Stk framework would have already sent Terminal Response to Setup Event // List and SETUP_MENU proactive commands. After sometime Stk app will send // Envelope Command/Event Download. In which case, the response details doesn't // match with last valid command (which are not related). // However, we should allow Stk framework to send the message to ICC. if (!validateResponse(resMsg)) { return; } ResponseData resp = null; boolean helpRequired = false; CommandDetails cmdDet = resMsg.getCmdDetails(); AppInterface.CommandType type = AppInterface.CommandType.fromInt(cmdDet.typeOfCommand); switch (resMsg.mResCode) { case HELP_INFO_REQUIRED: helpRequired = true; // fall through case OK: case PRFRMD_WITH_PARTIAL_COMPREHENSION: case PRFRMD_WITH_MISSING_INFO: case PRFRMD_WITH_ADDITIONAL_EFS_READ: case PRFRMD_ICON_NOT_DISPLAYED: case PRFRMD_MODIFIED_BY_NAA: case PRFRMD_LIMITED_SERVICE: case PRFRMD_WITH_MODIFICATION: case PRFRMD_NAA_NOT_ACTIVE: case PRFRMD_TONE_NOT_PLAYED: case LAUNCH_BROWSER_ERROR: case TERMINAL_CRNTLY_UNABLE_TO_PROCESS: switch (type) { case SET_UP_MENU: helpRequired = resMsg.mResCode == ResultCode.HELP_INFO_REQUIRED; sendMenuSelection(resMsg.mUsersMenuSelection, helpRequired); return; case SELECT_ITEM: resp = new SelectItemResponseData(resMsg.mUsersMenuSelection); break; case GET_INPUT: case GET_INKEY: Input input = mCurrntCmd.geInput(); if (!input.yesNo) { // when help is requested there is no need to send the text // string object. if (!helpRequired) { resp = new GetInkeyInputResponseData(resMsg.mUsersInput, input.ucs2, input.packed); } } else { resp = new GetInkeyInputResponseData( resMsg.mUsersYesNoSelection); } break; case DISPLAY_TEXT: //For screenbusy case there will be addtional information in the terminal //response. And the value of the additional information byte is 0x01. resMsg.setAdditionalInfo(0x01); break; case LAUNCH_BROWSER: break; // 3GPP TS.102.223: Open Channel alpha confirmation should not send TR case OPEN_CHANNEL: case SET_UP_CALL: mCmdIf.handleCallSetupRequestFromSim(resMsg.mUsersConfirm, null); // No need to send terminal response for SET UP CALL. The user's // confirmation result is send back using a dedicated ril message // invoked by the CommandInterface call above. mCurrntCmd = null; return; case SET_UP_EVENT_LIST: if (IDLE_SCREEN_AVAILABLE_EVENT == resMsg.mEventValue) { eventDownload(resMsg.mEventValue, DEV_ID_DISPLAY, DEV_ID_UICC, resMsg.mAddedInfo, false); } else { eventDownload(resMsg.mEventValue, DEV_ID_TERMINAL, DEV_ID_UICC, resMsg.mAddedInfo, false); } // No need to send the terminal response after event download. return; default: break; } break; case BACKWARD_MOVE_BY_USER: case USER_NOT_ACCEPT: // if the user dismissed the alert dialog for a // setup call/open channel, consider that as the user // rejecting the call. Use dedicated API for this, rather than // sending a terminal response. if (type == CommandType.SET_UP_CALL || type == CommandType.OPEN_CHANNEL) { mCmdIf.handleCallSetupRequestFromSim(false, null); mCurrntCmd = null; return; } else { resp = null; } break; case NO_RESPONSE_FROM_USER: case UICC_SESSION_TERM_BY_USER: resp = null; break; default: return; } sendTerminalResponse(cmdDet, resMsg.mResCode, resMsg.mIncludeAdditionalInfo, resMsg.mAdditionalInfo, resp); mCurrntCmd = null; } protected boolean isStkAppInstalled() { Intent intent = new Intent(AppInterface.CAT_CMD_ACTION); PackageManager pm = mContext.getPackageManager(); List<ResolveInfo> broadcastReceivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_META_DATA); int numReceiver = broadcastReceivers == null ? 0 : broadcastReceivers.size(); return (numReceiver > 0); } protected void updateIccAvailability() { CardState newState = CardState.CARDSTATE_ABSENT; if (null == mUiccController) { return; } UiccCard newCard = mUiccController.getUiccCard(); if (newCard != null) { newState = newCard.getCardState(); } CardState oldState = mCardState; mCardState = newState; CatLog.d(this,"New Card State = " + newState + " " + "Old Card State = " + oldState); if (oldState == CardState.CARDSTATE_PRESENT && newState != CardState.CARDSTATE_PRESENT) { broadcastCardStateAndIccRefreshResp(newState, null); } else if (oldState != CardState.CARDSTATE_PRESENT && newState == CardState.CARDSTATE_PRESENT) { // Card moved to PRESENT STATE. mCmdIf.reportStkServiceIsRunning(null); } } }
true
true
private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) { CatLog.d(this, cmdParams.getCommandType().name()); CharSequence message; ResultCode resultCode; CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams); switch (cmdParams.getCommandType()) { case SET_UP_MENU: if (removeMenu(cmdMsg.getMenu())) { mMenuCmd = null; } else { mMenuCmd = cmdMsg; } resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet, resultCode, false, 0, null); break; case DISPLAY_TEXT: // when application is not required to respond, send an immediate response. if (!cmdMsg.geTextMessage().responseNeeded) { resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet, resultCode, false, 0, null); } break; case REFRESH: //Stk app service displays alpha id to user if it is present, nothing to do here CatLog.d(this, "Pass Refresh to Stk app"); break; case SET_UP_IDLE_MODE_TEXT: resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet,resultCode, false, 0, null); break; case SET_UP_EVENT_LIST: if (isSupportedSetupEventCommand(cmdMsg)) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } else { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, false, 0, null); } break; case PROVIDE_LOCAL_INFORMATION: ResponseData resp; switch (cmdParams.mCmdDet.commandQualifier) { case CommandParamsFactory.DTTZ_SETTING: resp = new DTTZResponseData(null); sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); break; case CommandParamsFactory.LANGUAGE_SETTING: resp = new LanguageResponseData(Locale.getDefault().getLanguage()); sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); break; default: sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } // No need to start STK app here. return; case LAUNCH_BROWSER: if ((((LaunchBrowserParams) cmdParams).mConfirmMsg.text != null) && (((LaunchBrowserParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.launchBrowserDefault); ((LaunchBrowserParams) cmdParams).mConfirmMsg.text = message.toString(); } break; case SELECT_ITEM: case GET_INPUT: case GET_INKEY: break; case SEND_DTMF: case SEND_SMS: case SEND_SS: case SEND_USSD: if ((((DisplayTextParams)cmdParams).mTextMsg.text != null) && (((DisplayTextParams)cmdParams).mTextMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.sending); ((DisplayTextParams)cmdParams).mTextMsg.text = message.toString(); } break; case PLAY_TONE: break; case SET_UP_CALL: if ((((CallSetupParams) cmdParams).mConfirmMsg.text != null) && (((CallSetupParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.SetupCallDefault); ((CallSetupParams) cmdParams).mConfirmMsg.text = message.toString(); } break; case OPEN_CHANNEL: case CLOSE_CHANNEL: case RECEIVE_DATA: case SEND_DATA: BIPClientParams cmd = (BIPClientParams) cmdParams; /* Per 3GPP specification 102.223, * if the alpha identifier is not provided by the UICC, * the terminal MAY give information to the user * noAlphaUsrCnf defines if you need to show user confirmation or not */ boolean noAlphaUsrCnf = false; try { noAlphaUsrCnf = mContext.getResources().getBoolean( com.android.internal.R.bool.config_stkNoAlphaUsrCnf); } catch (NotFoundException e) { noAlphaUsrCnf = false; } if ((cmd.mTextMsg.text == null) && (cmd.mHasAlphaId || noAlphaUsrCnf)) { CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id"); // If alpha length is zero, we just respond with OK. if (isProactiveCmd) { if (cmdParams.getCommandType() == CommandType.OPEN_CHANNEL) { mCmdIf.handleCallSetupRequestFromSim(true, null); } else { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } } return; } // Respond with permanent failure to avoid retry if STK app is not present. if (!mStkAppInstalled) { CatLog.d(this, "No STK application found."); if (isProactiveCmd) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, false, 0, null); return; } } /* * CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by * either PROACTIVE_COMMAND or EVENT_NOTIFY. * If PROACTIVE_COMMAND is used for those commands, send terminal * response here. */ if (isProactiveCmd && ((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL) || (cmdParams.getCommandType() == CommandType.RECEIVE_DATA) || (cmdParams.getCommandType() == CommandType.SEND_DATA))) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } break; default: CatLog.d(this, "Unsupported command"); return; } mCurrntCmd = cmdMsg; broadcastCatCmdIntent(cmdMsg); }
private void handleCommand(CommandParams cmdParams, boolean isProactiveCmd) { CatLog.d(this, cmdParams.getCommandType().name()); CharSequence message; ResultCode resultCode; CatCmdMessage cmdMsg = new CatCmdMessage(cmdParams); switch (cmdParams.getCommandType()) { case SET_UP_MENU: if (removeMenu(cmdMsg.getMenu())) { mMenuCmd = null; } else { mMenuCmd = cmdMsg; } resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet, resultCode, false, 0, null); break; case DISPLAY_TEXT: // when application is not required to respond, send an immediate response. if (!cmdMsg.geTextMessage().responseNeeded) { resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet, resultCode, false, 0, null); } break; case REFRESH: //Stk app service displays alpha id to user if it is present, nothing to do here CatLog.d(this, "Pass Refresh to Stk app"); break; case SET_UP_IDLE_MODE_TEXT: resultCode = cmdParams.mLoadIconFailed ? ResultCode.PRFRMD_ICON_NOT_DISPLAYED : ResultCode.OK; sendTerminalResponse(cmdParams.mCmdDet,resultCode, false, 0, null); break; case SET_UP_EVENT_LIST: if (isSupportedSetupEventCommand(cmdMsg)) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } else { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, false, 0, null); } break; case PROVIDE_LOCAL_INFORMATION: ResponseData resp; switch (cmdParams.mCmdDet.commandQualifier) { case CommandParamsFactory.DTTZ_SETTING: resp = new DTTZResponseData(null); sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); break; case CommandParamsFactory.LANGUAGE_SETTING: resp = new LanguageResponseData(Locale.getDefault().getLanguage()); sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, resp); break; default: sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } // No need to start STK app here. return; case LAUNCH_BROWSER: if ((((LaunchBrowserParams) cmdParams).mConfirmMsg.text != null) && (((LaunchBrowserParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.launchBrowserDefault); ((LaunchBrowserParams) cmdParams).mConfirmMsg.text = message.toString(); } break; case SELECT_ITEM: case GET_INPUT: case GET_INKEY: break; case SEND_DTMF: case SEND_SMS: case SEND_SS: case SEND_USSD: if ((((DisplayTextParams)cmdParams).mTextMsg.text != null) && (((DisplayTextParams)cmdParams).mTextMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.sending); ((DisplayTextParams)cmdParams).mTextMsg.text = message.toString(); } break; case PLAY_TONE: break; case SET_UP_CALL: if ((((CallSetupParams) cmdParams).mConfirmMsg.text != null) && (((CallSetupParams) cmdParams).mConfirmMsg.text.equals(STK_DEFAULT))) { message = mContext.getText(com.android.internal.R.string.SetupCallDefault); ((CallSetupParams) cmdParams).mConfirmMsg.text = message.toString(); } break; case OPEN_CHANNEL: case CLOSE_CHANNEL: case RECEIVE_DATA: case SEND_DATA: BIPClientParams cmd = (BIPClientParams) cmdParams; /* Per 3GPP specification 102.223, * if the alpha identifier is not provided by the UICC, * the terminal MAY give information to the user * noAlphaUsrCnf defines if you need to show user confirmation or not */ boolean noAlphaUsrCnf = false; try { noAlphaUsrCnf = mContext.getResources().getBoolean( com.android.internal.R.bool.config_stkNoAlphaUsrCnf); } catch (NotFoundException e) { noAlphaUsrCnf = false; } if ((cmd.mTextMsg.text == null) && (cmd.mHasAlphaId || noAlphaUsrCnf)) { CatLog.d(this, "cmd " + cmdParams.getCommandType() + " with null alpha id"); // If alpha length is zero, we just respond with OK. if (isProactiveCmd) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } else if (cmdParams.getCommandType() == CommandType.OPEN_CHANNEL) { mCmdIf.handleCallSetupRequestFromSim(true, null); } return; } // Respond with permanent failure to avoid retry if STK app is not present. if (!mStkAppInstalled) { CatLog.d(this, "No STK application found."); if (isProactiveCmd) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.BEYOND_TERMINAL_CAPABILITY, false, 0, null); return; } } /* * CLOSE_CHANNEL, RECEIVE_DATA and SEND_DATA can be delivered by * either PROACTIVE_COMMAND or EVENT_NOTIFY. * If PROACTIVE_COMMAND is used for those commands, send terminal * response here. */ if (isProactiveCmd && ((cmdParams.getCommandType() == CommandType.CLOSE_CHANNEL) || (cmdParams.getCommandType() == CommandType.RECEIVE_DATA) || (cmdParams.getCommandType() == CommandType.SEND_DATA))) { sendTerminalResponse(cmdParams.mCmdDet, ResultCode.OK, false, 0, null); } break; default: CatLog.d(this, "Unsupported command"); return; } mCurrntCmd = cmdMsg; broadcastCatCmdIntent(cmdMsg); }
diff --git a/src/com/android/exchange/adapter/AbstractSyncParser.java b/src/com/android/exchange/adapter/AbstractSyncParser.java index c913af4..4c73fd8 100644 --- a/src/com/android/exchange/adapter/AbstractSyncParser.java +++ b/src/com/android/exchange/adapter/AbstractSyncParser.java @@ -1,197 +1,200 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange.adapter; import com.android.email.provider.EmailContent.Account; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.MailboxColumns; import com.android.exchange.EasSyncService; import com.android.exchange.SyncManager; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import java.io.IOException; import java.io.InputStream; /** * Base class for the Email and PIM sync parsers * Handles the basic flow of syncKeys, looping to get more data, handling errors, etc. * Each subclass must implement a handful of methods that relate specifically to the data type * */ public abstract class AbstractSyncParser extends Parser { protected EasSyncService mService; protected Mailbox mMailbox; protected Account mAccount; protected Context mContext; protected ContentResolver mContentResolver; protected AbstractSyncAdapter mAdapter; public AbstractSyncParser(InputStream in, AbstractSyncAdapter adapter) throws IOException { super(in); mAdapter = adapter; mService = adapter.mService; mContext = mService.mContext; mContentResolver = mContext.getContentResolver(); mMailbox = mService.mMailbox; mAccount = mService.mAccount; } /** * Read, parse, and act on incoming commands from the Exchange server * @throws IOException if the connection is broken */ public abstract void commandsParser() throws IOException; /** * Read, parse, and act on server responses * @throws IOException */ public abstract void responsesParser() throws IOException; /** * Commit any changes found during parsing * @throws IOException */ public abstract void commit() throws IOException; /** * Delete all records of this class in this account */ public abstract void wipe(); /** * Loop through the top-level structure coming from the Exchange server * Sync keys and the more available flag are handled here, whereas specific data parsing * is handled by abstract methods implemented for each data class (e.g. Email, Contacts, etc.) */ @Override public boolean parse() throws IOException { int status; boolean moreAvailable = false; int interval = mMailbox.mSyncInterval; // If we're not at the top of the xml tree, throw an exception if (nextTag(START_DOCUMENT) != Tags.SYNC_SYNC) { throw new EasParserException(); } boolean mailboxUpdated = false; ContentValues cv = new ContentValues(); // Loop here through the remaining xml while (nextTag(START_DOCUMENT) != END_DOCUMENT) { if (tag == Tags.SYNC_COLLECTION || tag == Tags.SYNC_COLLECTIONS) { // Ignore these tags, since we've only got one collection syncing in this loop } else if (tag == Tags.SYNC_STATUS) { // Status = 1 is success; everything else is a failure status = getValueInt(); if (status != 1) { mService.errorLog("Sync failed: " + status); // Status = 3 means invalid sync key if (status == 3) { // Must delete all of the data and start over with syncKey of "0" mAdapter.setSyncKey("0", false); // Make this a push box through the first sync // TODO Make frequency conditional on user settings! mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; mService.errorLog("Bad sync key; RESET and delete data"); wipe(); // Indicate there's more so that we'll start syncing again moreAvailable = true; } else if (status == 8) { // This is Bad; it means the server doesn't recognize the serverId it // sent us. What's needed is a refresh of the folder list. SyncManager.reloadFolderList(mContext, mAccount.mId, true); } // TODO Look at other error codes and consider what's to be done } } else if (tag == Tags.SYNC_COMMANDS) { commandsParser(); } else if (tag == Tags.SYNC_RESPONSES) { responsesParser(); } else if (tag == Tags.SYNC_MORE_AVAILABLE) { moreAvailable = true; } else if (tag == Tags.SYNC_SYNC_KEY) { if (mAdapter.getSyncKey().equals("0")) { moreAvailable = true; } String newKey = getValue(); userLog("Parsed key for ", mMailbox.mDisplayName, ": ", newKey); if (!newKey.equals(mMailbox.mSyncKey)) { mAdapter.setSyncKey(newKey, true); cv.put(MailboxColumns.SYNC_KEY, newKey); mailboxUpdated = true; - } + } else if (moreAvailable) { + userLog("!! SyncKey hasn't changed, setting moreAvailable = false"); + moreAvailable = false; + } // If we were pushing (i.e. auto-start), now we'll become ping-triggered if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) { mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PING; } } else { skipTag(); } } // Commit any changes commit(); boolean abortSyncs = false; // If the sync interval has changed, we need to save it if (mMailbox.mSyncInterval != interval) { cv.put(MailboxColumns.SYNC_INTERVAL, mMailbox.mSyncInterval); mailboxUpdated = true; // If there are changes, and we were bounced from push/ping, try again } else if (mService.mChangeCount > 0 && mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH && mMailbox.mSyncInterval > 0) { userLog("Changes found to ping loop mailbox ", mMailbox.mDisplayName, ": will ping."); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING); mailboxUpdated = true; abortSyncs = true; } if (mailboxUpdated) { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { mMailbox.update(mContext, cv); } } } if (abortSyncs) { userLog("Aborting account syncs due to mailbox change to ping..."); SyncManager.stopAccountSyncs(mAccount.mId); } // Let the caller know that there's more to do userLog("Returning moreAvailable = " + moreAvailable); return moreAvailable; } void userLog(String ...strings) { mService.userLog(strings); } void userLog(String string, int num, String string2) { mService.userLog(string, num, string2); } }
true
true
public boolean parse() throws IOException { int status; boolean moreAvailable = false; int interval = mMailbox.mSyncInterval; // If we're not at the top of the xml tree, throw an exception if (nextTag(START_DOCUMENT) != Tags.SYNC_SYNC) { throw new EasParserException(); } boolean mailboxUpdated = false; ContentValues cv = new ContentValues(); // Loop here through the remaining xml while (nextTag(START_DOCUMENT) != END_DOCUMENT) { if (tag == Tags.SYNC_COLLECTION || tag == Tags.SYNC_COLLECTIONS) { // Ignore these tags, since we've only got one collection syncing in this loop } else if (tag == Tags.SYNC_STATUS) { // Status = 1 is success; everything else is a failure status = getValueInt(); if (status != 1) { mService.errorLog("Sync failed: " + status); // Status = 3 means invalid sync key if (status == 3) { // Must delete all of the data and start over with syncKey of "0" mAdapter.setSyncKey("0", false); // Make this a push box through the first sync // TODO Make frequency conditional on user settings! mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; mService.errorLog("Bad sync key; RESET and delete data"); wipe(); // Indicate there's more so that we'll start syncing again moreAvailable = true; } else if (status == 8) { // This is Bad; it means the server doesn't recognize the serverId it // sent us. What's needed is a refresh of the folder list. SyncManager.reloadFolderList(mContext, mAccount.mId, true); } // TODO Look at other error codes and consider what's to be done } } else if (tag == Tags.SYNC_COMMANDS) { commandsParser(); } else if (tag == Tags.SYNC_RESPONSES) { responsesParser(); } else if (tag == Tags.SYNC_MORE_AVAILABLE) { moreAvailable = true; } else if (tag == Tags.SYNC_SYNC_KEY) { if (mAdapter.getSyncKey().equals("0")) { moreAvailable = true; } String newKey = getValue(); userLog("Parsed key for ", mMailbox.mDisplayName, ": ", newKey); if (!newKey.equals(mMailbox.mSyncKey)) { mAdapter.setSyncKey(newKey, true); cv.put(MailboxColumns.SYNC_KEY, newKey); mailboxUpdated = true; } // If we were pushing (i.e. auto-start), now we'll become ping-triggered if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) { mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PING; } } else { skipTag(); } } // Commit any changes commit(); boolean abortSyncs = false; // If the sync interval has changed, we need to save it if (mMailbox.mSyncInterval != interval) { cv.put(MailboxColumns.SYNC_INTERVAL, mMailbox.mSyncInterval); mailboxUpdated = true; // If there are changes, and we were bounced from push/ping, try again } else if (mService.mChangeCount > 0 && mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH && mMailbox.mSyncInterval > 0) { userLog("Changes found to ping loop mailbox ", mMailbox.mDisplayName, ": will ping."); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING); mailboxUpdated = true; abortSyncs = true; } if (mailboxUpdated) { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { mMailbox.update(mContext, cv); } } } if (abortSyncs) { userLog("Aborting account syncs due to mailbox change to ping..."); SyncManager.stopAccountSyncs(mAccount.mId); } // Let the caller know that there's more to do userLog("Returning moreAvailable = " + moreAvailable); return moreAvailable; }
public boolean parse() throws IOException { int status; boolean moreAvailable = false; int interval = mMailbox.mSyncInterval; // If we're not at the top of the xml tree, throw an exception if (nextTag(START_DOCUMENT) != Tags.SYNC_SYNC) { throw new EasParserException(); } boolean mailboxUpdated = false; ContentValues cv = new ContentValues(); // Loop here through the remaining xml while (nextTag(START_DOCUMENT) != END_DOCUMENT) { if (tag == Tags.SYNC_COLLECTION || tag == Tags.SYNC_COLLECTIONS) { // Ignore these tags, since we've only got one collection syncing in this loop } else if (tag == Tags.SYNC_STATUS) { // Status = 1 is success; everything else is a failure status = getValueInt(); if (status != 1) { mService.errorLog("Sync failed: " + status); // Status = 3 means invalid sync key if (status == 3) { // Must delete all of the data and start over with syncKey of "0" mAdapter.setSyncKey("0", false); // Make this a push box through the first sync // TODO Make frequency conditional on user settings! mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH; mService.errorLog("Bad sync key; RESET and delete data"); wipe(); // Indicate there's more so that we'll start syncing again moreAvailable = true; } else if (status == 8) { // This is Bad; it means the server doesn't recognize the serverId it // sent us. What's needed is a refresh of the folder list. SyncManager.reloadFolderList(mContext, mAccount.mId, true); } // TODO Look at other error codes and consider what's to be done } } else if (tag == Tags.SYNC_COMMANDS) { commandsParser(); } else if (tag == Tags.SYNC_RESPONSES) { responsesParser(); } else if (tag == Tags.SYNC_MORE_AVAILABLE) { moreAvailable = true; } else if (tag == Tags.SYNC_SYNC_KEY) { if (mAdapter.getSyncKey().equals("0")) { moreAvailable = true; } String newKey = getValue(); userLog("Parsed key for ", mMailbox.mDisplayName, ": ", newKey); if (!newKey.equals(mMailbox.mSyncKey)) { mAdapter.setSyncKey(newKey, true); cv.put(MailboxColumns.SYNC_KEY, newKey); mailboxUpdated = true; } else if (moreAvailable) { userLog("!! SyncKey hasn't changed, setting moreAvailable = false"); moreAvailable = false; } // If we were pushing (i.e. auto-start), now we'll become ping-triggered if (mMailbox.mSyncInterval == Mailbox.CHECK_INTERVAL_PUSH) { mMailbox.mSyncInterval = Mailbox.CHECK_INTERVAL_PING; } } else { skipTag(); } } // Commit any changes commit(); boolean abortSyncs = false; // If the sync interval has changed, we need to save it if (mMailbox.mSyncInterval != interval) { cv.put(MailboxColumns.SYNC_INTERVAL, mMailbox.mSyncInterval); mailboxUpdated = true; // If there are changes, and we were bounced from push/ping, try again } else if (mService.mChangeCount > 0 && mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH && mMailbox.mSyncInterval > 0) { userLog("Changes found to ping loop mailbox ", mMailbox.mDisplayName, ": will ping."); cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PING); mailboxUpdated = true; abortSyncs = true; } if (mailboxUpdated) { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { mMailbox.update(mContext, cv); } } } if (abortSyncs) { userLog("Aborting account syncs due to mailbox change to ping..."); SyncManager.stopAccountSyncs(mAccount.mId); } // Let the caller know that there's more to do userLog("Returning moreAvailable = " + moreAvailable); return moreAvailable; }
diff --git a/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java b/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java index 6b8ec8da8..f1ba726c1 100644 --- a/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java +++ b/orbisgis-ui/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/actions/ExecuteScriptProcess.java @@ -1,225 +1,225 @@ /** * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. * * OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG" * team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488. * * Copyright (C) 2007-1012 IRSTV (FR CNRS 2488) * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * or contact directly: * info_at_ orbisgis.org */ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. OrbisGIS is * distributed under GPL 3 license. It is produced by the "Atelier SIG" team of * the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488. * * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * * or contact directly: * info _at_ orbisgis.org */ package org.orbisgis.core.ui.plugins.views.sqlConsole.actions; import org.apache.log4j.Logger; import org.orbisgis.core.DataManager; import org.orbisgis.core.Services; import org.orbisgis.core.background.BackgroundJob; import org.orbisgis.core.layerModel.ILayer; import org.orbisgis.core.layerModel.LayerException; import org.orbisgis.core.layerModel.MapContext; import org.orbisgis.core.ui.editors.map.MapContextManager; import org.orbisgis.core.ui.plugins.views.output.OutputManager; import org.orbisgis.core.ui.plugins.views.sqlConsole.ui.SQLConsolePanel; import org.orbisgis.progress.ProgressMonitor; import org.gdms.data.DataSource; import org.gdms.data.DataSourceCreationException; import org.gdms.data.DataSourceFactory; import org.gdms.data.schema.Metadata; import org.gdms.data.schema.MetadataUtilities; import org.gdms.driver.DriverException; import org.gdms.sql.engine.Engine; import org.gdms.sql.engine.ParseException; import org.gdms.sql.engine.SQLStatement; import org.gdms.sql.engine.SemanticException; public class ExecuteScriptProcess implements BackgroundJob { private String script; private static final Logger logger = Logger.getLogger(ExecuteScriptProcess.class); private SQLConsolePanel panel; public ExecuteScriptProcess(String script) { this.script = script; } public ExecuteScriptProcess(String script, SQLConsolePanel panel) { this.script = script; this.panel = panel; } @Override public String getTaskName() { return "Executing script"; } @Override public void run(ProgressMonitor pm) { DataManager dataManager = (DataManager) Services.getService(DataManager.class); DataSourceFactory dsf = dataManager.getDataSourceFactory(); SQLStatement[] statements = null; long t1 = System.currentTimeMillis(); try { logger.debug("Preparing script: " + script); try { - statements = Engine.parse(script, dsf.getProperties()); + statements = Engine.parseScript(script, dsf.getProperties()).getStatements(); } catch (ParseException e) { Services.getErrorManager().error("Cannot parse script", e); if (panel != null) { panel.setStatusMessage("Failed to parse the script."); } return; } MapContext vc = ((MapContextManager) Services.getService(MapContextManager.class)).getActiveMapContext(); for (int i = 0; i < statements.length; i++) { SQLStatement st = statements[i]; boolean spatial; logger.info("Running instruction " + (i + 1) + " / " + statements.length + ":"); logger.info(st.getSQL()); try { st.setDataSourceFactory(dsf); st.setProgressMonitor(pm); st.prepare(); Metadata metadata = st.getResultMetadata(); if (metadata != null) { spatial = MetadataUtilities.isSpatial(metadata); DataSource ds = dsf.getDataSource(st, DataSourceFactory.DEFAULT, pm); if (pm.isCancelled()) { break; } if (spatial && vc != null) { try { final ILayer layer = dataManager.createLayer(ds); vc.getLayerModel().insertLayer(layer, 0); } catch (LayerException e) { Services.getErrorManager().error( "Impossible to create the layer:" + ds.getName(), e); break; } } else { OutputManager om = Services.getService(OutputManager.class); ds.open(); StringBuilder aux = new StringBuilder(); int fc = ds.getMetadata().getFieldCount(); int rc = (int) ds.getRowCount(); for (int j = 0; j < fc; j++) { om.print(ds.getFieldName(j)); om.print("\t"); } om.println(""); for (int row = 0; row < rc; row++) { for (int j = 0; j < fc; j++) { om.print(ds.getFieldValue(row, j).toString()); om.print("\t"); } om.println(""); if (row > 100) { om.println("and more... total " + rc + " rows"); break; } } ds.close(); om.println(aux.toString()); } } else { try { st.execute(); } finally { st.cleanUp(); } if (pm.isCancelled()) { break; } } } catch (DataSourceCreationException e) { Services.getErrorManager().error( "Cannot create the DataSource:" + st.getSQL(), e); break; } // DO NOT REMOVE // lets the GC remove a statement while the following ones are executed, // since we have no use for it now. statements[i] = null; pm.progressTo(100 * i / statements.length); } } catch (DriverException e) { Services.getErrorManager().error("Data access error:", e); } catch (SemanticException e) { Services.getErrorManager().error("SQL Semantic Error", e); } long t2 = System.currentTimeMillis(); double lastExecTime = ((t2 - t1) / 1000.0); logger.debug("Execution time: " + lastExecTime); if (panel != null) { panel.setStatusMessage("Execution time: " + lastExecTime); } } }
true
true
public void run(ProgressMonitor pm) { DataManager dataManager = (DataManager) Services.getService(DataManager.class); DataSourceFactory dsf = dataManager.getDataSourceFactory(); SQLStatement[] statements = null; long t1 = System.currentTimeMillis(); try { logger.debug("Preparing script: " + script); try { statements = Engine.parse(script, dsf.getProperties()); } catch (ParseException e) { Services.getErrorManager().error("Cannot parse script", e); if (panel != null) { panel.setStatusMessage("Failed to parse the script."); } return; } MapContext vc = ((MapContextManager) Services.getService(MapContextManager.class)).getActiveMapContext(); for (int i = 0; i < statements.length; i++) { SQLStatement st = statements[i]; boolean spatial; logger.info("Running instruction " + (i + 1) + " / " + statements.length + ":"); logger.info(st.getSQL()); try { st.setDataSourceFactory(dsf); st.setProgressMonitor(pm); st.prepare(); Metadata metadata = st.getResultMetadata(); if (metadata != null) { spatial = MetadataUtilities.isSpatial(metadata); DataSource ds = dsf.getDataSource(st, DataSourceFactory.DEFAULT, pm); if (pm.isCancelled()) { break; } if (spatial && vc != null) { try { final ILayer layer = dataManager.createLayer(ds); vc.getLayerModel().insertLayer(layer, 0); } catch (LayerException e) { Services.getErrorManager().error( "Impossible to create the layer:" + ds.getName(), e); break; } } else { OutputManager om = Services.getService(OutputManager.class); ds.open(); StringBuilder aux = new StringBuilder(); int fc = ds.getMetadata().getFieldCount(); int rc = (int) ds.getRowCount(); for (int j = 0; j < fc; j++) { om.print(ds.getFieldName(j)); om.print("\t"); } om.println(""); for (int row = 0; row < rc; row++) { for (int j = 0; j < fc; j++) { om.print(ds.getFieldValue(row, j).toString()); om.print("\t"); } om.println(""); if (row > 100) { om.println("and more... total " + rc + " rows"); break; } } ds.close(); om.println(aux.toString()); } } else { try { st.execute(); } finally { st.cleanUp(); } if (pm.isCancelled()) { break; } } } catch (DataSourceCreationException e) { Services.getErrorManager().error( "Cannot create the DataSource:" + st.getSQL(), e); break; } // DO NOT REMOVE // lets the GC remove a statement while the following ones are executed, // since we have no use for it now. statements[i] = null; pm.progressTo(100 * i / statements.length); } } catch (DriverException e) { Services.getErrorManager().error("Data access error:", e); } catch (SemanticException e) { Services.getErrorManager().error("SQL Semantic Error", e); } long t2 = System.currentTimeMillis(); double lastExecTime = ((t2 - t1) / 1000.0); logger.debug("Execution time: " + lastExecTime); if (panel != null) { panel.setStatusMessage("Execution time: " + lastExecTime); } }
public void run(ProgressMonitor pm) { DataManager dataManager = (DataManager) Services.getService(DataManager.class); DataSourceFactory dsf = dataManager.getDataSourceFactory(); SQLStatement[] statements = null; long t1 = System.currentTimeMillis(); try { logger.debug("Preparing script: " + script); try { statements = Engine.parseScript(script, dsf.getProperties()).getStatements(); } catch (ParseException e) { Services.getErrorManager().error("Cannot parse script", e); if (panel != null) { panel.setStatusMessage("Failed to parse the script."); } return; } MapContext vc = ((MapContextManager) Services.getService(MapContextManager.class)).getActiveMapContext(); for (int i = 0; i < statements.length; i++) { SQLStatement st = statements[i]; boolean spatial; logger.info("Running instruction " + (i + 1) + " / " + statements.length + ":"); logger.info(st.getSQL()); try { st.setDataSourceFactory(dsf); st.setProgressMonitor(pm); st.prepare(); Metadata metadata = st.getResultMetadata(); if (metadata != null) { spatial = MetadataUtilities.isSpatial(metadata); DataSource ds = dsf.getDataSource(st, DataSourceFactory.DEFAULT, pm); if (pm.isCancelled()) { break; } if (spatial && vc != null) { try { final ILayer layer = dataManager.createLayer(ds); vc.getLayerModel().insertLayer(layer, 0); } catch (LayerException e) { Services.getErrorManager().error( "Impossible to create the layer:" + ds.getName(), e); break; } } else { OutputManager om = Services.getService(OutputManager.class); ds.open(); StringBuilder aux = new StringBuilder(); int fc = ds.getMetadata().getFieldCount(); int rc = (int) ds.getRowCount(); for (int j = 0; j < fc; j++) { om.print(ds.getFieldName(j)); om.print("\t"); } om.println(""); for (int row = 0; row < rc; row++) { for (int j = 0; j < fc; j++) { om.print(ds.getFieldValue(row, j).toString()); om.print("\t"); } om.println(""); if (row > 100) { om.println("and more... total " + rc + " rows"); break; } } ds.close(); om.println(aux.toString()); } } else { try { st.execute(); } finally { st.cleanUp(); } if (pm.isCancelled()) { break; } } } catch (DataSourceCreationException e) { Services.getErrorManager().error( "Cannot create the DataSource:" + st.getSQL(), e); break; } // DO NOT REMOVE // lets the GC remove a statement while the following ones are executed, // since we have no use for it now. statements[i] = null; pm.progressTo(100 * i / statements.length); } } catch (DriverException e) { Services.getErrorManager().error("Data access error:", e); } catch (SemanticException e) { Services.getErrorManager().error("SQL Semantic Error", e); } long t2 = System.currentTimeMillis(); double lastExecTime = ((t2 - t1) / 1000.0); logger.debug("Execution time: " + lastExecTime); if (panel != null) { panel.setStatusMessage("Execution time: " + lastExecTime); } }
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/GadgetRenderer.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/GadgetRenderer.java index 24aabf60..9f88749a 100644 --- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/GadgetRenderer.java +++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/GadgetRenderer.java @@ -1,383 +1,384 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shindig.gadgets.http; import org.apache.shindig.gadgets.Gadget; import org.apache.shindig.gadgets.GadgetContentFilter; import org.apache.shindig.gadgets.GadgetContext; import org.apache.shindig.gadgets.GadgetException; import org.apache.shindig.gadgets.GadgetFeatureRegistry; import org.apache.shindig.gadgets.GadgetServerConfigReader; import org.apache.shindig.gadgets.JsLibrary; import org.apache.shindig.gadgets.SyndicatorConfig; import org.apache.shindig.gadgets.spec.MessageBundle; import org.apache.shindig.gadgets.spec.View; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Handles processing a single http request */ public class GadgetRenderer { private static final String CAJA_PARAM = "caja"; private static final String LIBS_PARAM_NAME = "libs"; private static final Logger logger = Logger.getLogger("org.apache.shindig.gadgets"); public static final String STRICT_MODE_DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"; private final HttpServletRequest request; private final HttpServletResponse response; private final CrossServletState state; private final GadgetContext context; private final List<GadgetContentFilter> filters; /** * Processes a single rendering request and produces output html or errors. * * @throws IOException */ public void process() throws IOException { URI url = context.getUrl(); if (url == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing or malformed url parameter"); return; } if (!"http".equals(url.getScheme()) && !"https".equals(url.getScheme())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported scheme (must be http or https)."); return; } if (!validateParent()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported parent parameter. Check your syndicator code."); return; } if (getUseCaja(request)) { filters.add(new CajaContentFilter(url)); } try { Gadget gadget = state.getGadgetServer().processGadget(context); outputGadget(gadget); } catch (GadgetException e) { outputErrors(e); } } /** * Renders a successfully processed gadget. * * @param gadget * @throws IOException * @throws GadgetException */ private void outputGadget(Gadget gadget) throws IOException, GadgetException { String viewName = context.getView(); View view = gadget.getSpec().getView(viewName); if (view == null) { throw new GadgetException(GadgetException.Code.UNKNOWN_VIEW_SPECIFIED, "No appropriate view could be found for this gadget"); } switch(view.getType()) { case HTML: outputHtmlGadget(gadget, view); break; case URL: outputUrlGadget(gadget, view); break; } } /** * Handles type=html gadget output. * * @param gadget * @param view * @throws IOException * @throws GadgetException */ private void outputHtmlGadget(Gadget gadget, View view) throws IOException, GadgetException { response.setContentType("text/html; charset=UTF-8"); StringBuilder markup = new StringBuilder(); if (!view.getQuirks()) { markup.append(STRICT_MODE_DOCTYPE); } // TODO: Substitute gadgets.skins values in here. String boilerPlate = "<style type=\"text/css\">" + "body,td,div,span,p{font-family:arial,sans-serif;}" + "a {color:#0000cc;}a:visited {color:#551a8b;}" + "a:active {color:#ff0000;}" + "body{margin: 0px;padding: 0px;background-color:white;}" + "</style></head></body>"; markup.append(boilerPlate); StringBuilder externJs = new StringBuilder(); StringBuilder inlineJs = new StringBuilder(); String externFmt = "<script src=\"%s\"></script>"; String forcedLibs = request.getParameter("libs"); - Set<String> libs; - if (forcedLibs == null) { - libs = new HashSet<String>(); - } else { - libs = new HashSet<String>(); - for (String lib : forcedLibs.split(":")) { - libs.add(lib); + Set<String> libs = new HashSet<String>(); + if (forcedLibs != null) { + if (forcedLibs.trim().length() == 0) { + libs.add("core"); + } else { + for (String lib : forcedLibs.split(":")) { + libs.add(lib); + } } } // Forced libs are always done first. if (libs.size() > 0) { String jsUrl = state.getJsUrl(libs, context); markup.append(String.format(externFmt, jsUrl)); // Transitive dependencies must be added. This will always include core // so is therefore always "safe". Set<GadgetFeatureRegistry.Entry> deps = new HashSet<GadgetFeatureRegistry.Entry>(); Set<String> dummy = new HashSet<String>(); GadgetFeatureRegistry registry = state.getGadgetServer().getConfig().getFeatureRegistry(); registry.getIncludedFeatures(libs, deps, dummy); for (GadgetFeatureRegistry.Entry dep : deps) { libs.add(dep.getName()); } } // Inline any libs that weren't forced for (JsLibrary library : gadget.getJsLibraries()) { JsLibrary.Type type = library.getType(); if (library.getType().equals(JsLibrary.Type.URL)) { externJs.append(String.format(externFmt, library.getContent())); } else { if (!libs.contains(library.getFeature())) { // already pulled this file in from the shared contents. if (context.getDebug()) { inlineJs.append(library.getDebugContent()); } else { inlineJs.append(library.getContent()); } } } } for (JsLibrary library : gadget.getJsLibraries()) { libs.add(library.getFeature()); } appendJsConfig(libs, inlineJs); // message bundles for prefs object. MessageBundle bundle = gadget.getMessageBundle(); String msgs = new JSONObject(bundle.getMessages()).toString(); inlineJs.append("gadgets.Prefs.setMessages_(").append(msgs).append(");"); if (inlineJs.length() > 0) { markup.append("<script><!--\n").append(inlineJs) .append("\n-->\n</script>"); } if (externJs.length() > 0) { markup.append(externJs); } List<GadgetException> gadgetExceptions = new LinkedList<GadgetException>(); String content = view.getContent(); for (GadgetContentFilter filter : filters) { content = filter.filter(content); } markup.append(content) .append("<script>gadgets.util.runOnLoadHandlers();</script>") .append("</body></html>"); if (request.getParameter("v") != null) { // Versioned files get cached indefinitely HttpUtil.setCachingHeaders(response, 0); } else { // Unversioned files get cached for 5 minutes. // TODO: This should be configurable HttpUtil.setCachingHeaders(response, 60 * 5); } response.getWriter().print(markup.toString()); } /** * Outputs a url type gadget by redirecting. * * @param gadget * @param view * @throws IOException */ private void outputUrlGadget(Gadget gadget, View view) throws IOException { // TODO: generalize this as injectedArgs on Gadget object // Preserve existing query string parameters. URI href = view.getHref(); String queryStr = href.getQuery(); StringBuilder query = new StringBuilder(queryStr == null ? "" : queryStr); // TODO: figure out a way to make this work with forced libs. Set<String> libs = gadget.getSpec().getModulePrefs().getFeatures().keySet(); appendLibsToQuery(libs, query); try { href = new URI(href.getScheme(), href.getUserInfo(), href.getHost(), href.getPort(), href.getPath(), query.toString(), href.getFragment()); } catch (URISyntaxException e) { // Not really ever going to happen; input values are already OK. response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } response.sendRedirect(href.toString()); } /** * Displays errors. * @param error * @throws IOException */ private void outputErrors(GadgetException error) throws IOException { // Log the errors here for now. We might want different severity levels // for different error codes. logger.log(Level.INFO, "Failed to render gadget", error); String message = error.getMessage(); if (message == null || message.length() == 0) { message = "Failed to render gadget: " + error.getCode().toString(); } response.getWriter().print(message); } /** * Appends libs to the query string. * @param libs * @param query */ private void appendLibsToQuery(Set<String> libs, StringBuilder query) { query.append("&") .append(LIBS_PARAM_NAME) .append("=") .append(state.getJsUrl(libs, context)); } /** * @param req * @return Whether or not to use caja. */ protected boolean getUseCaja(HttpServletRequest req) { String cajaParam = request.getParameter(CAJA_PARAM); return "1".equals(cajaParam); } /** * @param reqs The features you require. * @param js Existing js, to which the configuration will be appended. */ private void appendJsConfig(Set<String> reqs, StringBuilder js) { GadgetServerConfigReader config = state.getGadgetServer().getConfig(); SyndicatorConfig syndConf = config.getSyndicatorConfig(); js.append(HttpUtil.getJsConfig(syndConf, context, reqs)); } /** * Validates that the parent parameter was acceptable. * * @return True if the parent parameter is valid for the current * syndicator. */ private boolean validateParent() { String syndicator = request.getParameter("synd"); if (syndicator == null) { syndicator = SyndicatorConfig.DEFAULT_SYNDICATOR; } String parent = request.getParameter("parent"); if (parent == null) { // If there is no parent parameter, we are still safe because no // dependent code ever has to trust it anyway. return true; } SyndicatorConfig syndConf = state.getGadgetServer().getConfig().getSyndicatorConfig(); try { JSONArray parents = syndConf.getJsonArray(syndicator, "gadgets.parent"); if (parents == null) { return true; } else { // We need to check each possible parent parameter against this regex. for (int i = 0, j = parents.length(); i < j; ++i) { // TODO: Should patterns be cached? Recompiling every request // seems wasteful. if (Pattern.matches(parents.getString(i), parent)) { return true; } } } } catch (JSONException e) { logger.log(Level.WARNING, "Configuration error", e); } return false; } public GadgetRenderer(HttpServletRequest request, HttpServletResponse response, CrossServletState state) { this.request = request; this.response = response; this.state = state; context = new HttpGadgetContext(request); filters = new LinkedList<GadgetContentFilter>(); } }
true
true
private void outputHtmlGadget(Gadget gadget, View view) throws IOException, GadgetException { response.setContentType("text/html; charset=UTF-8"); StringBuilder markup = new StringBuilder(); if (!view.getQuirks()) { markup.append(STRICT_MODE_DOCTYPE); } // TODO: Substitute gadgets.skins values in here. String boilerPlate = "<style type=\"text/css\">" + "body,td,div,span,p{font-family:arial,sans-serif;}" + "a {color:#0000cc;}a:visited {color:#551a8b;}" + "a:active {color:#ff0000;}" + "body{margin: 0px;padding: 0px;background-color:white;}" + "</style></head></body>"; markup.append(boilerPlate); StringBuilder externJs = new StringBuilder(); StringBuilder inlineJs = new StringBuilder(); String externFmt = "<script src=\"%s\"></script>"; String forcedLibs = request.getParameter("libs"); Set<String> libs; if (forcedLibs == null) { libs = new HashSet<String>(); } else { libs = new HashSet<String>(); for (String lib : forcedLibs.split(":")) { libs.add(lib); } } // Forced libs are always done first. if (libs.size() > 0) { String jsUrl = state.getJsUrl(libs, context); markup.append(String.format(externFmt, jsUrl)); // Transitive dependencies must be added. This will always include core // so is therefore always "safe". Set<GadgetFeatureRegistry.Entry> deps = new HashSet<GadgetFeatureRegistry.Entry>(); Set<String> dummy = new HashSet<String>(); GadgetFeatureRegistry registry = state.getGadgetServer().getConfig().getFeatureRegistry(); registry.getIncludedFeatures(libs, deps, dummy); for (GadgetFeatureRegistry.Entry dep : deps) { libs.add(dep.getName()); } } // Inline any libs that weren't forced for (JsLibrary library : gadget.getJsLibraries()) { JsLibrary.Type type = library.getType(); if (library.getType().equals(JsLibrary.Type.URL)) { externJs.append(String.format(externFmt, library.getContent())); } else { if (!libs.contains(library.getFeature())) { // already pulled this file in from the shared contents. if (context.getDebug()) { inlineJs.append(library.getDebugContent()); } else { inlineJs.append(library.getContent()); } } } } for (JsLibrary library : gadget.getJsLibraries()) { libs.add(library.getFeature()); } appendJsConfig(libs, inlineJs); // message bundles for prefs object. MessageBundle bundle = gadget.getMessageBundle(); String msgs = new JSONObject(bundle.getMessages()).toString(); inlineJs.append("gadgets.Prefs.setMessages_(").append(msgs).append(");"); if (inlineJs.length() > 0) { markup.append("<script><!--\n").append(inlineJs) .append("\n-->\n</script>"); } if (externJs.length() > 0) { markup.append(externJs); } List<GadgetException> gadgetExceptions = new LinkedList<GadgetException>(); String content = view.getContent(); for (GadgetContentFilter filter : filters) { content = filter.filter(content); } markup.append(content) .append("<script>gadgets.util.runOnLoadHandlers();</script>") .append("</body></html>"); if (request.getParameter("v") != null) { // Versioned files get cached indefinitely HttpUtil.setCachingHeaders(response, 0); } else { // Unversioned files get cached for 5 minutes. // TODO: This should be configurable HttpUtil.setCachingHeaders(response, 60 * 5); } response.getWriter().print(markup.toString()); }
private void outputHtmlGadget(Gadget gadget, View view) throws IOException, GadgetException { response.setContentType("text/html; charset=UTF-8"); StringBuilder markup = new StringBuilder(); if (!view.getQuirks()) { markup.append(STRICT_MODE_DOCTYPE); } // TODO: Substitute gadgets.skins values in here. String boilerPlate = "<style type=\"text/css\">" + "body,td,div,span,p{font-family:arial,sans-serif;}" + "a {color:#0000cc;}a:visited {color:#551a8b;}" + "a:active {color:#ff0000;}" + "body{margin: 0px;padding: 0px;background-color:white;}" + "</style></head></body>"; markup.append(boilerPlate); StringBuilder externJs = new StringBuilder(); StringBuilder inlineJs = new StringBuilder(); String externFmt = "<script src=\"%s\"></script>"; String forcedLibs = request.getParameter("libs"); Set<String> libs = new HashSet<String>(); if (forcedLibs != null) { if (forcedLibs.trim().length() == 0) { libs.add("core"); } else { for (String lib : forcedLibs.split(":")) { libs.add(lib); } } } // Forced libs are always done first. if (libs.size() > 0) { String jsUrl = state.getJsUrl(libs, context); markup.append(String.format(externFmt, jsUrl)); // Transitive dependencies must be added. This will always include core // so is therefore always "safe". Set<GadgetFeatureRegistry.Entry> deps = new HashSet<GadgetFeatureRegistry.Entry>(); Set<String> dummy = new HashSet<String>(); GadgetFeatureRegistry registry = state.getGadgetServer().getConfig().getFeatureRegistry(); registry.getIncludedFeatures(libs, deps, dummy); for (GadgetFeatureRegistry.Entry dep : deps) { libs.add(dep.getName()); } } // Inline any libs that weren't forced for (JsLibrary library : gadget.getJsLibraries()) { JsLibrary.Type type = library.getType(); if (library.getType().equals(JsLibrary.Type.URL)) { externJs.append(String.format(externFmt, library.getContent())); } else { if (!libs.contains(library.getFeature())) { // already pulled this file in from the shared contents. if (context.getDebug()) { inlineJs.append(library.getDebugContent()); } else { inlineJs.append(library.getContent()); } } } } for (JsLibrary library : gadget.getJsLibraries()) { libs.add(library.getFeature()); } appendJsConfig(libs, inlineJs); // message bundles for prefs object. MessageBundle bundle = gadget.getMessageBundle(); String msgs = new JSONObject(bundle.getMessages()).toString(); inlineJs.append("gadgets.Prefs.setMessages_(").append(msgs).append(");"); if (inlineJs.length() > 0) { markup.append("<script><!--\n").append(inlineJs) .append("\n-->\n</script>"); } if (externJs.length() > 0) { markup.append(externJs); } List<GadgetException> gadgetExceptions = new LinkedList<GadgetException>(); String content = view.getContent(); for (GadgetContentFilter filter : filters) { content = filter.filter(content); } markup.append(content) .append("<script>gadgets.util.runOnLoadHandlers();</script>") .append("</body></html>"); if (request.getParameter("v") != null) { // Versioned files get cached indefinitely HttpUtil.setCachingHeaders(response, 0); } else { // Unversioned files get cached for 5 minutes. // TODO: This should be configurable HttpUtil.setCachingHeaders(response, 60 * 5); } response.getWriter().print(markup.toString()); }
diff --git a/src/main/java/com/moandjiezana/tent/essayist/db/migrations/Migration_1.java b/src/main/java/com/moandjiezana/tent/essayist/db/migrations/Migration_1.java index ec05011..fe74e58 100644 --- a/src/main/java/com/moandjiezana/tent/essayist/db/migrations/Migration_1.java +++ b/src/main/java/com/moandjiezana/tent/essayist/db/migrations/Migration_1.java @@ -1,33 +1,33 @@ package com.moandjiezana.tent.essayist.db.migrations; import static com.eroi.migrate.Define.autoincrement; import static com.eroi.migrate.Define.column; import static com.eroi.migrate.Define.notnull; import static com.eroi.migrate.Define.primarykey; import static com.eroi.migrate.Define.table; import static com.eroi.migrate.Define.DataTypes.LONGVARCHAR; import static com.eroi.migrate.Define.DataTypes.VARCHAR; import static com.eroi.migrate.Execute.createTable; import com.eroi.migrate.Define; import com.eroi.migrate.Execute; import com.eroi.migrate.Migration; public class Migration_1 implements Migration { @Override public void up() { createTable(table("AUTHORIZATIONS", column("ID", Define.DataTypes.BIGINT, primarykey(), autoincrement(), notnull()), - column("ENTITY", VARCHAR, notnull(), Define.length(65000)), + column("ENTITY", VARCHAR, notnull(), Define.length(1000)), column("PROFILE", LONGVARCHAR), column("REGISTRATION", LONGVARCHAR), column("ACCESSTOKEN", LONGVARCHAR))); } @Override public void down() { Execute.dropTable("authorizations"); } }
true
true
public void up() { createTable(table("AUTHORIZATIONS", column("ID", Define.DataTypes.BIGINT, primarykey(), autoincrement(), notnull()), column("ENTITY", VARCHAR, notnull(), Define.length(65000)), column("PROFILE", LONGVARCHAR), column("REGISTRATION", LONGVARCHAR), column("ACCESSTOKEN", LONGVARCHAR))); }
public void up() { createTable(table("AUTHORIZATIONS", column("ID", Define.DataTypes.BIGINT, primarykey(), autoincrement(), notnull()), column("ENTITY", VARCHAR, notnull(), Define.length(1000)), column("PROFILE", LONGVARCHAR), column("REGISTRATION", LONGVARCHAR), column("ACCESSTOKEN", LONGVARCHAR))); }
diff --git a/modules/srm/src/org/dcache/srm/request/sql/BringOnlineRequestStorage.java b/modules/srm/src/org/dcache/srm/request/sql/BringOnlineRequestStorage.java index f649b3dcb8..f3e0493982 100644 --- a/modules/srm/src/org/dcache/srm/request/sql/BringOnlineRequestStorage.java +++ b/modules/srm/src/org/dcache/srm/request/sql/BringOnlineRequestStorage.java @@ -1,275 +1,277 @@ // $Id$ // $Log: not supported by cvs2svn $ // Revision 1.3 2007/01/10 23:00:25 timur // implemented srmGetRequestTokens, store request description in database, fixed several srmv2 issues // // Revision 1.2 2007/01/06 00:23:55 timur // merging production branch changes to database layer to improve performance and reduce number of updates // /* * BringOnlineRequestStorage.java * * Created on June 22, 2004, 2:48 PM */ package org.dcache.srm.request.sql; import org.dcache.srm.request.ContainerRequest; import org.dcache.srm.request.FileRequest; import org.dcache.srm.request.BringOnlineRequest; import org.dcache.srm.util.Configuration; import java.sql.*; import org.dcache.srm.scheduler.Job; import org.dcache.srm.SRMUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author timur */ public class BringOnlineRequestStorage extends DatabaseContainerRequestStorage{ private final static Logger logger = LoggerFactory.getLogger(BringOnlineRequestStorage.class); public static final String TABLE_NAME ="bringonlinerequests"; private static final String UPDATE_PREFIX = "UPDATE " + TABLE_NAME + " SET "+ "NEXTJOBID=?, " + "CREATIONTIME=?, " + "LIFETIME=?, " + "STATE=?, " + "ERRORMESSAGE=?, " +//5 "SCHEDULERID=?, " + "SCHEDULERTIMESTAMP=?," + "NUMOFRETR=?," + "MAXNUMOFRETR=?," + "LASTSTATETRANSITIONTIME=? ";//10 private static final String INSERT_SQL = "INSERT INTO "+ TABLE_NAME+ "( " + "ID ,"+ "NEXTJOBID ,"+ "CREATIONTIME ,"+ "LIFETIME ,"+ "STATE ,"+ //5 "ERRORMESSAGE ,"+ "SCHEDULERID ,"+ "SCHEDULERTIMESTAMP ,"+ "NUMOFRETR ,"+ "MAXNUMOFRETR ,"+ //10 "LASTSTATETRANSITIONTIME,"+ //Database Request Storage "CREDENTIALID , " + "RETRYDELTATIME , "+ "SHOULDUPDATERETRYDELTATIME ,"+ "DESCRIPTION ,"+ //15 "CLIENTHOST ,"+ "STATUSCODE ,"+ "USERID ) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; @Override public PreparedStatement getCreateStatement(Connection connection, Job job) throws SQLException { BringOnlineRequest bor = (BringOnlineRequest)job; PreparedStatement stmt = getPreparedStatement(connection, INSERT_SQL, bor.getId(), bor.getNextJobId(), bor.getCreationTime(), bor.getLifetime(), bor.getState().getStateId(),//5 bor.getErrorMessage(), bor.getSchedulerId(), bor.getSchedulerTimeStamp(), bor.getNumberOfRetries(), bor.getMaxNumberOfRetries(),//10 bor.getLastStateTransitionTime(), //Database Request Storage bor.getCredentialId(), bor.getRetryDeltaTime(), bor.isShould_updateretryDeltaTime()?0:1, bor.getDescription(), bor.getClient_host(), bor.getStatusCodeString(), bor.getUser().getId()); return stmt; } private static final String UPDATE_REQUEST_SQL = UPDATE_PREFIX + ", CREDENTIALID=?," + " RETRYDELTATIME=?," + " SHOULDUPDATERETRYDELTATIME=?," + " DESCRIPTION=?," + " CLIENTHOST=?," + " STATUSCODE=?," + " USERID=?" + " WHERE ID=?"; @Override public PreparedStatement getUpdateStatement(Connection connection, Job job) throws SQLException { BringOnlineRequest bor = (BringOnlineRequest)job; PreparedStatement stmt = getPreparedStatement(connection, UPDATE_REQUEST_SQL, bor.getNextJobId(), bor.getCreationTime(), bor.getLifetime(), bor.getState().getStateId(), bor.getErrorMessage(),//5 bor.getSchedulerId(), bor.getSchedulerTimeStamp(), bor.getNumberOfRetries(), bor.getMaxNumberOfRetries(), bor.getLastStateTransitionTime(),//10 //Database Request Storage bor.getCredentialId(), bor.getRetryDeltaTime(), bor.isShould_updateretryDeltaTime()?0:1, bor.getDescription(), bor.getClient_host(), bor.getStatusCodeString(), bor.getUser().getId(), bor.getId()); return stmt; } /** Creates a new instance of BringOnlineRequestStorage */ public BringOnlineRequestStorage( Configuration.DatabaseParameters configuration ) throws SQLException { super(configuration); } private String getProtocolsTableName() { return getTableName()+"_protocols"; } public void dbInit1() throws SQLException { if(reanamed_old_table) { renameTable(getProtocolsTableName()); } String protocolsTableName = getProtocolsTableName().toLowerCase(); String createProtocolsTable = "CREATE TABLE "+ protocolsTableName+" ( "+ " PROTOCOL "+stringType+ ","+ " RequestID "+longType+ ", "+ //forein key " CONSTRAINT fk_"+getTableName()+"_PG FOREIGN KEY (RequestID) REFERENCES "+ getTableName() +" (ID) "+ " ON DELETE CASCADE"+ " )"; createTable(protocolsTableName, createProtocolsTable); } public void getCreateList(ContainerRequest r, StringBuffer sb) { } private static int ADDITIONAL_FIELDS = 0; protected ContainerRequest getContainerRequest( Connection _con, Long ID, Long NEXTJOBID, long CREATIONTIME, long LIFETIME, int STATE, String ERRORMESSAGE, SRMUser user, String SCHEDULERID, long SCHEDULER_TIMESTAMP, int NUMOFRETR, int MAXNUMOFRETR, long LASTSTATETRANSITIONTIME, Long CREDENTIALID, int RETRYDELTATIME, boolean SHOULDUPDATERETRYDELTATIME, String DESCRIPTION, String CLIENTHOST, String STATUSCODE, FileRequest[] fileRequests, java.sql.ResultSet set, int next_index)throws java.sql.SQLException { - String sqlStatementString = "SELECT PROTOCOL FROM " + getProtocolsTableName() + - " WHERE RequestID='"+ID+"'"; - Statement sqlStatement = _con.createStatement(); - logger.debug("executing statement: "+sqlStatementString); - ResultSet fileIdsSet = sqlStatement.executeQuery(sqlStatementString); + String sql = "SELECT PROTOCOL FROM ? WHERE RequestID=?"; + PreparedStatement statement = _con.prepareStatement(sql); + statement.setString(1, getProtocolsTableName()); + statement.setLong(2, ID); + logger.debug("executing: SELECT PROTOCOL FROM {} WHERE RequestID={} ", + getProtocolsTableName(),ID); + ResultSet fileIdsSet = statement.executeQuery(sql); java.util.Set utilset = new java.util.HashSet(); while(fileIdsSet.next()) { utilset.add(fileIdsSet.getString(1)); } String [] protocols = (String[]) utilset.toArray(new String[0]); - sqlStatement.close(); + statement.close(); Job.JobHistory[] jobHistoryArray = getJobHistory(ID,_con); return new BringOnlineRequest( ID, NEXTJOBID, CREATIONTIME, LIFETIME, STATE, ERRORMESSAGE, user, SCHEDULERID, SCHEDULER_TIMESTAMP, NUMOFRETR, MAXNUMOFRETR, LASTSTATETRANSITIONTIME, jobHistoryArray, CREDENTIALID, fileRequests, RETRYDELTATIME, SHOULDUPDATERETRYDELTATIME, DESCRIPTION, CLIENTHOST, STATUSCODE, protocols); } public String getRequestCreateTableFields() { return ""; } public String getTableName() { return TABLE_NAME; } private final String insertProtocols = "INSERT INTO "+getProtocolsTableName()+ " (PROTOCOL, RequestID) "+ " VALUES (?,?)"; @Override public PreparedStatement[] getAdditionalCreateStatements(Connection connection, Job job) throws SQLException { if(job == null || !(job instanceof BringOnlineRequest)) { throw new IllegalArgumentException("Request is not BringOnlineRequest" ); } BringOnlineRequest bor = (BringOnlineRequest)job; String[] protocols = bor.getProtocols(); if(protocols ==null) return null; PreparedStatement[] statements = new PreparedStatement[protocols.length]; for(int i=0; i<protocols.length ; ++i){ statements[i] = getPreparedStatement(connection, insertProtocols, protocols[i], bor.getId()); } return statements; } public String getFileRequestsTableName() { return BringOnlineFileRequestStorage.TABLE_NAME; } protected void __verify(int nextIndex, int columnIndex, String tableName, String columnName, int columnType) throws SQLException { } protected int getMoreCollumnsNum() { return ADDITIONAL_FIELDS; } }
false
true
protected ContainerRequest getContainerRequest( Connection _con, Long ID, Long NEXTJOBID, long CREATIONTIME, long LIFETIME, int STATE, String ERRORMESSAGE, SRMUser user, String SCHEDULERID, long SCHEDULER_TIMESTAMP, int NUMOFRETR, int MAXNUMOFRETR, long LASTSTATETRANSITIONTIME, Long CREDENTIALID, int RETRYDELTATIME, boolean SHOULDUPDATERETRYDELTATIME, String DESCRIPTION, String CLIENTHOST, String STATUSCODE, FileRequest[] fileRequests, java.sql.ResultSet set, int next_index)throws java.sql.SQLException { String sqlStatementString = "SELECT PROTOCOL FROM " + getProtocolsTableName() + " WHERE RequestID='"+ID+"'"; Statement sqlStatement = _con.createStatement(); logger.debug("executing statement: "+sqlStatementString); ResultSet fileIdsSet = sqlStatement.executeQuery(sqlStatementString); java.util.Set utilset = new java.util.HashSet(); while(fileIdsSet.next()) { utilset.add(fileIdsSet.getString(1)); } String [] protocols = (String[]) utilset.toArray(new String[0]); sqlStatement.close(); Job.JobHistory[] jobHistoryArray = getJobHistory(ID,_con); return new BringOnlineRequest( ID, NEXTJOBID, CREATIONTIME, LIFETIME, STATE, ERRORMESSAGE, user, SCHEDULERID, SCHEDULER_TIMESTAMP, NUMOFRETR, MAXNUMOFRETR, LASTSTATETRANSITIONTIME, jobHistoryArray, CREDENTIALID, fileRequests, RETRYDELTATIME, SHOULDUPDATERETRYDELTATIME, DESCRIPTION, CLIENTHOST, STATUSCODE, protocols); }
protected ContainerRequest getContainerRequest( Connection _con, Long ID, Long NEXTJOBID, long CREATIONTIME, long LIFETIME, int STATE, String ERRORMESSAGE, SRMUser user, String SCHEDULERID, long SCHEDULER_TIMESTAMP, int NUMOFRETR, int MAXNUMOFRETR, long LASTSTATETRANSITIONTIME, Long CREDENTIALID, int RETRYDELTATIME, boolean SHOULDUPDATERETRYDELTATIME, String DESCRIPTION, String CLIENTHOST, String STATUSCODE, FileRequest[] fileRequests, java.sql.ResultSet set, int next_index)throws java.sql.SQLException { String sql = "SELECT PROTOCOL FROM ? WHERE RequestID=?"; PreparedStatement statement = _con.prepareStatement(sql); statement.setString(1, getProtocolsTableName()); statement.setLong(2, ID); logger.debug("executing: SELECT PROTOCOL FROM {} WHERE RequestID={} ", getProtocolsTableName(),ID); ResultSet fileIdsSet = statement.executeQuery(sql); java.util.Set utilset = new java.util.HashSet(); while(fileIdsSet.next()) { utilset.add(fileIdsSet.getString(1)); } String [] protocols = (String[]) utilset.toArray(new String[0]); statement.close(); Job.JobHistory[] jobHistoryArray = getJobHistory(ID,_con); return new BringOnlineRequest( ID, NEXTJOBID, CREATIONTIME, LIFETIME, STATE, ERRORMESSAGE, user, SCHEDULERID, SCHEDULER_TIMESTAMP, NUMOFRETR, MAXNUMOFRETR, LASTSTATETRANSITIONTIME, jobHistoryArray, CREDENTIALID, fileRequests, RETRYDELTATIME, SHOULDUPDATERETRYDELTATIME, DESCRIPTION, CLIENTHOST, STATUSCODE, protocols); }
diff --git a/apps/ibis/benchmarks/latency/Latency.java b/apps/ibis/benchmarks/latency/Latency.java index cc93b64d..258cd8cd 100644 --- a/apps/ibis/benchmarks/latency/Latency.java +++ b/apps/ibis/benchmarks/latency/Latency.java @@ -1,513 +1,513 @@ import ibis.ipl.*; import java.util.Properties; import java.util.Random; import java.io.IOException; interface Config { static final boolean DEBUG = false; } class Computer extends Thread { boolean stop = false; long cycles = 0; long start = 0; final synchronized void printCycles(String temp) { long tmp = start; start = System.currentTimeMillis(); double result = ((double) cycles) / ((start-tmp)/1000.0); cycles = 0; System.err.println(temp + " cycles/s " + result); } final synchronized void reset() { start = System.currentTimeMillis(); cycles = 0; } final synchronized void setStop() { stop = true; } final synchronized boolean getStop() { return stop; } final void flip(double [] src, double [] dst, double mult) { for (int i=0;i<src.length;i++) { dst[i] = mult*src[src.length-i-1]; } } public void run() { double [] a = new double[4096]; double [] b = new double[4096]; for (int i=0;i<4096;i++) { a[i] = i*0.8; } start = System.currentTimeMillis(); while (!getStop()){ synchronized (this) { cycles++; } flip(a, b, 0.5); flip(a, b, 2.0); } } } class Sender implements Config { SendPort sport; ReceivePort rport; Sender(ReceivePort rport, SendPort sport) { this.rport = rport; this.sport = sport; } void send(int count, int repeat, Computer c) throws Exception { for (int r=0;r<repeat;r++) { long time = System.currentTimeMillis(); for(int i = 0; i< count; i++) { WriteMessage writeMessage = sport.newMessage(); if(DEBUG) { System.out.println("LAT: finish message"); } writeMessage.finish(); if(DEBUG) { System.out.println("LAT: message done"); } ReadMessage readMessage = rport.receive(); readMessage.finish(); } time = System.currentTimeMillis() - time; double speed = (time * 1000.0) / (double)count; System.err.println("Latency: " + count + " calls took " + (time/1000.0) + " seconds, time/call = " + speed + " micros"); if (c != null) c.printCycles("Sender"); } } } class ExplicitReceiver implements Config { SendPort sport; ReceivePort rport; Computer c; ExplicitReceiver(ReceivePort rport, SendPort sport, Computer c) { this.rport = rport; this.sport = sport; this.c = c; } void receive(int count, int repeat) throws IOException { for (int r=0;r<repeat;r++) { for(int i = 0; i< count; i++) { if(DEBUG) { System.out.println("LAT: in receive"); } ReadMessage readMessage = rport.receive(); if(DEBUG) { System.out.println("LAT: receive done"); } readMessage.finish(); if(DEBUG) { System.out.println("LAT: finish done"); } WriteMessage writeMessage = sport.newMessage(); writeMessage.finish(); } if (c != null) c.printCycles("Server"); } } } class UpcallReceiver implements Upcall { SendPort sport; Computer c; int count = 0; int max; int repeat; boolean earlyFinish; boolean delayedFinish; UpcallReceiver(SendPort sport, int max, boolean earlyFinish, boolean delayedFinish, int repeat, Computer c) { this.sport = sport; this.c = c; this.repeat = repeat; this.max = max; this.earlyFinish = earlyFinish; this.delayedFinish = delayedFinish; } public void upcall(ReadMessage readMessage) { // System.err.println("Got readMessage!!"); try { if(earlyFinish) { readMessage.finish(); } WriteMessage writeMessage = sport.newMessage(); writeMessage.finish(); count++; if (c != null && (count % max == 0)) c.printCycles("Server"); if (count == max*repeat) { synchronized (this) { notifyAll(); } } if(delayedFinish) { readMessage.finish(); } } catch (Exception e) { System.err.println("EEEEEK " + e); e.printStackTrace(); } } synchronized void finish() { while (count < max) { try { // System.err.println("Jikes"); wait(); } catch (Exception e) { } } System.err.println("Finished Receiver"); } } class UpcallSender implements Upcall, Config { SendPort sport; int count, max; long time; int repeat; Computer c; boolean earlyFinish; boolean delayedFinish; UpcallSender(SendPort sport, int count, boolean earlyFinish, boolean delayedFinish, int repeat, Computer c) { this.sport = sport; this.count = 0; this.max = count; this.repeat = repeat; this.c = c; this.earlyFinish = earlyFinish; this.delayedFinish = delayedFinish; } public void start() { try { System.err.println("Starting " + count); WriteMessage writeMessage = sport.newMessage(); writeMessage.finish(); } catch (Exception e) { System.err.println("EEEEEK " + e); e.printStackTrace(); } } public void upcall(ReadMessage readMessage) { try { if(earlyFinish) { readMessage.finish(); } // System.err.println("Sending " + count); if (count == 0) { time = System.currentTimeMillis(); } count++; if (count == max) { long temp = time; time = System.currentTimeMillis(); double speed = ((time-temp) * 1000.0) / (double)max; System.err.println("Latency: " + max + " calls took " + ((time-temp)/1000.0) + " seconds, time/call = " + speed + " micros"); count = 0; repeat--; if (repeat == 0) { synchronized (this) { notifyAll(); } return; } } if(DEBUG) { System.err.println("SEND pre new"); } WriteMessage writeMessage = sport.newMessage(); if(DEBUG) { System.err.println("SEND pre fin"); } writeMessage.finish(); if(DEBUG) { System.err.println("SEND post fin"); } if(delayedFinish) { readMessage.finish(); } } catch (Exception e) { System.err.println("EEEEEK " + e); e.printStackTrace(); } } synchronized void finish() { while (count < 2*max) { try { // System.err.println("EEK"); wait(); } catch (Exception e) { } } System.err.println("Finished Sender " + count + " " + max); } } class Latency implements Config { static Ibis ibis; static Registry registry; public static void connect(SendPort s, ReceivePortIdentifier ident) { boolean success = false; do { try { s.connect(ident); success = true; } catch (Exception e) { try { Thread.sleep(500); } catch (Exception e2) { // ignore } } } while (!success); } public static ReceivePortIdentifier lookup(String name) throws Exception { ReceivePortIdentifier temp = null; do { temp = registry.lookup(name); if (temp == null) { try { Thread.sleep(500); } catch (Exception e) { // ignore } } } while (temp == null); return temp; } static void usage() { System.out.println("Usage: Latency [-u] [-uu] [-ibis] [count]"); System.exit(0); } public static void main(String [] args) { boolean upcalls = false; boolean upcallsend = false; boolean ibisSer = false; int count = -1; int repeat = 10; int rank = 0, remoteRank = 1; Random r = new Random(); boolean compRec = false; boolean compSnd = false; Computer c = null; boolean earlyFinish = false; boolean delayedFinish = false; boolean noneSer = false; /* Parse commandline parameters. */ for(int i=0; i<args.length; i++) { if(args[i].equals("-u")) { upcalls = true; } else if(args[i].equals("-uu")) { upcalls = true; upcallsend = true; } else if(args[i].equals("-repeat")) { i++; repeat = Integer.parseInt(args[i]); } else if(args[i].equals("-ibis")) { ibisSer = true; } else if(args[i].equals("-none")) { noneSer = true; } else if(args[i].equals("-comp-rec")) { compRec = true; } else if(args[i].equals("-comp-snd")) { compSnd = true; } else if(args[i].equals("-early-finish")) { earlyFinish = true; } else if(args[i].equals("-delayed-finish")) { delayedFinish = true; } else { if(count == -1) { count = Integer.parseInt(args[i]); } else { usage(); } } } if(count == -1) { count = 10000; } try { StaticProperties s = new StaticProperties(); if (ibisSer) { s.add("Serialization", "ibis"); } else if (noneSer) { - s.add("Serialization", "none"); + s.add("Serialization", "byte"); } else s.add("Serialization", "sun"); s.add("Communication", "OneToOne, Reliable, AutoUpcalls, ExplicitReceipt"); s.add("worldmodel", "open"); ibis = Ibis.createIbis(s, null); registry = ibis.registry(); PortType t = ibis.createPortType("test type", s); SendPort sport = t.createSendPort("send port"); ReceivePort rport; Latency lat = null; if(DEBUG) { System.out.println("LAT: pre elect"); } IbisIdentifier master = (IbisIdentifier) registry.elect("latency", ibis.identifier()); if(DEBUG) { System.out.println("LAT: post elect"); } if(master.equals(ibis.identifier())) { if(DEBUG) { System.out.println("LAT: I am master"); } rank = 0; remoteRank = 1; } else { if(DEBUG) { System.out.println("LAT: I am slave"); } rank = 1; remoteRank = 0; } if (rank == 0) { if(compSnd) { c = new Computer(); c.setDaemon(true); c.start(); } if (!upcallsend) { rport = t.createReceivePort("test port 0"); rport.enableConnections(); ReceivePortIdentifier ident = lookup("test port 1"); connect(sport, ident); Sender sender = new Sender(rport, sport); if(DEBUG) { System.out.println("LAT: starting send test"); } sender.send(count, repeat, c); } else { UpcallSender sender = new UpcallSender(sport, count, earlyFinish, delayedFinish, repeat, c); rport = t.createReceivePort("test port 0", sender); rport.enableConnections(); ReceivePortIdentifier ident = lookup("test port 1"); connect(sport, ident); rport.enableUpcalls(); sender.start(); sender.finish(); } } else { ReceivePortIdentifier ident = lookup("test port 0"); connect(sport, ident); if(compRec) { c = new Computer(); c.setDaemon(true); c.start(); } if (upcalls) { UpcallReceiver receiver = new UpcallReceiver(sport, count, earlyFinish, delayedFinish, repeat, c); rport = t.createReceivePort("test port 1", receiver); rport.enableConnections(); rport.enableUpcalls(); receiver.finish(); } else { rport = t.createReceivePort("test port 1"); rport.enableConnections(); ExplicitReceiver receiver = new ExplicitReceiver(rport, sport, c); if(DEBUG) { System.out.println("LAT: starting test receiver"); } receiver.receive(count, repeat); } } /* free the send ports first */ sport.close(); rport.close(); ibis.end(); } catch (Exception e) { System.err.println("Got exception " + e); System.err.println("StackTrace:"); e.printStackTrace(); } } }
true
true
public static void main(String [] args) { boolean upcalls = false; boolean upcallsend = false; boolean ibisSer = false; int count = -1; int repeat = 10; int rank = 0, remoteRank = 1; Random r = new Random(); boolean compRec = false; boolean compSnd = false; Computer c = null; boolean earlyFinish = false; boolean delayedFinish = false; boolean noneSer = false; /* Parse commandline parameters. */ for(int i=0; i<args.length; i++) { if(args[i].equals("-u")) { upcalls = true; } else if(args[i].equals("-uu")) { upcalls = true; upcallsend = true; } else if(args[i].equals("-repeat")) { i++; repeat = Integer.parseInt(args[i]); } else if(args[i].equals("-ibis")) { ibisSer = true; } else if(args[i].equals("-none")) { noneSer = true; } else if(args[i].equals("-comp-rec")) { compRec = true; } else if(args[i].equals("-comp-snd")) { compSnd = true; } else if(args[i].equals("-early-finish")) { earlyFinish = true; } else if(args[i].equals("-delayed-finish")) { delayedFinish = true; } else { if(count == -1) { count = Integer.parseInt(args[i]); } else { usage(); } } } if(count == -1) { count = 10000; } try { StaticProperties s = new StaticProperties(); if (ibisSer) { s.add("Serialization", "ibis"); } else if (noneSer) { s.add("Serialization", "none"); } else s.add("Serialization", "sun"); s.add("Communication", "OneToOne, Reliable, AutoUpcalls, ExplicitReceipt"); s.add("worldmodel", "open"); ibis = Ibis.createIbis(s, null); registry = ibis.registry(); PortType t = ibis.createPortType("test type", s); SendPort sport = t.createSendPort("send port"); ReceivePort rport; Latency lat = null; if(DEBUG) { System.out.println("LAT: pre elect"); } IbisIdentifier master = (IbisIdentifier) registry.elect("latency", ibis.identifier()); if(DEBUG) { System.out.println("LAT: post elect"); } if(master.equals(ibis.identifier())) { if(DEBUG) { System.out.println("LAT: I am master"); } rank = 0; remoteRank = 1; } else { if(DEBUG) { System.out.println("LAT: I am slave"); } rank = 1; remoteRank = 0; } if (rank == 0) { if(compSnd) { c = new Computer(); c.setDaemon(true); c.start(); } if (!upcallsend) { rport = t.createReceivePort("test port 0"); rport.enableConnections(); ReceivePortIdentifier ident = lookup("test port 1"); connect(sport, ident); Sender sender = new Sender(rport, sport); if(DEBUG) { System.out.println("LAT: starting send test"); } sender.send(count, repeat, c); } else { UpcallSender sender = new UpcallSender(sport, count, earlyFinish, delayedFinish, repeat, c); rport = t.createReceivePort("test port 0", sender); rport.enableConnections(); ReceivePortIdentifier ident = lookup("test port 1"); connect(sport, ident); rport.enableUpcalls(); sender.start(); sender.finish(); } } else { ReceivePortIdentifier ident = lookup("test port 0"); connect(sport, ident); if(compRec) { c = new Computer(); c.setDaemon(true); c.start(); } if (upcalls) { UpcallReceiver receiver = new UpcallReceiver(sport, count, earlyFinish, delayedFinish, repeat, c); rport = t.createReceivePort("test port 1", receiver); rport.enableConnections(); rport.enableUpcalls(); receiver.finish(); } else { rport = t.createReceivePort("test port 1"); rport.enableConnections(); ExplicitReceiver receiver = new ExplicitReceiver(rport, sport, c); if(DEBUG) { System.out.println("LAT: starting test receiver"); } receiver.receive(count, repeat); } } /* free the send ports first */ sport.close(); rport.close(); ibis.end(); } catch (Exception e) { System.err.println("Got exception " + e); System.err.println("StackTrace:"); e.printStackTrace(); } }
public static void main(String [] args) { boolean upcalls = false; boolean upcallsend = false; boolean ibisSer = false; int count = -1; int repeat = 10; int rank = 0, remoteRank = 1; Random r = new Random(); boolean compRec = false; boolean compSnd = false; Computer c = null; boolean earlyFinish = false; boolean delayedFinish = false; boolean noneSer = false; /* Parse commandline parameters. */ for(int i=0; i<args.length; i++) { if(args[i].equals("-u")) { upcalls = true; } else if(args[i].equals("-uu")) { upcalls = true; upcallsend = true; } else if(args[i].equals("-repeat")) { i++; repeat = Integer.parseInt(args[i]); } else if(args[i].equals("-ibis")) { ibisSer = true; } else if(args[i].equals("-none")) { noneSer = true; } else if(args[i].equals("-comp-rec")) { compRec = true; } else if(args[i].equals("-comp-snd")) { compSnd = true; } else if(args[i].equals("-early-finish")) { earlyFinish = true; } else if(args[i].equals("-delayed-finish")) { delayedFinish = true; } else { if(count == -1) { count = Integer.parseInt(args[i]); } else { usage(); } } } if(count == -1) { count = 10000; } try { StaticProperties s = new StaticProperties(); if (ibisSer) { s.add("Serialization", "ibis"); } else if (noneSer) { s.add("Serialization", "byte"); } else s.add("Serialization", "sun"); s.add("Communication", "OneToOne, Reliable, AutoUpcalls, ExplicitReceipt"); s.add("worldmodel", "open"); ibis = Ibis.createIbis(s, null); registry = ibis.registry(); PortType t = ibis.createPortType("test type", s); SendPort sport = t.createSendPort("send port"); ReceivePort rport; Latency lat = null; if(DEBUG) { System.out.println("LAT: pre elect"); } IbisIdentifier master = (IbisIdentifier) registry.elect("latency", ibis.identifier()); if(DEBUG) { System.out.println("LAT: post elect"); } if(master.equals(ibis.identifier())) { if(DEBUG) { System.out.println("LAT: I am master"); } rank = 0; remoteRank = 1; } else { if(DEBUG) { System.out.println("LAT: I am slave"); } rank = 1; remoteRank = 0; } if (rank == 0) { if(compSnd) { c = new Computer(); c.setDaemon(true); c.start(); } if (!upcallsend) { rport = t.createReceivePort("test port 0"); rport.enableConnections(); ReceivePortIdentifier ident = lookup("test port 1"); connect(sport, ident); Sender sender = new Sender(rport, sport); if(DEBUG) { System.out.println("LAT: starting send test"); } sender.send(count, repeat, c); } else { UpcallSender sender = new UpcallSender(sport, count, earlyFinish, delayedFinish, repeat, c); rport = t.createReceivePort("test port 0", sender); rport.enableConnections(); ReceivePortIdentifier ident = lookup("test port 1"); connect(sport, ident); rport.enableUpcalls(); sender.start(); sender.finish(); } } else { ReceivePortIdentifier ident = lookup("test port 0"); connect(sport, ident); if(compRec) { c = new Computer(); c.setDaemon(true); c.start(); } if (upcalls) { UpcallReceiver receiver = new UpcallReceiver(sport, count, earlyFinish, delayedFinish, repeat, c); rport = t.createReceivePort("test port 1", receiver); rport.enableConnections(); rport.enableUpcalls(); receiver.finish(); } else { rport = t.createReceivePort("test port 1"); rport.enableConnections(); ExplicitReceiver receiver = new ExplicitReceiver(rport, sport, c); if(DEBUG) { System.out.println("LAT: starting test receiver"); } receiver.receive(count, repeat); } } /* free the send ports first */ sport.close(); rport.close(); ibis.end(); } catch (Exception e) { System.err.println("Got exception " + e); System.err.println("StackTrace:"); e.printStackTrace(); } }
diff --git a/src/no/ntnu/ai/ui/UserInterface.java b/src/no/ntnu/ai/ui/UserInterface.java index 6c7984b..66044ce 100644 --- a/src/no/ntnu/ai/ui/UserInterface.java +++ b/src/no/ntnu/ai/ui/UserInterface.java @@ -1,181 +1,183 @@ package no.ntnu.ai.ui; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import no.ntnu.ai.boost.AdaBoost; import no.ntnu.ai.data.DataElement; import no.ntnu.ai.file.parser.FileParser; import no.ntnu.ai.file.parser.Parser; import no.ntnu.ai.filter.Filter; import no.ntnu.ai.hypothesis.Generator; import no.ntnu.ai.hypothesis.Hypothesis; public class UserInterface { private final static String FILE_STRING = "file"; private final static String CLASSIFIER_STRING = "classifier"; private final static String GLOBAL_OPTIONS = "global"; private final static String FILTER_STRING = "filter"; public static List<Generator<?,?>> parseClassifier(List<String> options){ try { int numberOf = Integer.parseInt(options.get(2)); List<Generator<?, ?>> result = new ArrayList<Generator<?,?>>(numberOf); for(int i = 0; i < numberOf; i++){ Generator<?,?> g = (Generator<?, ?>) Class.forName(options.get(1)).newInstance(); g.initialize(options.subList(3, options.size())); result.add(g); } return result; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { System.err.println("Could not find the specified class: " + options.get(1)); System.exit(-1); } return null; } public static Filter<Object, Object> parseFilter(List<String> options){ try { @SuppressWarnings("unchecked") Filter<Object, Object> f = (Filter<Object, Object>) Class.forName(options.get(1)).newInstance(); f.initialize(options.subList(2, options.size())); return f; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { System.err.println("Could not find the specified class: " + options.get(1)); System.exit(-1); } return null; } public static List<List<String>> parseCommandLine(String[] args){ List<List<String>> result = new ArrayList<List<String>>(); int i = -1; for(int j = 0; j < args.length; j++){ String s = args[j]; if(s.equalsIgnoreCase("--" + CLASSIFIER_STRING) || s.equalsIgnoreCase("-c")){ result.add(new ArrayList<String>()); i++; result.get(i).add(CLASSIFIER_STRING); }else if(s.equalsIgnoreCase("--" + FILE_STRING) || s.equalsIgnoreCase("-f")){ result.add(new ArrayList<String>()); i++; result.get(i).add(FILE_STRING); }else if(s.equalsIgnoreCase("--" + GLOBAL_OPTIONS) || s.equalsIgnoreCase("-g")){ result.add(new ArrayList<String>()); i++; result.get(i).add(GLOBAL_OPTIONS); }else if(s.equalsIgnoreCase("--" + FILTER_STRING) || s.equalsIgnoreCase("-fi")){ result.add(new ArrayList<String>()); i++; result.get(i).add(FILTER_STRING); }else{ result.get(i).add(s); } } return result; } /** * @param args */ @SuppressWarnings({ "unchecked" }) public static void main(String[] args) { if(args.length > 1 && !args[0].equalsIgnoreCase("--help")){ List<List<String>> options = parseCommandLine(args); List<List<Generator<?,?>>> classifierGenerators = new ArrayList<List<Generator<?,?>>>(); Parser<String, String> dataParser = null; Filter<Object, Object> dataFilter = null; double percentage = 0.25; int randomValue = 42; for(List<String> option : options){ if(option.get(0).equalsIgnoreCase(CLASSIFIER_STRING)){ classifierGenerators.add(parseClassifier(option)); }else if(option.get(0).equalsIgnoreCase(FILE_STRING)){ dataParser = new FileParser(); dataParser.initialize(option.get(1)); }else if(option.get(0).equalsIgnoreCase(GLOBAL_OPTIONS)){ percentage = Double.parseDouble(option.get(1)); randomValue = Integer.parseInt(option.get(2)); }else if(option.get(0).equalsIgnoreCase(FILTER_STRING)){ dataFilter = parseFilter(option); }else{ System.err.println("Did not recoqnize the option: '" + option.get(0) + "'"); } } //Shuffle data List<?> data = dataFilter.convert(dataParser.getData()); Collections.shuffle(data, new Random(randomValue)); List<DataElement<?, ?>> training = (List<DataElement<?, ?>>) data.subList(0, (int)(data.size() - data.size()*percentage)); List<DataElement<?, ?>> test = (List<DataElement<?, ?>>) data.subList((int)(data.size() - data.size()*percentage), data.size()); //Use adaboost to obtain result: List<Hypothesis> hypotheses = new ArrayList(); for(List<Generator<?, ?>> l : classifierGenerators){ AdaBoost<?, ?> boost = new AdaBoost(l, training); List<?> hypos = boost.runBooster(); hypotheses.addAll((Collection<? extends Hypothesis>) hypos); System.out.println(hypos.get(0).getClass().getName() + "(" + hypos.size() + "):"); System.out.println("\tTraining avg error: " + boost.getAvg() + ", std dev of error: " + boost.getStdDev()); } System.out.println(""); int error = 0; for(DataElement dat : test){ Map<Object, Double> classStrength = new HashMap<Object, Double>(); for(Object o : hypotheses){ Hypothesis h = (Hypothesis) o; Object classi = h.classify(dat); if(!classStrength.containsKey(classi)){ classStrength.put(classi, 0.0); } classStrength.put(classi, classStrength.get(classi) + h.getWeight()); } Object max = null; double maxVal = -1; for(Object o : classStrength.keySet()){ if(classStrength.get(o) > maxVal){ max = o; maxVal = classStrength.get(o); } } if(!dat.getClassification().equals(max)){ error ++; } } - System.out.println("Test error: " + error + " of " + test.size()); + int posError = (int) (((double)error / test.size()) * 100); + System.out.println("Test error: " + error + " of " + test.size() + + " (" + posError + "%)"); }else{ String classy = "--" + CLASSIFIER_STRING + " classname " + "numberOfClassifiers [options]"; System.out.println("Usage:"); System.out.println("java " + UserInterface.class.getName() + " [--" + GLOBAL_OPTIONS + " percentageOfTestData randomKey]" + " --" + FILE_STRING + " name" + " --" + FILTER_STRING + " filter " + classy + " [" + classy + "]"); } } }
true
true
public static void main(String[] args) { if(args.length > 1 && !args[0].equalsIgnoreCase("--help")){ List<List<String>> options = parseCommandLine(args); List<List<Generator<?,?>>> classifierGenerators = new ArrayList<List<Generator<?,?>>>(); Parser<String, String> dataParser = null; Filter<Object, Object> dataFilter = null; double percentage = 0.25; int randomValue = 42; for(List<String> option : options){ if(option.get(0).equalsIgnoreCase(CLASSIFIER_STRING)){ classifierGenerators.add(parseClassifier(option)); }else if(option.get(0).equalsIgnoreCase(FILE_STRING)){ dataParser = new FileParser(); dataParser.initialize(option.get(1)); }else if(option.get(0).equalsIgnoreCase(GLOBAL_OPTIONS)){ percentage = Double.parseDouble(option.get(1)); randomValue = Integer.parseInt(option.get(2)); }else if(option.get(0).equalsIgnoreCase(FILTER_STRING)){ dataFilter = parseFilter(option); }else{ System.err.println("Did not recoqnize the option: '" + option.get(0) + "'"); } } //Shuffle data List<?> data = dataFilter.convert(dataParser.getData()); Collections.shuffle(data, new Random(randomValue)); List<DataElement<?, ?>> training = (List<DataElement<?, ?>>) data.subList(0, (int)(data.size() - data.size()*percentage)); List<DataElement<?, ?>> test = (List<DataElement<?, ?>>) data.subList((int)(data.size() - data.size()*percentage), data.size()); //Use adaboost to obtain result: List<Hypothesis> hypotheses = new ArrayList(); for(List<Generator<?, ?>> l : classifierGenerators){ AdaBoost<?, ?> boost = new AdaBoost(l, training); List<?> hypos = boost.runBooster(); hypotheses.addAll((Collection<? extends Hypothesis>) hypos); System.out.println(hypos.get(0).getClass().getName() + "(" + hypos.size() + "):"); System.out.println("\tTraining avg error: " + boost.getAvg() + ", std dev of error: " + boost.getStdDev()); } System.out.println(""); int error = 0; for(DataElement dat : test){ Map<Object, Double> classStrength = new HashMap<Object, Double>(); for(Object o : hypotheses){ Hypothesis h = (Hypothesis) o; Object classi = h.classify(dat); if(!classStrength.containsKey(classi)){ classStrength.put(classi, 0.0); } classStrength.put(classi, classStrength.get(classi) + h.getWeight()); } Object max = null; double maxVal = -1; for(Object o : classStrength.keySet()){ if(classStrength.get(o) > maxVal){ max = o; maxVal = classStrength.get(o); } } if(!dat.getClassification().equals(max)){ error ++; } } System.out.println("Test error: " + error + " of " + test.size()); }else{ String classy = "--" + CLASSIFIER_STRING + " classname " + "numberOfClassifiers [options]"; System.out.println("Usage:"); System.out.println("java " + UserInterface.class.getName() + " [--" + GLOBAL_OPTIONS + " percentageOfTestData randomKey]" + " --" + FILE_STRING + " name" + " --" + FILTER_STRING + " filter " + classy + " [" + classy + "]"); } }
public static void main(String[] args) { if(args.length > 1 && !args[0].equalsIgnoreCase("--help")){ List<List<String>> options = parseCommandLine(args); List<List<Generator<?,?>>> classifierGenerators = new ArrayList<List<Generator<?,?>>>(); Parser<String, String> dataParser = null; Filter<Object, Object> dataFilter = null; double percentage = 0.25; int randomValue = 42; for(List<String> option : options){ if(option.get(0).equalsIgnoreCase(CLASSIFIER_STRING)){ classifierGenerators.add(parseClassifier(option)); }else if(option.get(0).equalsIgnoreCase(FILE_STRING)){ dataParser = new FileParser(); dataParser.initialize(option.get(1)); }else if(option.get(0).equalsIgnoreCase(GLOBAL_OPTIONS)){ percentage = Double.parseDouble(option.get(1)); randomValue = Integer.parseInt(option.get(2)); }else if(option.get(0).equalsIgnoreCase(FILTER_STRING)){ dataFilter = parseFilter(option); }else{ System.err.println("Did not recoqnize the option: '" + option.get(0) + "'"); } } //Shuffle data List<?> data = dataFilter.convert(dataParser.getData()); Collections.shuffle(data, new Random(randomValue)); List<DataElement<?, ?>> training = (List<DataElement<?, ?>>) data.subList(0, (int)(data.size() - data.size()*percentage)); List<DataElement<?, ?>> test = (List<DataElement<?, ?>>) data.subList((int)(data.size() - data.size()*percentage), data.size()); //Use adaboost to obtain result: List<Hypothesis> hypotheses = new ArrayList(); for(List<Generator<?, ?>> l : classifierGenerators){ AdaBoost<?, ?> boost = new AdaBoost(l, training); List<?> hypos = boost.runBooster(); hypotheses.addAll((Collection<? extends Hypothesis>) hypos); System.out.println(hypos.get(0).getClass().getName() + "(" + hypos.size() + "):"); System.out.println("\tTraining avg error: " + boost.getAvg() + ", std dev of error: " + boost.getStdDev()); } System.out.println(""); int error = 0; for(DataElement dat : test){ Map<Object, Double> classStrength = new HashMap<Object, Double>(); for(Object o : hypotheses){ Hypothesis h = (Hypothesis) o; Object classi = h.classify(dat); if(!classStrength.containsKey(classi)){ classStrength.put(classi, 0.0); } classStrength.put(classi, classStrength.get(classi) + h.getWeight()); } Object max = null; double maxVal = -1; for(Object o : classStrength.keySet()){ if(classStrength.get(o) > maxVal){ max = o; maxVal = classStrength.get(o); } } if(!dat.getClassification().equals(max)){ error ++; } } int posError = (int) (((double)error / test.size()) * 100); System.out.println("Test error: " + error + " of " + test.size() + " (" + posError + "%)"); }else{ String classy = "--" + CLASSIFIER_STRING + " classname " + "numberOfClassifiers [options]"; System.out.println("Usage:"); System.out.println("java " + UserInterface.class.getName() + " [--" + GLOBAL_OPTIONS + " percentageOfTestData randomKey]" + " --" + FILE_STRING + " name" + " --" + FILTER_STRING + " filter " + classy + " [" + classy + "]"); } }
diff --git a/src/savant/swing/component/TrackChooser.java b/src/savant/swing/component/TrackChooser.java index 60727bec..0c3e6195 100644 --- a/src/savant/swing/component/TrackChooser.java +++ b/src/savant/swing/component/TrackChooser.java @@ -1,658 +1,656 @@ /* * Copyright 2010-2011 University of Toronto * * 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 savant.swing.component; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import savant.controller.FrameController; import savant.file.DataFormat; import savant.settings.PersistentSettings; import savant.util.MiscUtils; import savant.view.swing.Frame; /** * * @author AndrewBrook */ public class TrackChooser extends JDialog { private boolean multiple; private JPanel filler1; private JPanel filler2; private JPanel filler3; private JList leftList; private JList rightList; private JScrollPane leftScroll; private JScrollPane rightScroll; private JButton moveRight; private JButton moveLeft; private JButton allRight; private JButton allLeft; private JButton okButton; private JButton cancelButton; private String[] retVal; private JLabel leftLabel; private JLabel rightLabel; private JPanel filterPanel; private JLabel filterLabel; private JComboBox filterCombo; private String[] filteredTracks = null; private JCheckBox autoSelectAllCheck; private boolean selectBase; private JTextField selectBaseField; private int baseSelected = -1; public TrackChooser(JFrame parent, boolean multiple, String title){ this(parent, multiple, title, false, -1); } public TrackChooser(JFrame parent, boolean multiple, String title, boolean selectBase){ this(parent, multiple, title, selectBase, -1); } public TrackChooser(JFrame parent, boolean multiple, String title, boolean selectBase, int defaultBase){ super(parent, true); this.multiple = multiple; this.selectBase = selectBase; this.setTitle(title); init(); initLists(); if(selectBase && defaultBase != -1){ selectBaseField.setText(MiscUtils.numToString(defaultBase)); } if(this.getAutoSelect()) selectAll(); this.setLocationRelativeTo(null); } public String[] getSelectedTracks(){ return retVal; } public int getBaseSelected(){ return baseSelected; } private void filter(){ if(this.filteredTracks != null){ for(int i = 0; i < filteredTracks.length; i++){ ((TrackListModel)leftList.getModel()).add(filteredTracks[i]); } filteredTracks = null; } leftList.updateUI(); leftList.clearSelection(); DataFormat ff = MiscUtils.dataFormatFromString((String)filterCombo.getSelectedItem()); //if(filterCombo.getSelectedItem().equals("All")){ if(ff == null){ leftList.updateUI(); leftList.clearSelection(); return; } String[] leftTracks = ((TrackListModel)leftList.getModel()).getAll(); List<Frame> frames = FrameController.getInstance().getFrames(); String[] removed = new String[leftTracks.length]; int[] remove = new int[leftTracks.length]; int count = 0; for(int i = 0; i < leftTracks.length; i++){ String current = leftTracks[i]; for(int j = 0; j <frames.size(); j++){ if(frames.get(j).getName().equals(current)){ if(!frames.get(j).getTracks()[0].getDataSource().getDataFormat().equals(ff)){ remove[count] = i; removed[count] = current; count++; } break; } } } int[] removeFinal = new int[count]; String[] removedFinal = new String[count]; for(int i = 0; i < count; i++){ removeFinal[i] = remove[i]; removedFinal[i] = removed[i]; } this.filteredTracks = removedFinal; ((TrackListModel)leftList.getModel()).removeIndices(removeFinal); leftList.updateUI(); leftList.clearSelection(); } private void initLayout(){ this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //FILLER filler1 = new JPanel(); filler1.setPreferredSize(new Dimension(10,10)); c.weightx = 1.0; c.weighty = 3.0; c.gridx = 0; c.gridy = 0; this.add(filler1, c); //LEFT LABEL leftLabel = new JLabel("All Tracks"); leftLabel.setFont(new Font(null, Font.BOLD, 12)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.anchor = GridBagConstraints.CENTER; this.add(leftLabel, c); //RIGHT LABEL rightLabel = new JLabel("Selected Tracks"); rightLabel.setFont(new Font(null, Font.BOLD, 12)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 1; c.gridwidth = 2; c.anchor = GridBagConstraints.CENTER; this.add(rightLabel, c); //LEFT LIST leftList = new JList(); leftScroll = new JScrollPane(); leftScroll.setViewportView(leftList); leftScroll.setMinimumSize(new Dimension(450,300)); leftScroll.setPreferredSize(new Dimension(450,300)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 2; c.gridwidth = 1; c.gridheight = 4; this.add(leftScroll, c); //FILLER filler3 = new JPanel(); filler3.setSize(60, 10); filler3.setPreferredSize(new Dimension(60,10)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 0; c.gridheight = 1; this.add(filler3, c); //MOVE RIGHT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 2; c.gridheight = 1; this.add(moveRight, c); //MOVE LEFT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 3; c.gridheight = 1; this.add(moveLeft, c); //ALL RIGHT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 4; c.gridheight = 1; this.add(allRight, c); //ALL LEFT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 5; c.gridheight = 1; this.add(allLeft, c); //RIGHT LIST rightList = new JList(); rightScroll = new JScrollPane(); rightScroll.setViewportView(rightList); rightScroll.setMinimumSize(new Dimension(450,300)); rightScroll.setPreferredSize(new Dimension(450,300)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 2; c.gridheight = 4; c.gridwidth = 2; this.add(rightScroll, c); //FILLER filler2 = new JPanel(); filler2.setSize(10, 40); filler2.setPreferredSize(new Dimension(10,40)); c.weightx = 0; c.weighty = 0; c.gridx = 5; c.gridy = 7; c.gridheight = 1; c.gridwidth = 1; this.add(filler2, c); //FILTER c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 6; c.gridheight = 1; c.gridwidth = 1; this.add(filterPanel, c); //AUTO SELECT ALL c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 6; c.gridheight = 1; c.gridwidth = 2; this.add(autoSelectAllCheck, c); //SEPARATOR JPanel sepPanel1 = new JPanel(); sepPanel1.setMinimumSize(new Dimension(5, 10)); - sepPanel1.setBackground(Color.red); sepPanel1.setLayout(new BorderLayout()); sepPanel1.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.CENTER); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 7; c.gridheight = 1; c.gridwidth = 5; this.add(sepPanel1, c); int y = 8; if(selectBase){ //SELECT BASE PANEL JPanel selectBasePanel = new JPanel(); selectBasePanel.setMinimumSize(new Dimension(40, 10)); selectBasePanel.setLayout(new BorderLayout()); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = y; c.gridheight = 1; c.gridwidth = 2; this.add(selectBasePanel, c); //SELECT BASE LABEL JLabel selectBaseLabel = new JLabel("(Optional) Select Base: "); selectBasePanel.add(selectBaseLabel, BorderLayout.WEST); //SELECT BASE FIELD selectBaseField = new JTextField(); selectBasePanel.add(selectBaseField, BorderLayout.CENTER); //FILLER JPanel selectBaseFiller = new JPanel(); selectBaseFiller.setSize(new Dimension(10,10)); selectBaseFiller.setPreferredSize(new Dimension(10,10)); selectBasePanel.add(selectBaseFiller, BorderLayout.SOUTH); y++; //SEPARATOR JPanel sepPanel2 = new JPanel(); sepPanel2.setMinimumSize(new Dimension(10, 10)); - sepPanel2.setBackground(Color.red); sepPanel2.setLayout(new BorderLayout()); sepPanel2.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.CENTER); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = y; c.gridheight = 1; c.gridwidth = 5; this.add(sepPanel2, c); y++; //FILLER JPanel filler5 = new JPanel(); filler5.setSize(10, 10); filler5.setPreferredSize(new Dimension(10,10)); c.weightx = 0; c.weighty = 0; c.gridx = 0; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(filler5, c); y++; } //OK c.fill = GridBagConstraints.NONE; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(okButton, c); //CANCEL c.weightx = 1.0; c.weighty = 0.5; c.gridx = 4; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(cancelButton, c); y++; //FILLER JPanel filler4 = new JPanel(); filler4.setSize(10, 10); filler4.setPreferredSize(new Dimension(10,10)); c.weightx = 0; c.weighty = 0; c.gridx = 0; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(filler4, c); pack(); } private void createFilter(){ filterPanel = new JPanel(); filterPanel.setLayout(new BorderLayout()); filterLabel = new JLabel("Filter By: "); filterLabel.setPreferredSize(new Dimension(50,20)); filterPanel.add(filterLabel, BorderLayout.WEST); filterCombo = new JComboBox(); filterCombo.setPreferredSize(new Dimension(140,20)); filterPanel.add(filterCombo, BorderLayout.EAST); } private void createOkButton(){ okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { retVal = ((TrackListModel)rightList.getModel()).getAll(); if(autoSelectAllCheck.isSelected() != getAutoSelect()){ setAutoSelect(autoSelectAllCheck.isSelected()); try { PersistentSettings.getInstance().store(); } catch (IOException ex) { Logger.getLogger(TrackChooser.class.getName()).log(Level.SEVERE, null, ex); } } if(selectBase){ try { baseSelected = Integer.parseInt(selectBaseField.getText().replaceAll(",", "")); } catch (NumberFormatException ex){ baseSelected = -1; } } dispose(); } }); } private void createCancelButton(){ cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { retVal = null; dispose(); } }); } private boolean getAutoSelect(){ return PersistentSettings.getInstance().getBoolean("TRACK_CHOOSER_AUTO_SELECT", false); } private void setAutoSelect(boolean value){ PersistentSettings.getInstance().setBoolean("TRACK_CHOOSER_AUTO_SELECT", value); } private void createMoveRight(){ moveRight = new JButton(">"); moveRight.setToolTipText("Add item(s) to selected"); moveRight.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] selected = leftList.getSelectedValues(); if(selected.length > 1 && !multiple) return; if(((TrackListModel)rightList.getModel()).getSize() > 0 && !multiple) return; for(int i = 0; i < selected.length; i++){ ((TrackListModel)rightList.getModel()).add(selected[i].toString()); } ((TrackListModel)leftList.getModel()).removeIndices(leftList.getSelectedIndices()); rightList.updateUI(); leftList.updateUI(); leftList.clearSelection(); rightList.clearSelection(); } }); } private void createMoveLeft(){ moveLeft = new JButton("<"); moveLeft.setToolTipText("Remove item(s) from selected"); moveLeft.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] selected = rightList.getSelectedValues(); if(selected.length > 1 && !multiple) return; for(int i = 0; i < selected.length; i++){ ((TrackListModel)leftList.getModel()).add(selected[i].toString()); } ((TrackListModel)rightList.getModel()).removeIndices(rightList.getSelectedIndices()); leftList.updateUI(); rightList.updateUI(); leftList.clearSelection(); rightList.clearSelection(); } }); } private void createAllRight(){ allRight = new JButton(">>"); allRight.setToolTipText("Add all to selected"); if(!this.multiple) allRight.setEnabled(false); allRight.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectAll(); } }); } private void createAllLeft(){ allLeft = new JButton("<<"); allLeft.setToolTipText("Remove all from selected"); if(!this.multiple) allLeft.setEnabled(false); allLeft.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] stringsRight = ((TrackListModel)rightList.getModel()).getAll(); for(int i = 0; i < stringsRight.length; i++){ ((TrackListModel)leftList.getModel()).add(stringsRight[i]); } ((TrackListModel)rightList.getModel()).removeAll(); leftList.updateUI(); rightList.updateUI(); leftList.clearSelection(); rightList.clearSelection(); } }); } private void createSelectAllCheck(){ autoSelectAllCheck = new JCheckBox("Always select all"); autoSelectAllCheck.setSelected(getAutoSelect()); } private void createSelectBase(){ } private void init() { createMoveRight(); createMoveLeft(); createAllLeft(); createAllRight(); createOkButton(); createCancelButton(); createFilter(); createSelectAllCheck(); if(selectBase) createSelectBase(); initLayout(); } private void initLists() { leftList.setModel(new TrackListModel()); rightList.setModel(new TrackListModel()); List<Frame> frames = FrameController.getInstance().getFrames(); String[] trackNames = new String[frames.size()]; List<DataFormat> fileFormats = new ArrayList<DataFormat>(); for(int i = 0; i <frames.size(); i++){ //tracks[i] = frames.get(i).getTracks().get(0).getName(); trackNames[i] = frames.get(i).getName(); DataFormat ff = frames.get(i).getTracks()[0].getDataSource().getDataFormat(); if(!fileFormats.contains(ff)) fileFormats.add(ff); } filterCombo.addItem("All"); for(int i = 0; i < fileFormats.size(); i++){ filterCombo.addItem(MiscUtils.dataFormatToString(fileFormats.get(i))); } filterCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filter(); } }); ((TrackListModel)leftList.getModel()).init(trackNames); } private void selectAll(){ String[] stringsLeft = ((TrackListModel)leftList.getModel()).getAll(); for(int i = 0; i < stringsLeft.length; i++){ ((TrackListModel)rightList.getModel()).add(stringsLeft[i]); } ((TrackListModel)leftList.getModel()).removeAll(); leftList.updateUI(); rightList.updateUI(); leftList.clearSelection(); rightList.clearSelection(); } private class TrackListModel extends DefaultListModel { String[] strings = {}; @Override public int getSize() { return strings.length; } @Override public Object getElementAt(int i) { return strings[i]; } public void init(String[] strings1){ strings = strings1; } public void add(String s){ String[] strings1 = new String[strings.length+1]; System.arraycopy(strings, 0, strings1, 0, strings.length); strings1[strings.length] = s; strings = strings1; } public void removeIndex(int i){ if(strings.length <= i || i < 0) return; String[] strings1 = new String[strings.length-1]; int k = 0; for(int j = 0; j < strings.length; j++){ if(j!=i){ strings1[k] = strings[j]; k++; } } strings = strings1; } public void removeIndices(int[] indices){ String[] strings1 = new String[strings.length - indices.length]; int[] strings2 = new int[strings.length]; for(int i = 0; i < strings.length; i++) strings2[i] = 1; for(int i = 0; i < indices.length; i++) strings2[indices[i]] = 0; int j = 0; for(int i = 0; i < strings.length; i++){ if(strings2[i] == 1){ strings1[j] = strings[i]; j++; } } strings = strings1; } public String[] getAll(){ return strings; } public void removeAll(){ strings = new String[0]; } } }
false
true
private void initLayout(){ this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //FILLER filler1 = new JPanel(); filler1.setPreferredSize(new Dimension(10,10)); c.weightx = 1.0; c.weighty = 3.0; c.gridx = 0; c.gridy = 0; this.add(filler1, c); //LEFT LABEL leftLabel = new JLabel("All Tracks"); leftLabel.setFont(new Font(null, Font.BOLD, 12)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.anchor = GridBagConstraints.CENTER; this.add(leftLabel, c); //RIGHT LABEL rightLabel = new JLabel("Selected Tracks"); rightLabel.setFont(new Font(null, Font.BOLD, 12)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 1; c.gridwidth = 2; c.anchor = GridBagConstraints.CENTER; this.add(rightLabel, c); //LEFT LIST leftList = new JList(); leftScroll = new JScrollPane(); leftScroll.setViewportView(leftList); leftScroll.setMinimumSize(new Dimension(450,300)); leftScroll.setPreferredSize(new Dimension(450,300)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 2; c.gridwidth = 1; c.gridheight = 4; this.add(leftScroll, c); //FILLER filler3 = new JPanel(); filler3.setSize(60, 10); filler3.setPreferredSize(new Dimension(60,10)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 0; c.gridheight = 1; this.add(filler3, c); //MOVE RIGHT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 2; c.gridheight = 1; this.add(moveRight, c); //MOVE LEFT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 3; c.gridheight = 1; this.add(moveLeft, c); //ALL RIGHT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 4; c.gridheight = 1; this.add(allRight, c); //ALL LEFT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 5; c.gridheight = 1; this.add(allLeft, c); //RIGHT LIST rightList = new JList(); rightScroll = new JScrollPane(); rightScroll.setViewportView(rightList); rightScroll.setMinimumSize(new Dimension(450,300)); rightScroll.setPreferredSize(new Dimension(450,300)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 2; c.gridheight = 4; c.gridwidth = 2; this.add(rightScroll, c); //FILLER filler2 = new JPanel(); filler2.setSize(10, 40); filler2.setPreferredSize(new Dimension(10,40)); c.weightx = 0; c.weighty = 0; c.gridx = 5; c.gridy = 7; c.gridheight = 1; c.gridwidth = 1; this.add(filler2, c); //FILTER c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 6; c.gridheight = 1; c.gridwidth = 1; this.add(filterPanel, c); //AUTO SELECT ALL c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 6; c.gridheight = 1; c.gridwidth = 2; this.add(autoSelectAllCheck, c); //SEPARATOR JPanel sepPanel1 = new JPanel(); sepPanel1.setMinimumSize(new Dimension(5, 10)); sepPanel1.setBackground(Color.red); sepPanel1.setLayout(new BorderLayout()); sepPanel1.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.CENTER); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 7; c.gridheight = 1; c.gridwidth = 5; this.add(sepPanel1, c); int y = 8; if(selectBase){ //SELECT BASE PANEL JPanel selectBasePanel = new JPanel(); selectBasePanel.setMinimumSize(new Dimension(40, 10)); selectBasePanel.setLayout(new BorderLayout()); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = y; c.gridheight = 1; c.gridwidth = 2; this.add(selectBasePanel, c); //SELECT BASE LABEL JLabel selectBaseLabel = new JLabel("(Optional) Select Base: "); selectBasePanel.add(selectBaseLabel, BorderLayout.WEST); //SELECT BASE FIELD selectBaseField = new JTextField(); selectBasePanel.add(selectBaseField, BorderLayout.CENTER); //FILLER JPanel selectBaseFiller = new JPanel(); selectBaseFiller.setSize(new Dimension(10,10)); selectBaseFiller.setPreferredSize(new Dimension(10,10)); selectBasePanel.add(selectBaseFiller, BorderLayout.SOUTH); y++; //SEPARATOR JPanel sepPanel2 = new JPanel(); sepPanel2.setMinimumSize(new Dimension(10, 10)); sepPanel2.setBackground(Color.red); sepPanel2.setLayout(new BorderLayout()); sepPanel2.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.CENTER); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = y; c.gridheight = 1; c.gridwidth = 5; this.add(sepPanel2, c); y++; //FILLER JPanel filler5 = new JPanel(); filler5.setSize(10, 10); filler5.setPreferredSize(new Dimension(10,10)); c.weightx = 0; c.weighty = 0; c.gridx = 0; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(filler5, c); y++; } //OK c.fill = GridBagConstraints.NONE; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(okButton, c); //CANCEL c.weightx = 1.0; c.weighty = 0.5; c.gridx = 4; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(cancelButton, c); y++; //FILLER JPanel filler4 = new JPanel(); filler4.setSize(10, 10); filler4.setPreferredSize(new Dimension(10,10)); c.weightx = 0; c.weighty = 0; c.gridx = 0; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(filler4, c); pack(); }
private void initLayout(){ this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //FILLER filler1 = new JPanel(); filler1.setPreferredSize(new Dimension(10,10)); c.weightx = 1.0; c.weighty = 3.0; c.gridx = 0; c.gridy = 0; this.add(filler1, c); //LEFT LABEL leftLabel = new JLabel("All Tracks"); leftLabel.setFont(new Font(null, Font.BOLD, 12)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.anchor = GridBagConstraints.CENTER; this.add(leftLabel, c); //RIGHT LABEL rightLabel = new JLabel("Selected Tracks"); rightLabel.setFont(new Font(null, Font.BOLD, 12)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 1; c.gridwidth = 2; c.anchor = GridBagConstraints.CENTER; this.add(rightLabel, c); //LEFT LIST leftList = new JList(); leftScroll = new JScrollPane(); leftScroll.setViewportView(leftList); leftScroll.setMinimumSize(new Dimension(450,300)); leftScroll.setPreferredSize(new Dimension(450,300)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 2; c.gridwidth = 1; c.gridheight = 4; this.add(leftScroll, c); //FILLER filler3 = new JPanel(); filler3.setSize(60, 10); filler3.setPreferredSize(new Dimension(60,10)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 0; c.gridheight = 1; this.add(filler3, c); //MOVE RIGHT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 2; c.gridheight = 1; this.add(moveRight, c); //MOVE LEFT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 3; c.gridheight = 1; this.add(moveLeft, c); //ALL RIGHT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 4; c.gridheight = 1; this.add(allRight, c); //ALL LEFT c.weightx = 1.0; c.weighty = 1.0; c.gridx = 2; c.gridy = 5; c.gridheight = 1; this.add(allLeft, c); //RIGHT LIST rightList = new JList(); rightScroll = new JScrollPane(); rightScroll.setViewportView(rightList); rightScroll.setMinimumSize(new Dimension(450,300)); rightScroll.setPreferredSize(new Dimension(450,300)); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 2; c.gridheight = 4; c.gridwidth = 2; this.add(rightScroll, c); //FILLER filler2 = new JPanel(); filler2.setSize(10, 40); filler2.setPreferredSize(new Dimension(10,40)); c.weightx = 0; c.weighty = 0; c.gridx = 5; c.gridy = 7; c.gridheight = 1; c.gridwidth = 1; this.add(filler2, c); //FILTER c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 6; c.gridheight = 1; c.gridwidth = 1; this.add(filterPanel, c); //AUTO SELECT ALL c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = 6; c.gridheight = 1; c.gridwidth = 2; this.add(autoSelectAllCheck, c); //SEPARATOR JPanel sepPanel1 = new JPanel(); sepPanel1.setMinimumSize(new Dimension(5, 10)); sepPanel1.setLayout(new BorderLayout()); sepPanel1.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.CENTER); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = 7; c.gridheight = 1; c.gridwidth = 5; this.add(sepPanel1, c); int y = 8; if(selectBase){ //SELECT BASE PANEL JPanel selectBasePanel = new JPanel(); selectBasePanel.setMinimumSize(new Dimension(40, 10)); selectBasePanel.setLayout(new BorderLayout()); c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = y; c.gridheight = 1; c.gridwidth = 2; this.add(selectBasePanel, c); //SELECT BASE LABEL JLabel selectBaseLabel = new JLabel("(Optional) Select Base: "); selectBasePanel.add(selectBaseLabel, BorderLayout.WEST); //SELECT BASE FIELD selectBaseField = new JTextField(); selectBasePanel.add(selectBaseField, BorderLayout.CENTER); //FILLER JPanel selectBaseFiller = new JPanel(); selectBaseFiller.setSize(new Dimension(10,10)); selectBaseFiller.setPreferredSize(new Dimension(10,10)); selectBasePanel.add(selectBaseFiller, BorderLayout.SOUTH); y++; //SEPARATOR JPanel sepPanel2 = new JPanel(); sepPanel2.setMinimumSize(new Dimension(10, 10)); sepPanel2.setLayout(new BorderLayout()); sepPanel2.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.CENTER); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 1; c.gridy = y; c.gridheight = 1; c.gridwidth = 5; this.add(sepPanel2, c); y++; //FILLER JPanel filler5 = new JPanel(); filler5.setSize(10, 10); filler5.setPreferredSize(new Dimension(10,10)); c.weightx = 0; c.weighty = 0; c.gridx = 0; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(filler5, c); y++; } //OK c.fill = GridBagConstraints.NONE; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 3; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(okButton, c); //CANCEL c.weightx = 1.0; c.weighty = 0.5; c.gridx = 4; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(cancelButton, c); y++; //FILLER JPanel filler4 = new JPanel(); filler4.setSize(10, 10); filler4.setPreferredSize(new Dimension(10,10)); c.weightx = 0; c.weighty = 0; c.gridx = 0; c.gridy = y; c.gridheight = 1; c.gridwidth = 1; this.add(filler4, c); pack(); }
diff --git a/payment/broadleaf-paypal/src/main/java/org/broadleafcommerce/vendor/paypal/service/payment/PayPalRequestGeneratorImpl.java b/payment/broadleaf-paypal/src/main/java/org/broadleafcommerce/vendor/paypal/service/payment/PayPalRequestGeneratorImpl.java index 8fa030f..bbdd0bc 100644 --- a/payment/broadleaf-paypal/src/main/java/org/broadleafcommerce/vendor/paypal/service/payment/PayPalRequestGeneratorImpl.java +++ b/payment/broadleaf-paypal/src/main/java/org/broadleafcommerce/vendor/paypal/service/payment/PayPalRequestGeneratorImpl.java @@ -1,247 +1,246 @@ /* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.broadleafcommerce.vendor.paypal.service.payment; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.NameValuePair; import org.broadleafcommerce.vendor.paypal.service.payment.message.payment.PayPalItemRequest; import org.broadleafcommerce.vendor.paypal.service.payment.message.payment.PayPalPaymentRequest; import org.broadleafcommerce.vendor.paypal.service.payment.message.PayPalRequest; import org.broadleafcommerce.vendor.paypal.service.payment.message.details.PayPalDetailsRequest; import org.broadleafcommerce.vendor.paypal.service.payment.type.PayPalMethodType; import org.broadleafcommerce.vendor.paypal.service.payment.type.PayPalRefundType; /** * @author Jeff Fischer */ public class PayPalRequestGeneratorImpl implements PayPalRequestGenerator { protected String user; protected String password; protected String signature; protected String libVersion; protected String returnUrl; protected String cancelUrl; protected Map<String, String> additionalConfig; @Override public List<NameValuePair> buildRequest(PayPalRequest request) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); setBaseNvps(nvps); if (request.getMethodType() == PayPalMethodType.CHECKOUT) { setNvpsForCheckoutOrAuth(nvps, (PayPalPaymentRequest) request, MessageConstants.SALEACTION); - nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); + nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.DETAILSPAYMENTCURRENCYCODE, new Integer[]{0}, new String[]{"n"}), ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.AUTHORIZATION) { setNvpsForCheckoutOrAuth(nvps, (PayPalPaymentRequest) request, MessageConstants.AUTHORIZATIONACTION); - nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); + nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.DETAILSPAYMENTCURRENCYCODE, new Integer[]{0}, new String[]{"n"}), ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.PROCESS) { setNvpsForProcess(nvps, (PayPalPaymentRequest) request); - nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); + nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.DETAILSPAYMENTCURRENCYCODE, new Integer[]{0}, new String[]{"n"}), ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.REFUND) { setNvpsForRefund(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.CAPTURE) { setNvpsForCapture(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.VOID) { setNvpsForVoid(nvps, (PayPalPaymentRequest) request); - nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.DETAILS) { setNvpsForDetails(nvps, (PayPalDetailsRequest) request); } else { throw new IllegalArgumentException("Method type not supported: " + request.getMethodType().getFriendlyType()); } return nvps; } protected void setNvpsForDetails(List<NameValuePair> nvps, PayPalDetailsRequest paymentRequest) { nvps.add(new NameValuePair(MessageConstants.TOKEN, paymentRequest.getToken())); nvps.add(new NameValuePair(MessageConstants.METHOD, MessageConstants.PAYMENTDETAILSACTION)); } protected void setNvpsForVoid(List<NameValuePair> nvps, PayPalPaymentRequest paymentRequest) { nvps.add(new NameValuePair(MessageConstants.AUTHORIZATONID, paymentRequest.getTransactionID())); for (Map.Entry<String, String> entry : getAdditionalConfig().entrySet()) { nvps.add(new NameValuePair(entry.getKey(), entry.getValue())); } nvps.add(new NameValuePair(MessageConstants.METHOD, MessageConstants.VOIDACTION)); } protected void setNvpsForCapture(List<NameValuePair> nvps, PayPalPaymentRequest paymentRequest) { nvps.add(new NameValuePair(MessageConstants.AUTHORIZATONID, paymentRequest.getTransactionID())); nvps.add(new NameValuePair(MessageConstants.AMOUNT, paymentRequest.getSummaryRequest().getGrandTotal().toString())); nvps.add(new NameValuePair(MessageConstants.COMPLETETYPE, MessageConstants.CAPTURECOMPLETE)); for (Map.Entry<String, String> entry : getAdditionalConfig().entrySet()) { nvps.add(new NameValuePair(entry.getKey(), entry.getValue())); } nvps.add(new NameValuePair(MessageConstants.METHOD, MessageConstants.CAPTUREACTION)); } protected void setNvpsForRefund(List<NameValuePair> nvps, PayPalPaymentRequest paymentRequest) { nvps.add(new NameValuePair(MessageConstants.TRANSACTIONID, paymentRequest.getTransactionID())); nvps.add(new NameValuePair(MessageConstants.REFUNDTYPE, paymentRequest.getRefundType().getType())); if (paymentRequest.getRefundType() != PayPalRefundType.FULL) { nvps.add(new NameValuePair(MessageConstants.AMOUNT, paymentRequest.getSummaryRequest().getGrandTotal().toString())); } nvps.add(new NameValuePair(MessageConstants.METHOD, MessageConstants.REFUNDACTION)); } protected void setNvpsForProcess(List<NameValuePair> nvps, PayPalPaymentRequest paymentRequest) { if (paymentRequest.getSecondaryMethodType() != null && paymentRequest.getSecondaryMethodType() == PayPalMethodType.AUTHORIZATION) { nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.PAYMENTACTION, new Integer[]{0}, new String[]{"n"}), MessageConstants.AUTHORIZATIONACTION)); } else { nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.PAYMENTACTION, new Integer[]{0}, new String[]{"n"}), MessageConstants.SALEACTION)); } nvps.add(new NameValuePair(MessageConstants.TOKEN, paymentRequest.getToken())); nvps.add(new NameValuePair(MessageConstants.PAYERID, paymentRequest.getPayerID())); for (Map.Entry<String, String> entry : getAdditionalConfig().entrySet()) { nvps.add(new NameValuePair(entry.getKey(), entry.getValue())); } nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.GRANDTOTALREQUEST, new Integer[]{0}, new String[]{"n"}), paymentRequest.getSummaryRequest().getGrandTotal().toString())); nvps.add(new NameValuePair(MessageConstants.METHOD, MessageConstants.PROCESSPAYMENTACTION)); } protected void setBaseNvps(List<NameValuePair> nvps) { nvps.add(new NameValuePair(MessageConstants.USER, user)); nvps.add(new NameValuePair(MessageConstants.PASSWORD, password)); nvps.add(new NameValuePair(MessageConstants.SIGNATURE, signature)); nvps.add(new NameValuePair(MessageConstants.VERSION, libVersion)); } protected void setNvpsForCheckoutOrAuth(List<NameValuePair> nvps, PayPalPaymentRequest paymentRequest, String payPalAction) { nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.PAYMENTACTION, new Integer[]{0}, new String[]{"n"}), payPalAction)); nvps.add(new NameValuePair(MessageConstants.INVNUM, paymentRequest.getReferenceNumber())); //do not display shipping address fields on paypal pages //nvps.add(new NameValuePair(MessageConstants.NOSHIPPING, "1")); setCostNvps(nvps, paymentRequest); nvps.add(new NameValuePair(MessageConstants.RETURNURL, getReturnUrl())); nvps.add(new NameValuePair(MessageConstants.CANCELURL, getCancelUrl())); for (Map.Entry<String, String> entry : getAdditionalConfig().entrySet()) { nvps.add(new NameValuePair(entry.getKey(), entry.getValue())); } nvps.add(new NameValuePair(MessageConstants.METHOD, MessageConstants.EXPRESSCHECKOUTACTION)); } protected void setCostNvps(List<NameValuePair> nvps, PayPalPaymentRequest paymentRequest) { int counter = 0; for (PayPalItemRequest itemRequest : paymentRequest.getItemRequests()) { nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.NAMEREQUEST, new Integer[] {0, counter}, new String[] {"n", "m"}), itemRequest.getShortDescription())); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.NUMBERREQUEST, new Integer[] {0, counter}, new String[] {"n", "m"}), itemRequest.getSystemId())); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.DESCRIPTIONREQUEST, new Integer[] {0, counter}, new String[] {"n", "m"}), itemRequest.getDescription())); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.AMOUNTREQUEST, new Integer[] {0, counter}, new String[] {"n", "m"}), itemRequest.getUnitPrice().toString())); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.QUANTITYREQUEST, new Integer[] {0, counter}, new String[] {"n", "m"}), String.valueOf(itemRequest.getQuantity()))); counter++; } nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.SUBTOTALREQUEST, new Integer[] {0}, new String[] {"n"}), paymentRequest.getSummaryRequest().getSubTotal().toString())); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.TAXREQUEST, new Integer[] {0}, new String[] {"n"}), paymentRequest.getSummaryRequest().getTotalTax().toString())); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.SHIPPINGREQUEST, new Integer[] {0}, new String[] {"n"}), paymentRequest.getSummaryRequest().getTotalShipping().toString())); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.GRANDTOTALREQUEST, new Integer[] {0}, new String[] {"n"}), paymentRequest.getSummaryRequest().getGrandTotal().toString())); } protected String replaceNumericBoundProperty(String property, Integer[] number, String[] positions) { int counter = 0; for (String position : positions) { int pos = property.indexOf(position); if (pos < 0) { throw new IllegalArgumentException("Property does not contain the specified position value (" + position +")"); } String newValue = String.valueOf(number[counter]); property = property.substring(0 , pos) + newValue + property.substring(pos + position.length(), property.length()); counter++; } return property; } @Override public Map<String, String> getAdditionalConfig() { return additionalConfig; } @Override public void setAdditionalConfig(Map<String, String> additionalConfig) { this.additionalConfig = additionalConfig; } @Override public String getCancelUrl() { return cancelUrl; } @Override public void setCancelUrl(String cancelUrl) { this.cancelUrl = cancelUrl; } @Override public String getLibVersion() { return libVersion; } @Override public void setLibVersion(String libVersion) { this.libVersion = libVersion; } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getReturnUrl() { return returnUrl; } @Override public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } @Override public String getSignature() { return signature; } @Override public void setSignature(String signature) { this.signature = signature; } @Override public String getUser() { return user; } @Override public void setUser(String user) { this.user = user; } }
false
true
public List<NameValuePair> buildRequest(PayPalRequest request) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); setBaseNvps(nvps); if (request.getMethodType() == PayPalMethodType.CHECKOUT) { setNvpsForCheckoutOrAuth(nvps, (PayPalPaymentRequest) request, MessageConstants.SALEACTION); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.AUTHORIZATION) { setNvpsForCheckoutOrAuth(nvps, (PayPalPaymentRequest) request, MessageConstants.AUTHORIZATIONACTION); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.PROCESS) { setNvpsForProcess(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.REFUND) { setNvpsForRefund(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.CAPTURE) { setNvpsForCapture(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.VOID) { setNvpsForVoid(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.DETAILS) { setNvpsForDetails(nvps, (PayPalDetailsRequest) request); } else { throw new IllegalArgumentException("Method type not supported: " + request.getMethodType().getFriendlyType()); } return nvps; }
public List<NameValuePair> buildRequest(PayPalRequest request) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); setBaseNvps(nvps); if (request.getMethodType() == PayPalMethodType.CHECKOUT) { setNvpsForCheckoutOrAuth(nvps, (PayPalPaymentRequest) request, MessageConstants.SALEACTION); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.DETAILSPAYMENTCURRENCYCODE, new Integer[]{0}, new String[]{"n"}), ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.AUTHORIZATION) { setNvpsForCheckoutOrAuth(nvps, (PayPalPaymentRequest) request, MessageConstants.AUTHORIZATIONACTION); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.DETAILSPAYMENTCURRENCYCODE, new Integer[]{0}, new String[]{"n"}), ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.PROCESS) { setNvpsForProcess(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(replaceNumericBoundProperty(MessageConstants.DETAILSPAYMENTCURRENCYCODE, new Integer[]{0}, new String[]{"n"}), ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.REFUND) { setNvpsForRefund(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.CAPTURE) { setNvpsForCapture(nvps, (PayPalPaymentRequest) request); nvps.add(new NameValuePair(MessageConstants.CURRENCYCODE, ((PayPalPaymentRequest) request).getCurrency())); } else if (request.getMethodType() == PayPalMethodType.VOID) { setNvpsForVoid(nvps, (PayPalPaymentRequest) request); } else if (request.getMethodType() == PayPalMethodType.DETAILS) { setNvpsForDetails(nvps, (PayPalDetailsRequest) request); } else { throw new IllegalArgumentException("Method type not supported: " + request.getMethodType().getFriendlyType()); } return nvps; }
diff --git a/AKKtuell/src/org/akk/akktuell/Model/AkkHomepageEventParser.java b/AKKtuell/src/org/akk/akktuell/Model/AkkHomepageEventParser.java index 074689b..803a2de 100644 --- a/AKKtuell/src/org/akk/akktuell/Model/AkkHomepageEventParser.java +++ b/AKKtuell/src/org/akk/akktuell/Model/AkkHomepageEventParser.java @@ -1,394 +1,395 @@ package org.akk.akktuell.Model; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.LinkedList; import org.akk.akktuell.R; import org.akk.akktuell.Model.AkkEvent.AkkEventType; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.text.Html; import android.util.Log; public class AkkHomepageEventParser implements Runnable, EventDownloader { private LinkedList<AkkEvent> eventsWaitingForDescription; private LinkedList<AkkEvent> eventsWaitingForDBPush; private ThreadGroup getDescThreads; private Context context; private InfoManager infoManager; private boolean updateRequested = false; private ArrayList<EventDownloadListener> listeners = new ArrayList<EventDownloadListener>(); public AkkHomepageEventParser(Context ctx, InfoManager infoManager) { this.context = ctx; this.infoManager = infoManager; this.eventsWaitingForDescription = new LinkedList<AkkEvent>(); this.eventsWaitingForDBPush = new LinkedList<AkkEvent>(); getDescThreads = new ThreadGroup("EventUpdateThreads"); for (int i = 0; i < 3; i++) { new Thread(getDescThreads, this).start(); } } private String getAkkHpSource() throws IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.akk.org/chronologie.php"); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { str.append(line); } in.close(); return str.toString(); } private String getDescriptionSource(String link) throws IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(link); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while((line = reader.readLine()) != null) { str.append(line); } in.close(); return str.toString(); } @Override public boolean updateEvents() { if (!this.updateRequested) { this.updateRequested = true; String htmlSource; try { htmlSource = getAkkHpSource(); } catch (IOException e) { Log.d("AkkHomepageParser", "error while downloading akk source code"); e.printStackTrace(); AkkEvent[] result = new AkkEvent[1]; result[0] = new AkkEvent("Error while downloading", null,"test"); this.addElementToDBPushList(result[0]); return false; } LinkedList<AkkEvent> events = new LinkedList<AkkEvent>(); LinkedList<String> singleEventhtmlSource = getSingleEventSources(htmlSource); //remove first part singleEventhtmlSource.removeFirst(); //save last part for last_modified string String htmlContainingLastModified = singleEventhtmlSource.getLast(); singleEventhtmlSource.removeLast(); //remove part after "</TD></TR>" for (int i = 0; i < singleEventhtmlSource.size(); i++) { String currentLine = singleEventhtmlSource.get(i).split("</TD></TR>")[0]; singleEventhtmlSource.remove(i); singleEventhtmlSource.add(i, currentLine); //equivalent to string.matches but faster for multiple operations } //produce events from the lines AkkEvent newAkkEvent; String newAkkEventName; String newAkkEventPlace; Boolean hasDescription; GregorianCalendar newAkkEventDate; AkkEvent.AkkEventType newAkkEventType; for (String currentEventString : singleEventhtmlSource) { //check event type if (currentEventString.contains("Veranstaltungshinweis")) { newAkkEventType = AkkEventType.Veranstaltungshinweis; } else if (currentEventString.contains("Sonderveranstaltung")) { newAkkEventType = AkkEventType.Sonderveranstaltung; } else if (currentEventString.contains("Workshop")) { newAkkEventType = AkkEventType.Workshop; } else if (currentEventString.contains("Schlonz") || currentEventString.contains("Liveschlonz")) { newAkkEventType = AkkEventType.Schlonz; } else { newAkkEventType = AkkEventType.Tanzen; } //get eventDate newAkkEventDate = getEventDateFromString(currentEventString.substring(0,11)); //parse schlonze /* * example source String: * <TR><TD>Do. 19. Apr.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="/schlonze/schlonz.php?Kochduell">Kochduell Schlonz</A></TD><TD><A HREF="/adresse.php">Altes Stadion</A></TD></TR> * *ohne desc: * *<TR><TD>Di. 10. Jul.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> Reggae-Ska-Punk-Trash Schlonz</TD><TD><A HREF="/adresse.php">Altes Stadion</A></TD></TR> */ if (newAkkEventType == AkkEventType.Schlonz) { if (currentEventString.contains("HREF=\"/schlonze")) { hasDescription = true; } else { hasDescription = false; } try { if (hasDescription) { String source = currentEventString.split("/schlonze")[1]; newAkkEventName = source.split("\">")[1]; newAkkEventName = newAkkEventName.split("<")[0]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = source.split("adresse.php\">")[1]; newAkkEventPlace = newAkkEventPlace.split("<")[0]; newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); newAkkEvent.setDescription(currentEventString); newAkkEvent.setType(AkkEventType.Schlonz); this.addElementToWaitingList(newAkkEvent); } else { String source = currentEventString.split("</SPAN>")[2]; newAkkEventName = source.split("</TD><TD>")[1]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = source.split("adresse.php\">")[1]; newAkkEventPlace = newAkkEventPlace.split("<")[0]; newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); - newAkkEvent.setDescription(context.getResources().getString(R.string.no_description_available)); + newAkkEvent.setDescription(context.getResources().getString(R.string.hello)); newAkkEvent.setType(AkkEventType.Schlonz); this.addElementToDBPushList(newAkkEvent); } synchronized (this) { notify(); } } catch (ArrayIndexOutOfBoundsException e) { Log.d("HPParser", "Seems this is not a normal String: " + currentEventString); e.printStackTrace(); } } else if (newAkkEventType == AkkEventType.Veranstaltungshinweis) { /*example source * Mo. 16. Apr.</TD><TD></TD><TD> Veranstaltungshinweis: Rektor: Vorlesungsbeginn</TD><TD><A HREF="http://www.uni-karlsruhe.de/info/campusplan/">Campus</A> * * * Fr. 6. Jul.</TD><TD>15<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="http://www.z10.info/">Veranstaltungshinweis: Z10: Sommerfest</A></TD><TD><A HREF="http://www.z10.info/?topic">Z10</A></TD></TR> * Sa. 21. Apr.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="http://www.z10.info/">Veranstaltungshinweis: Z10: Konzert - Montreal, Liedfett, Ill</A></TD><TD><A HREF="http://www.z10.info/?topic">Z10</A> */ if (currentEventString.contains("Rektor")) { } else { if (currentEventString.endsWith("</A>")) { String source = currentEventString.split("\">")[3]; newAkkEventName = source.split("</A>")[0]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = currentEventString.split("\">")[4]; newAkkEventPlace = newAkkEventPlace.substring(0, newAkkEventPlace.length()-3); } else { newAkkEventName = currentEventString.split("</TD><TD>")[2];; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = currentEventString.split("</TD><TD>")[3]; } if (newAkkEventName.startsWith("\t")) { newAkkEventName = newAkkEventName.substring(1, newAkkEventName.length() -1); } newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); - newAkkEvent.setDescription(context.getResources().getString(R.string.no_description_available)); + newAkkEvent.setDescription(context.getResources().getString(R.string.hello)); newAkkEvent.setType(AkkEventType.Veranstaltungshinweis); this.addElementToDBPushList(newAkkEvent); synchronized (this) { notify(); } } } } } + return updateRequested; } private GregorianCalendar getEventDateFromString(String substring) { GregorianCalendar calendar = new GregorianCalendar(); if (substring.contains("Jan")) { calendar.set(GregorianCalendar.MONTH, 0); } else if (substring.contains("Feb")) { calendar.set(GregorianCalendar.MONTH, 1); } else if (substring.contains("Mar")) { calendar.set(GregorianCalendar.MONTH, 2); } else if (substring.contains("Apr")) { calendar.set(GregorianCalendar.MONTH, 3); } else if (substring.contains("Mai")) { calendar.set(GregorianCalendar.MONTH, 4); } else if (substring.contains("Jun")) { calendar.set(GregorianCalendar.MONTH, 5); } else if (substring.contains("Jul")) { calendar.set(GregorianCalendar.MONTH, 6); } else if (substring.contains("Aug")) { calendar.set(GregorianCalendar.MONTH, 7); } else if (substring.contains("Sep")) { calendar.set(GregorianCalendar.MONTH, 8); } else if (substring.contains("Okt")) { calendar.set(GregorianCalendar.MONTH, 9); } else if (substring.contains("Nov")) { calendar.set(GregorianCalendar.MONTH, 10); } else if (substring.contains("Dez")) { calendar.set(GregorianCalendar.MONTH, 11); } else { Log.d("Halt", "STOP!"); } return calendar; } private LinkedList<String> getSingleEventSources(String htmlSource) { LinkedList<String> returnStrings = new LinkedList<String>(); String[] eventSourceSequence = htmlSource.split("<TR><TD>"); for (String s : eventSourceSequence) { returnStrings.addLast(s); } return returnStrings; } public void run() { AkkEvent event = null; while (true) { if (this.elementsWaitingForDesc()) { synchronized (this) { if (this.elementsWaitingForDesc()) { event = this.popElementFromwaitingList(); } } if (event != null) { addDescriptionToEvent(event); this.addElementToDBPushList(event); } } if (this.elementsWaitingForDBPush()){ event = popElementFromDBPushList(); //something to do here? infoManager.appendEvent(event); } else { try { synchronized (this) { wait(); } } catch (InterruptedException e) { Log.d("AkkHomepageParse", "Thread got InterrupterException."); } } } } private void addDescriptionToEvent(AkkEvent event) { String eventSource = event.getEventDescription(); eventSource = eventSource.split("<A HREF=\"")[1]; String eventDescriptionSource = eventSource.split("\">")[0]; eventDescriptionSource = "http://www.akk.org" + eventDescriptionSource; try { eventDescriptionSource = getDescriptionSource(eventDescriptionSource); String eventDescription = eventDescriptionSource.split("<P>")[1]; eventDescription = Html.fromHtml(eventDescription.split("</P>")[0]).toString(); event.setDescription(eventDescription); } catch (IOException e) { Log.d("HPParser", "Could not get event Description..."); e.printStackTrace(); event.setDescription("Error fetching Description"); return; } catch (ArrayIndexOutOfBoundsException e) { Log.d("HPParser", "Could not get event Description..."); e.printStackTrace(); event.setDescription("Error fetching Description"); return; } } private boolean elementsWaitingForDBPush() { synchronized (this) { return !this.eventsWaitingForDBPush.isEmpty(); } } private boolean elementsWaitingForDesc() { synchronized (this) { return !this.eventsWaitingForDescription.isEmpty(); } } private void addElementToWaitingList(AkkEvent event) { synchronized (this) { this.eventsWaitingForDescription.addLast(event); } } private AkkEvent popElementFromwaitingList() { AkkEvent event; synchronized(this) { event = this.eventsWaitingForDescription.getFirst(); this.eventsWaitingForDescription.removeFirst(); } return event; } private void addElementToDBPushList(AkkEvent event) { synchronized (this) { this.eventsWaitingForDBPush.addLast(event); } } private AkkEvent popElementFromDBPushList() { AkkEvent event; synchronized (this) { event = this.eventsWaitingForDBPush.getFirst(); this.eventsWaitingForDBPush.removeFirst(); } return event; } @Override public boolean addEventDownloadListener(EventDownloadListener listener) { return this.listeners.add(listener); } @Override public boolean removeEventDownloadListener(EventDownloadListener listener) { return this.listeners.remove(listener); } @Override public boolean isUpdating() { return this.updateRequested; } }
false
true
public boolean updateEvents() { if (!this.updateRequested) { this.updateRequested = true; String htmlSource; try { htmlSource = getAkkHpSource(); } catch (IOException e) { Log.d("AkkHomepageParser", "error while downloading akk source code"); e.printStackTrace(); AkkEvent[] result = new AkkEvent[1]; result[0] = new AkkEvent("Error while downloading", null,"test"); this.addElementToDBPushList(result[0]); return false; } LinkedList<AkkEvent> events = new LinkedList<AkkEvent>(); LinkedList<String> singleEventhtmlSource = getSingleEventSources(htmlSource); //remove first part singleEventhtmlSource.removeFirst(); //save last part for last_modified string String htmlContainingLastModified = singleEventhtmlSource.getLast(); singleEventhtmlSource.removeLast(); //remove part after "</TD></TR>" for (int i = 0; i < singleEventhtmlSource.size(); i++) { String currentLine = singleEventhtmlSource.get(i).split("</TD></TR>")[0]; singleEventhtmlSource.remove(i); singleEventhtmlSource.add(i, currentLine); //equivalent to string.matches but faster for multiple operations } //produce events from the lines AkkEvent newAkkEvent; String newAkkEventName; String newAkkEventPlace; Boolean hasDescription; GregorianCalendar newAkkEventDate; AkkEvent.AkkEventType newAkkEventType; for (String currentEventString : singleEventhtmlSource) { //check event type if (currentEventString.contains("Veranstaltungshinweis")) { newAkkEventType = AkkEventType.Veranstaltungshinweis; } else if (currentEventString.contains("Sonderveranstaltung")) { newAkkEventType = AkkEventType.Sonderveranstaltung; } else if (currentEventString.contains("Workshop")) { newAkkEventType = AkkEventType.Workshop; } else if (currentEventString.contains("Schlonz") || currentEventString.contains("Liveschlonz")) { newAkkEventType = AkkEventType.Schlonz; } else { newAkkEventType = AkkEventType.Tanzen; } //get eventDate newAkkEventDate = getEventDateFromString(currentEventString.substring(0,11)); //parse schlonze /* * example source String: * <TR><TD>Do. 19. Apr.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="/schlonze/schlonz.php?Kochduell">Kochduell Schlonz</A></TD><TD><A HREF="/adresse.php">Altes Stadion</A></TD></TR> * *ohne desc: * *<TR><TD>Di. 10. Jul.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> Reggae-Ska-Punk-Trash Schlonz</TD><TD><A HREF="/adresse.php">Altes Stadion</A></TD></TR> */ if (newAkkEventType == AkkEventType.Schlonz) { if (currentEventString.contains("HREF=\"/schlonze")) { hasDescription = true; } else { hasDescription = false; } try { if (hasDescription) { String source = currentEventString.split("/schlonze")[1]; newAkkEventName = source.split("\">")[1]; newAkkEventName = newAkkEventName.split("<")[0]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = source.split("adresse.php\">")[1]; newAkkEventPlace = newAkkEventPlace.split("<")[0]; newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); newAkkEvent.setDescription(currentEventString); newAkkEvent.setType(AkkEventType.Schlonz); this.addElementToWaitingList(newAkkEvent); } else { String source = currentEventString.split("</SPAN>")[2]; newAkkEventName = source.split("</TD><TD>")[1]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = source.split("adresse.php\">")[1]; newAkkEventPlace = newAkkEventPlace.split("<")[0]; newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); newAkkEvent.setDescription(context.getResources().getString(R.string.no_description_available)); newAkkEvent.setType(AkkEventType.Schlonz); this.addElementToDBPushList(newAkkEvent); } synchronized (this) { notify(); } } catch (ArrayIndexOutOfBoundsException e) { Log.d("HPParser", "Seems this is not a normal String: " + currentEventString); e.printStackTrace(); } } else if (newAkkEventType == AkkEventType.Veranstaltungshinweis) { /*example source * Mo. 16. Apr.</TD><TD></TD><TD> Veranstaltungshinweis: Rektor: Vorlesungsbeginn</TD><TD><A HREF="http://www.uni-karlsruhe.de/info/campusplan/">Campus</A> * * * Fr. 6. Jul.</TD><TD>15<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="http://www.z10.info/">Veranstaltungshinweis: Z10: Sommerfest</A></TD><TD><A HREF="http://www.z10.info/?topic">Z10</A></TD></TR> * Sa. 21. Apr.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="http://www.z10.info/">Veranstaltungshinweis: Z10: Konzert - Montreal, Liedfett, Ill</A></TD><TD><A HREF="http://www.z10.info/?topic">Z10</A> */ if (currentEventString.contains("Rektor")) { } else { if (currentEventString.endsWith("</A>")) { String source = currentEventString.split("\">")[3]; newAkkEventName = source.split("</A>")[0]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = currentEventString.split("\">")[4]; newAkkEventPlace = newAkkEventPlace.substring(0, newAkkEventPlace.length()-3); } else { newAkkEventName = currentEventString.split("</TD><TD>")[2];; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = currentEventString.split("</TD><TD>")[3]; } if (newAkkEventName.startsWith("\t")) { newAkkEventName = newAkkEventName.substring(1, newAkkEventName.length() -1); } newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); newAkkEvent.setDescription(context.getResources().getString(R.string.no_description_available)); newAkkEvent.setType(AkkEventType.Veranstaltungshinweis); this.addElementToDBPushList(newAkkEvent); synchronized (this) { notify(); } } } } } }
public boolean updateEvents() { if (!this.updateRequested) { this.updateRequested = true; String htmlSource; try { htmlSource = getAkkHpSource(); } catch (IOException e) { Log.d("AkkHomepageParser", "error while downloading akk source code"); e.printStackTrace(); AkkEvent[] result = new AkkEvent[1]; result[0] = new AkkEvent("Error while downloading", null,"test"); this.addElementToDBPushList(result[0]); return false; } LinkedList<AkkEvent> events = new LinkedList<AkkEvent>(); LinkedList<String> singleEventhtmlSource = getSingleEventSources(htmlSource); //remove first part singleEventhtmlSource.removeFirst(); //save last part for last_modified string String htmlContainingLastModified = singleEventhtmlSource.getLast(); singleEventhtmlSource.removeLast(); //remove part after "</TD></TR>" for (int i = 0; i < singleEventhtmlSource.size(); i++) { String currentLine = singleEventhtmlSource.get(i).split("</TD></TR>")[0]; singleEventhtmlSource.remove(i); singleEventhtmlSource.add(i, currentLine); //equivalent to string.matches but faster for multiple operations } //produce events from the lines AkkEvent newAkkEvent; String newAkkEventName; String newAkkEventPlace; Boolean hasDescription; GregorianCalendar newAkkEventDate; AkkEvent.AkkEventType newAkkEventType; for (String currentEventString : singleEventhtmlSource) { //check event type if (currentEventString.contains("Veranstaltungshinweis")) { newAkkEventType = AkkEventType.Veranstaltungshinweis; } else if (currentEventString.contains("Sonderveranstaltung")) { newAkkEventType = AkkEventType.Sonderveranstaltung; } else if (currentEventString.contains("Workshop")) { newAkkEventType = AkkEventType.Workshop; } else if (currentEventString.contains("Schlonz") || currentEventString.contains("Liveschlonz")) { newAkkEventType = AkkEventType.Schlonz; } else { newAkkEventType = AkkEventType.Tanzen; } //get eventDate newAkkEventDate = getEventDateFromString(currentEventString.substring(0,11)); //parse schlonze /* * example source String: * <TR><TD>Do. 19. Apr.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="/schlonze/schlonz.php?Kochduell">Kochduell Schlonz</A></TD><TD><A HREF="/adresse.php">Altes Stadion</A></TD></TR> * *ohne desc: * *<TR><TD>Di. 10. Jul.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> Reggae-Ska-Punk-Trash Schlonz</TD><TD><A HREF="/adresse.php">Altes Stadion</A></TD></TR> */ if (newAkkEventType == AkkEventType.Schlonz) { if (currentEventString.contains("HREF=\"/schlonze")) { hasDescription = true; } else { hasDescription = false; } try { if (hasDescription) { String source = currentEventString.split("/schlonze")[1]; newAkkEventName = source.split("\">")[1]; newAkkEventName = newAkkEventName.split("<")[0]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = source.split("adresse.php\">")[1]; newAkkEventPlace = newAkkEventPlace.split("<")[0]; newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); newAkkEvent.setDescription(currentEventString); newAkkEvent.setType(AkkEventType.Schlonz); this.addElementToWaitingList(newAkkEvent); } else { String source = currentEventString.split("</SPAN>")[2]; newAkkEventName = source.split("</TD><TD>")[1]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = source.split("adresse.php\">")[1]; newAkkEventPlace = newAkkEventPlace.split("<")[0]; newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); newAkkEvent.setDescription(context.getResources().getString(R.string.hello)); newAkkEvent.setType(AkkEventType.Schlonz); this.addElementToDBPushList(newAkkEvent); } synchronized (this) { notify(); } } catch (ArrayIndexOutOfBoundsException e) { Log.d("HPParser", "Seems this is not a normal String: " + currentEventString); e.printStackTrace(); } } else if (newAkkEventType == AkkEventType.Veranstaltungshinweis) { /*example source * Mo. 16. Apr.</TD><TD></TD><TD> Veranstaltungshinweis: Rektor: Vorlesungsbeginn</TD><TD><A HREF="http://www.uni-karlsruhe.de/info/campusplan/">Campus</A> * * * Fr. 6. Jul.</TD><TD>15<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="http://www.z10.info/">Veranstaltungshinweis: Z10: Sommerfest</A></TD><TD><A HREF="http://www.z10.info/?topic">Z10</A></TD></TR> * Sa. 21. Apr.</TD><TD>20<SPAN class="min-alt">:</SPAN><SPAN class="min">00</SPAN> Uhr</TD><TD> <A HREF="http://www.z10.info/">Veranstaltungshinweis: Z10: Konzert - Montreal, Liedfett, Ill</A></TD><TD><A HREF="http://www.z10.info/?topic">Z10</A> */ if (currentEventString.contains("Rektor")) { } else { if (currentEventString.endsWith("</A>")) { String source = currentEventString.split("\">")[3]; newAkkEventName = source.split("</A>")[0]; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = currentEventString.split("\">")[4]; newAkkEventPlace = newAkkEventPlace.substring(0, newAkkEventPlace.length()-3); } else { newAkkEventName = currentEventString.split("</TD><TD>")[2];; newAkkEventName = Html.fromHtml(newAkkEventName).toString(); newAkkEventPlace = currentEventString.split("</TD><TD>")[3]; } if (newAkkEventName.startsWith("\t")) { newAkkEventName = newAkkEventName.substring(1, newAkkEventName.length() -1); } newAkkEvent = new AkkEvent(newAkkEventName, newAkkEventDate, newAkkEventPlace); newAkkEvent.setDescription(context.getResources().getString(R.string.hello)); newAkkEvent.setType(AkkEventType.Veranstaltungshinweis); this.addElementToDBPushList(newAkkEvent); synchronized (this) { notify(); } } } } } return updateRequested; }
diff --git a/hibernate-core/src/matrix/java/org/hibernate/test/dialect/functional/SQLServerDialectTest.java b/hibernate-core/src/matrix/java/org/hibernate/test/dialect/functional/SQLServerDialectTest.java index 53a9631b06..00d7bffea1 100644 --- a/hibernate-core/src/matrix/java/org/hibernate/test/dialect/functional/SQLServerDialectTest.java +++ b/hibernate-core/src/matrix/java/org/hibernate/test/dialect/functional/SQLServerDialectTest.java @@ -1,195 +1,195 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates or third- * party contributors as indicated by the @author tags or express * copyright attribution statements applied by the authors. * All third-party contributions are distributed under license by * Red Hat, Inc. * * This copyrighted material is made available to anyone wishing to * use, modify, copy, or redistribute it subject to the terms and * conditions of the GNU Lesser General Public License, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this distribution; if not, write to: * * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.dialect.functional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.util.List; import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.dialect.SQLServer2005Dialect; import org.hibernate.exception.SQLGrammarException; import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.junit.Test; /** * used driver hibernate.connection.driver_class com.microsoft.sqlserver.jdbc.SQLServerDriver * * @author Guenther Demetz */ @RequiresDialect(value = { SQLServer2005Dialect.class }) public class SQLServerDialectTest extends BaseCoreFunctionalTestCase { @TestForIssue(jiraKey = "HHH-7198") @Test public void testMaxResultsSqlServerWithCaseSensitiveCollation() throws Exception { Session s = openSession(); Connection conn = ( (SessionFactoryImpl) s.getSessionFactory() ).getConnectionProvider().getConnection(); String databaseName = conn.getCatalog(); conn.close(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " set single_user with rollback immediate" ) .executeUpdate(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " COLLATE Latin1_General_CS_AS" ).executeUpdate(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " set multi_user" ).executeUpdate(); Transaction tx = s.beginTransaction(); for ( int i = 1; i <= 20; i++ ) { Product2 kit = new Product2(); kit.id = i; kit.description = "Kit" + i; s.persist( kit ); } s.flush(); s.clear(); - List list = s.createQuery( "from Product where description like 'Kit%'" ) + List list = s.createQuery( "from Product2 where description like 'Kit%'" ) .setFirstResult( 2 ) .setMaxResults( 2 ) .list(); // without patch this query produces following sql (Note that the tablename as well as the like condition have turned into lowercase)" // WITH query AS (select product0_.id as id0_, product0_.description as descript2_0_, ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __hibernate_row_nr__ from product product0_ where product0_.description like 'kit%') SELECT * FROM query WHERE __hibernate_row_nr__ >= ? AND __hibernate_row_nr__ < ? // this leads to following exception: // org.hibernate.exception.SQLGrammarException: Invalid object name 'product'. // at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122) // at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) // at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) // at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) // at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:130) // at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) // at $Proxy18.executeQuery(Unknown Source) // at org.hibernate.loader.Loader.getResultSet(Loader.java:1953) // ... // Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'product'. // at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340) // at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575) // at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:154) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:283) // at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) // at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) // at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) // at java.lang.reflect.Method.invoke(Unknown Source) // at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) // ... 44 more assertEquals( 2, list.size() ); tx.rollback(); s.close(); } @TestForIssue(jiraKey = "HHH-3961") @Test public void testLockNowaitSqlServer() throws Exception { Session s = openSession(); s.beginTransaction(); final Product2 kit = new Product2(); kit.id = 4000; kit.description = "m"; s.persist( kit ); s.getTransaction().commit(); final Transaction tx = s.beginTransaction(); Session s2 = openSession(); Transaction tx2 = s2.beginTransaction(); //s2.createSQLQuery("SET LOCK_TIMEOUT 5000;Select @@LOCK_TIMEOUT;").uniqueResult(); strangely this is useless for this kind of locks Product2 kit2 = (Product2) s2.byId( Product2.class ).load( kit.id ); kit.description = "change!"; s.flush(); // creates write lock on kit until we end the transaction Thread thread = new Thread( new Runnable() { @Override public void run() { try { Thread.sleep( 3000 ); } catch ( InterruptedException e ) { e.printStackTrace(); } tx.commit(); } } ); LockOptions opt = new LockOptions( LockMode.UPGRADE_NOWAIT ); opt.setTimeOut( 0 ); // seems useless long start = System.currentTimeMillis(); thread.start(); try { s2.buildLockRequest( opt ).lock( kit2 ); } catch ( SQLGrammarException e ) { // OK } long end = System.currentTimeMillis(); thread.join(); long differenceInMillisecs = end - start; assertTrue( "Lock NoWait blocked for " + differenceInMillisecs + " ms, this is definitely to much for Nowait", differenceInMillisecs < 2000 ); s2.getTransaction().rollback(); s.getTransaction().begin(); s.delete( kit ); s.getTransaction().commit(); } @Override protected java.lang.Class<?>[] getAnnotatedClasses() { return new java.lang.Class[] { Product2.class }; } }
true
true
public void testMaxResultsSqlServerWithCaseSensitiveCollation() throws Exception { Session s = openSession(); Connection conn = ( (SessionFactoryImpl) s.getSessionFactory() ).getConnectionProvider().getConnection(); String databaseName = conn.getCatalog(); conn.close(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " set single_user with rollback immediate" ) .executeUpdate(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " COLLATE Latin1_General_CS_AS" ).executeUpdate(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " set multi_user" ).executeUpdate(); Transaction tx = s.beginTransaction(); for ( int i = 1; i <= 20; i++ ) { Product2 kit = new Product2(); kit.id = i; kit.description = "Kit" + i; s.persist( kit ); } s.flush(); s.clear(); List list = s.createQuery( "from Product where description like 'Kit%'" ) .setFirstResult( 2 ) .setMaxResults( 2 ) .list(); // without patch this query produces following sql (Note that the tablename as well as the like condition have turned into lowercase)" // WITH query AS (select product0_.id as id0_, product0_.description as descript2_0_, ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __hibernate_row_nr__ from product product0_ where product0_.description like 'kit%') SELECT * FROM query WHERE __hibernate_row_nr__ >= ? AND __hibernate_row_nr__ < ? // this leads to following exception: // org.hibernate.exception.SQLGrammarException: Invalid object name 'product'. // at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122) // at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) // at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) // at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) // at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:130) // at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) // at $Proxy18.executeQuery(Unknown Source) // at org.hibernate.loader.Loader.getResultSet(Loader.java:1953) // ... // Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'product'. // at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340) // at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575) // at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:154) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:283) // at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) // at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) // at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) // at java.lang.reflect.Method.invoke(Unknown Source) // at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) // ... 44 more assertEquals( 2, list.size() ); tx.rollback(); s.close(); }
public void testMaxResultsSqlServerWithCaseSensitiveCollation() throws Exception { Session s = openSession(); Connection conn = ( (SessionFactoryImpl) s.getSessionFactory() ).getConnectionProvider().getConnection(); String databaseName = conn.getCatalog(); conn.close(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " set single_user with rollback immediate" ) .executeUpdate(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " COLLATE Latin1_General_CS_AS" ).executeUpdate(); s.createSQLQuery( "ALTER DATABASE " + databaseName + " set multi_user" ).executeUpdate(); Transaction tx = s.beginTransaction(); for ( int i = 1; i <= 20; i++ ) { Product2 kit = new Product2(); kit.id = i; kit.description = "Kit" + i; s.persist( kit ); } s.flush(); s.clear(); List list = s.createQuery( "from Product2 where description like 'Kit%'" ) .setFirstResult( 2 ) .setMaxResults( 2 ) .list(); // without patch this query produces following sql (Note that the tablename as well as the like condition have turned into lowercase)" // WITH query AS (select product0_.id as id0_, product0_.description as descript2_0_, ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as __hibernate_row_nr__ from product product0_ where product0_.description like 'kit%') SELECT * FROM query WHERE __hibernate_row_nr__ >= ? AND __hibernate_row_nr__ < ? // this leads to following exception: // org.hibernate.exception.SQLGrammarException: Invalid object name 'product'. // at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122) // at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) // at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) // at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) // at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:130) // at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) // at $Proxy18.executeQuery(Unknown Source) // at org.hibernate.loader.Loader.getResultSet(Loader.java:1953) // ... // Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name 'product'. // at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340) // at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575) // at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179) // at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:154) // at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:283) // at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) // at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) // at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) // at java.lang.reflect.Method.invoke(Unknown Source) // at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) // ... 44 more assertEquals( 2, list.size() ); tx.rollback(); s.close(); }
diff --git a/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java b/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java index c5a87cbf..eeedb42e 100644 --- a/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java +++ b/src/java/org/jivesoftware/spark/ui/rooms/ChatRoomImpl.java @@ -1,671 +1,671 @@ /** * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Lesser Public License (LGPL), * a copy of which is included in this distribution. */ package org.jivesoftware.spark.ui.rooms; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.OrFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.StreamError; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.MessageEventManager; import org.jivesoftware.smackx.packet.MessageEvent; import org.jivesoftware.spark.ChatManager; import org.jivesoftware.spark.PresenceManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomButton; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.ui.ContactList; import org.jivesoftware.spark.ui.FromJIDFilter; import org.jivesoftware.spark.ui.MessageEventListener; import org.jivesoftware.spark.ui.RosterDialog; import org.jivesoftware.spark.ui.VCardPanel; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.TaskEngine; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscript; import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscripts; import org.jivesoftware.sparkimpl.plugin.transcripts.HistoryMessage; import org.jivesoftware.sparkimpl.profile.VCardManager; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import javax.swing.Icon; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.TimerTask; /** * This is the Person to Person implementation of <code>ChatRoom</code> * This room only allows for 1 to 1 conversations. */ public class ChatRoomImpl extends ChatRoom { private List messageEventListeners = new ArrayList(); private String roomname; private Icon tabIcon; private String roomTitle; private String tabTitle; private String participantJID; private String participantNickname; boolean isOnline = true; private Presence presence; private boolean offlineSent; private Roster roster; private long lastTypedCharTime; private boolean sendNotification; private TimerTask typingTimerTask; private boolean sendTypingNotification; private String threadID; private long lastActivity; /** * Constructs a 1-to-1 ChatRoom. * * @param jid the participants jid to chat with. * @param participantNickname the nickname of the participant. * @param title the title of the room. */ - public ChatRoomImpl(String jid, String participantNickname, String title) { + public ChatRoomImpl(final String jid, String participantNickname, String title) { this.participantJID = jid; roster = SparkManager.getConnection().getRoster(); Iterator<Presence> presences = roster.getPresences(jid); int count = 0; Presence p = null; if (presences.hasNext()) { p = presences.next(); count++; } if(count == 1 && p != null && p.getFrom() != null){ participantJID = p.getFrom(); } this.participantNickname = participantNickname; // Loads the current history for this user. loadHistory(); // Register PacketListeners - PacketFilter fromFilter = new FromJIDFilter(participantJID); + PacketFilter fromFilter = new FromJIDFilter(jid); PacketFilter orFilter = new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class)); PacketFilter andFilter = new AndFilter(orFilter, fromFilter); SparkManager.getConnection().addPacketListener(this, andFilter); // The roomname will be the participantJID this.roomname = jid; // Use the agents username as the Tab Title this.tabTitle = title; // The name of the room will be the node of the user jid + conversation. final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); this.roomTitle = participantNickname; // Add RoomInfo this.getSplitPane().setRightComponent(null); getSplitPane().setDividerSize(0); presence = PresenceManager.getPresence(participantJID); - RosterEntry entry = roster.getEntry(participantJID); + RosterEntry entry = roster.getEntry(jid); tabIcon = PresenceManager.getIconFromPresence(presence); // Create toolbar buttons. ChatRoomButton infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24)); infoButton.setToolTipText(Res.getString("message.view.information.about.this.user")); // Create basic toolbar. getToolBar().addChatRoomButton(infoButton); // If the user is not in the roster, then allow user to add them. if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) { ChatRoomButton addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24)); addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster")); getToolBar().addChatRoomButton(addToRosterButton); addToRosterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RosterDialog rosterDialog = new RosterDialog(); - rosterDialog.setDefaultJID(participantJID); + rosterDialog.setDefaultJID(jid); rosterDialog.setDefaultNickname(getParticipantNickname()); rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame()); } }); } // Show VCard. infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VCardManager vcard = SparkManager.getVCardManager(); - vcard.viewProfile(participantJID, SparkManager.getChatManager().getChatContainer()); + vcard.viewProfile(jid, SparkManager.getChatManager().getChatContainer()); } }); // If this is a private chat from a group chat room, do not show toolbar. if (StringUtils.parseResource(participantJID).equals(participantNickname)) { getToolBar().setVisible(false); } typingTimerTask = new TimerTask() { public void run() { if (!sendTypingNotification) { return; } long now = System.currentTimeMillis(); if (now - lastTypedCharTime > 2000) { if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } } } }; TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000); lastActivity = System.currentTimeMillis(); } public void closeChatRoom() { super.closeChatRoom(); // Send a cancel notification event on closing if listening. if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } SparkManager.getChatManager().removeChat(this); SparkManager.getConnection().removePacketListener(this); typingTimerTask.cancel(); } public void sendMessage() { String text = getChatInputEditor().getText(); sendMessage(text); } public void sendMessage(String text) { final Message message = new Message(); if (threadID == null) { threadID = StringUtils.randomString(6); } message.setThread(threadID); // Set the body of the message using typedMessage message.setBody(text); // IF there is no body, just return and do nothing if (!ModelUtil.hasLength(text)) { return; } // Fire Message Filters SparkManager.getChatManager().filterOutgoingMessage(this, message); // Fire Global Filters SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message); sendMessage(message); sendNotification = true; } /** * Sends a message to the appropriate jid. The message is automatically added to the transcript. * * @param message the message to send. */ public void sendMessage(Message message) { lastActivity = System.currentTimeMillis(); try { getTranscriptWindow().insertMessage(getNickname(), message, ChatManager.TO_COLOR); getChatInputEditor().selectAll(); getTranscriptWindow().validate(); getTranscriptWindow().repaint(); getChatInputEditor().clear(); } catch (Exception ex) { Log.error("Error sending message", ex); } // Before sending message, let's add our full jid for full verification message.setType(Message.Type.chat); message.setTo(participantJID); message.setFrom(SparkManager.getSessionManager().getJID()); // Notify users that message has been sent fireMessageSent(message); addToTranscript(message, false); getChatInputEditor().setCaretPosition(0); getChatInputEditor().requestFocusInWindow(); scrollToBottom(); // No need to request displayed or delivered as we aren't doing anything with this // information. MessageEventManager.addNotificationsRequests(message, true, false, false, true); // Send the message that contains the notifications request try { fireOutgoingMessageSending(message); SparkManager.getConnection().sendPacket(message); } catch (Exception ex) { Log.error("Error sending message", ex); } } public String getRoomname() { return roomname; } public Icon getTabIcon() { return tabIcon; } public void setTabIcon(Icon icon) { this.tabIcon = icon; } public String getTabTitle() { return tabTitle; } public void setTabTitle(String tabTitle) { this.tabTitle = tabTitle; } public void setRoomTitle(String roomTitle) { this.roomTitle = roomTitle; } public String getRoomTitle() { return roomTitle; } public Message.Type getChatType() { return Message.Type.chat; } public void leaveChatRoom() { // There really is no such thing in Agent to Agent } public boolean isActive() { return true; } public String getParticipantJID() { return participantJID; } /** * Returns the users full jid (ex. [email protected]/spark). * * @return the users Full JID. */ public String getJID() { presence = PresenceManager.getPresence(getParticipantJID()); return presence.getFrom(); } /** * Process incoming packets. * * @param packet - the packet to process */ public void processPacket(final Packet packet) { final Runnable runnable = new Runnable() { public void run() { if (packet instanceof Presence) { presence = (Presence)packet; final Presence presence = (Presence)packet; ContactList list = SparkManager.getWorkspace().getContactList(); ContactItem contactItem = list.getContactItemByJID(getParticipantJID()); final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); String time = formatter.format(new Date()); if (presence.getType() == Presence.Type.unavailable && contactItem != null) { if (isOnline) { getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.went.offline", participantNickname, time), ChatManager.NOTIFICATION_COLOR); } isOnline = false; } else if (presence.getType() == Presence.Type.available) { if (!isOnline) { getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.came.online", participantNickname, time), ChatManager.NOTIFICATION_COLOR); } isOnline = true; } } else if (packet instanceof Message) { lastActivity = System.currentTimeMillis(); // Do something with the incoming packet here. final Message message = (Message)packet; if (message.getError() != null) { if (message.getError().getCode() == 404) { // Check to see if the user is online to recieve this message. RosterEntry entry = roster.getEntry(participantJID); if (!presence.isAvailable() && !offlineSent && entry != null) { getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline.error"), ChatManager.ERROR_COLOR); offlineSent = true; } } return; } // Check to see if the user is online to recieve this message. RosterEntry entry = roster.getEntry(participantJID); if (!presence.isAvailable() && !offlineSent && entry != null) { getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline"), ChatManager.ERROR_COLOR); offlineSent = true; } if (threadID == null) { threadID = message.getThread(); if (threadID == null) { threadID = StringUtils.randomString(6); } } boolean broadcast = message.getProperty("broadcast") != null; // If this is a group chat message, discard if (message.getType() == Message.Type.groupchat || broadcast) { return; } // Do not accept Administrative messages. final String host = SparkManager.getSessionManager().getServerAddress(); if (host.equals(message.getFrom())) { return; } // If the message is not from the current agent. Append to chat. if (message.getBody() != null) { participantJID = message.getFrom(); insertMessage(message); showTyping(false); } } } }; SwingUtilities.invokeLater(runnable); } /** * Returns the nickname of the user chatting with. * * @return the nickname of the chatting user. */ public String getParticipantNickname() { return participantNickname; } /** * The current SendField has been updated somehow. * * @param e - the DocumentEvent to respond to. */ public void insertUpdate(DocumentEvent e) { checkForText(e); if (!sendTypingNotification) { return; } lastTypedCharTime = System.currentTimeMillis(); // If the user pauses for more than two seconds, send out a new notice. if (sendNotification) { try { SparkManager.getMessageEventManager().sendComposingNotification(getParticipantJID(), threadID); sendNotification = false; } catch (Exception exception) { Log.error("Error updating", exception); } } } public void insertMessage(Message message) { // Debug info super.insertMessage(message); MessageEvent messageEvent = (MessageEvent)message.getExtension("x", "jabber:x:event"); if (messageEvent != null) { checkEvents(message.getFrom(), message.getPacketID(), messageEvent); } getTranscriptWindow().insertMessage(participantNickname, message, ChatManager.FROM_COLOR); // Set the participant jid to their full JID. participantJID = message.getFrom(); } private void checkEvents(String from, String packetID, MessageEvent messageEvent) { if (messageEvent.isDelivered() || messageEvent.isDisplayed()) { // Create the message to send Message msg = new Message(from); // Create a MessageEvent Package and add it to the message MessageEvent event = new MessageEvent(); if (messageEvent.isDelivered()) { event.setDelivered(true); } if (messageEvent.isDisplayed()) { event.setDisplayed(true); } event.setPacketID(packetID); msg.addExtension(event); // Send the packet SparkManager.getConnection().sendPacket(msg); } } public void addMessageEventListener(MessageEventListener listener) { messageEventListeners.add(listener); } public void removeMessageEventListener(MessageEventListener listener) { messageEventListeners.remove(listener); } public Collection getMessageEventListeners() { return messageEventListeners; } public void fireOutgoingMessageSending(Message message) { Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator(); while (messageEventListeners.hasNext()) { ((MessageEventListener)messageEventListeners.next()).sendingMessage(message); } } public void fireReceivingIncomingMessage(Message message) { Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator(); while (messageEventListeners.hasNext()) { ((MessageEventListener)messageEventListeners.next()).receivingMessage(message); } } /** * Show the typing notification. * * @param typing true if the typing notification should show, otherwise hide it. */ public void showTyping(boolean typing) { if (typing) { String isTypingText = Res.getString("message.is.typing.a.message", participantNickname); getNotificationLabel().setText(isTypingText); getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_EDIT_IMAGE)); } else { // Remove is typing text. getNotificationLabel().setText(""); getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.BLANK_IMAGE)); } } /** * The last time this chat room sent or received a message. * * @return the last time this chat room sent or receieved a message. */ public long getLastActivity() { return lastActivity; } /** * Returns the current presence of the client this room was created for. * * @return the presence */ public Presence getPresence() { return presence; } public void setSendTypingNotification(boolean isSendTypingNotification) { this.sendTypingNotification = isSendTypingNotification; } public void connectionClosed() { handleDisconnect(); String message = Res.getString("message.disconnected.error"); getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR); } public void connectionClosedOnError(Exception ex) { handleDisconnect(); String message = Res.getString("message.disconnected.error"); if (ex instanceof XMPPException) { XMPPException xmppEx = (XMPPException)ex; StreamError error = xmppEx.getStreamError(); String reason = error.getCode(); if ("conflict".equals(reason)) { message = Res.getString("message.disconnected.conflict.error"); } } getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR); } public void reconnectionSuccessful() { Presence usersPresence = PresenceManager.getPresence(getParticipantJID()); if (usersPresence.isAvailable()) { presence = usersPresence; } SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this); getChatInputEditor().setEnabled(true); getSendButton().setEnabled(true); } private void handleDisconnect() { presence = new Presence(Presence.Type.unavailable); getChatInputEditor().setEnabled(false); getSendButton().setEnabled(false); SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this); } private void loadHistory() { // Add VCard Panel final VCardPanel vcardPanel = new VCardPanel(participantJID); getToolBar().add(vcardPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 2), 0, 0)); final LocalPreferences localPreferences = SettingsManager.getLocalPreferences(); if (!localPreferences.isChatHistoryEnabled()) { return; } final String bareJID = StringUtils.parseBareAddress(getParticipantJID()); final ChatTranscript chatTranscript = ChatTranscripts.getCurrentChatTranscript(bareJID); final String personalNickname = SparkManager.getUserManager().getNickname(); for (HistoryMessage message : chatTranscript.getMessages()) { String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String messageBody = message.getBody(); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (ModelUtil.hasLength(messageBody) && messageBody.startsWith("/me ")) { messageBody = messageBody.replaceAll("/me", nickname); } final Date messageDate = message.getDate(); getTranscriptWindow().insertHistoryMessage(nickname, messageBody, messageDate); } } }
false
true
public ChatRoomImpl(String jid, String participantNickname, String title) { this.participantJID = jid; roster = SparkManager.getConnection().getRoster(); Iterator<Presence> presences = roster.getPresences(jid); int count = 0; Presence p = null; if (presences.hasNext()) { p = presences.next(); count++; } if(count == 1 && p != null && p.getFrom() != null){ participantJID = p.getFrom(); } this.participantNickname = participantNickname; // Loads the current history for this user. loadHistory(); // Register PacketListeners PacketFilter fromFilter = new FromJIDFilter(participantJID); PacketFilter orFilter = new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class)); PacketFilter andFilter = new AndFilter(orFilter, fromFilter); SparkManager.getConnection().addPacketListener(this, andFilter); // The roomname will be the participantJID this.roomname = jid; // Use the agents username as the Tab Title this.tabTitle = title; // The name of the room will be the node of the user jid + conversation. final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); this.roomTitle = participantNickname; // Add RoomInfo this.getSplitPane().setRightComponent(null); getSplitPane().setDividerSize(0); presence = PresenceManager.getPresence(participantJID); RosterEntry entry = roster.getEntry(participantJID); tabIcon = PresenceManager.getIconFromPresence(presence); // Create toolbar buttons. ChatRoomButton infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24)); infoButton.setToolTipText(Res.getString("message.view.information.about.this.user")); // Create basic toolbar. getToolBar().addChatRoomButton(infoButton); // If the user is not in the roster, then allow user to add them. if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) { ChatRoomButton addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24)); addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster")); getToolBar().addChatRoomButton(addToRosterButton); addToRosterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RosterDialog rosterDialog = new RosterDialog(); rosterDialog.setDefaultJID(participantJID); rosterDialog.setDefaultNickname(getParticipantNickname()); rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame()); } }); } // Show VCard. infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VCardManager vcard = SparkManager.getVCardManager(); vcard.viewProfile(participantJID, SparkManager.getChatManager().getChatContainer()); } }); // If this is a private chat from a group chat room, do not show toolbar. if (StringUtils.parseResource(participantJID).equals(participantNickname)) { getToolBar().setVisible(false); } typingTimerTask = new TimerTask() { public void run() { if (!sendTypingNotification) { return; } long now = System.currentTimeMillis(); if (now - lastTypedCharTime > 2000) { if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } } } }; TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000); lastActivity = System.currentTimeMillis(); }
public ChatRoomImpl(final String jid, String participantNickname, String title) { this.participantJID = jid; roster = SparkManager.getConnection().getRoster(); Iterator<Presence> presences = roster.getPresences(jid); int count = 0; Presence p = null; if (presences.hasNext()) { p = presences.next(); count++; } if(count == 1 && p != null && p.getFrom() != null){ participantJID = p.getFrom(); } this.participantNickname = participantNickname; // Loads the current history for this user. loadHistory(); // Register PacketListeners PacketFilter fromFilter = new FromJIDFilter(jid); PacketFilter orFilter = new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class)); PacketFilter andFilter = new AndFilter(orFilter, fromFilter); SparkManager.getConnection().addPacketListener(this, andFilter); // The roomname will be the participantJID this.roomname = jid; // Use the agents username as the Tab Title this.tabTitle = title; // The name of the room will be the node of the user jid + conversation. final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); this.roomTitle = participantNickname; // Add RoomInfo this.getSplitPane().setRightComponent(null); getSplitPane().setDividerSize(0); presence = PresenceManager.getPresence(participantJID); RosterEntry entry = roster.getEntry(jid); tabIcon = PresenceManager.getIconFromPresence(presence); // Create toolbar buttons. ChatRoomButton infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24)); infoButton.setToolTipText(Res.getString("message.view.information.about.this.user")); // Create basic toolbar. getToolBar().addChatRoomButton(infoButton); // If the user is not in the roster, then allow user to add them. if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) { ChatRoomButton addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24)); addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster")); getToolBar().addChatRoomButton(addToRosterButton); addToRosterButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RosterDialog rosterDialog = new RosterDialog(); rosterDialog.setDefaultJID(jid); rosterDialog.setDefaultNickname(getParticipantNickname()); rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame()); } }); } // Show VCard. infoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VCardManager vcard = SparkManager.getVCardManager(); vcard.viewProfile(jid, SparkManager.getChatManager().getChatContainer()); } }); // If this is a private chat from a group chat room, do not show toolbar. if (StringUtils.parseResource(participantJID).equals(participantNickname)) { getToolBar().setVisible(false); } typingTimerTask = new TimerTask() { public void run() { if (!sendTypingNotification) { return; } long now = System.currentTimeMillis(); if (now - lastTypedCharTime > 2000) { if (!sendNotification) { // send cancel SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID); sendNotification = true; } } } }; TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000); lastActivity = System.currentTimeMillis(); }
diff --git a/src/main/java/hudson/plugins/jira/JiraProjectProperty.java b/src/main/java/hudson/plugins/jira/JiraProjectProperty.java index 02248b9..5a21c52 100644 --- a/src/main/java/hudson/plugins/jira/JiraProjectProperty.java +++ b/src/main/java/hudson/plugins/jira/JiraProjectProperty.java @@ -1,137 +1,141 @@ package hudson.plugins.jira; import hudson.Util; import hudson.model.AbstractProject; import hudson.model.Job; import hudson.model.JobProperty; import hudson.model.JobPropertyDescriptor; import hudson.util.CopyOnWriteList; import hudson.util.FormFieldValidator; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; /** * Associates {@link AbstractProject} with {@link JiraSite}. * * @author Kohsuke Kawaguchi */ public class JiraProjectProperty extends JobProperty<AbstractProject<?,?>> { /** * Used to find {@link JiraSite}. Matches {@link JiraSite#getName()}. * Always non-null (but beware that this value might become stale * if the system config is changed.) */ public final String siteName; /** * @stapler-constructor */ public JiraProjectProperty(String siteName) { if(siteName==null) { // defaults to the first one JiraSite[] sites = DESCRIPTOR.getSites(); if(sites.length>0) siteName = sites[0].getName(); } this.siteName = siteName; } /** * Gets the {@link JiraSite} that this project belongs to. * * @return * null if the configuration becomes out of sync. */ public JiraSite getSite() { JiraSite[] sites = DESCRIPTOR.getSites(); if(siteName==null && sites.length>0) // default return sites[0]; for( JiraSite site : sites ) { if(site.getName().equals(siteName)) return site; } return null; } public DescriptorImpl getDescriptor() { return DESCRIPTOR; } public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); public static final class DescriptorImpl extends JobPropertyDescriptor { private final CopyOnWriteList<JiraSite> sites = new CopyOnWriteList<JiraSite>(); public DescriptorImpl() { super(JiraProjectProperty.class); load(); } public boolean isApplicable(Class<? extends Job> jobType) { return AbstractProject.class.isAssignableFrom(jobType); } public String getDisplayName() { return "Associated JIRA"; } public JiraSite[] getSites() { return sites.toArray(new JiraSite[0]); } public JobProperty<?> newInstance(StaplerRequest req) throws FormException { JiraProjectProperty jpp = req.bindParameters(JiraProjectProperty.class, "jira."); if(jpp.siteName==null) jpp = null; // not configured return jpp; } public boolean configure(StaplerRequest req) { sites.replaceBy(req.bindParametersToList(JiraSite.class,"jira.")); save(); return true; } /** * Checks if the JIRA URL is accessible and exists. */ - public void doURLCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { + public void doUrlCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this can be used to check existence of any file in any URL, so admin only new FormFieldValidator(req,rsp,true) { protected void check() throws IOException, ServletException { String url = Util.fixEmpty(request.getParameter("value")); if(url==null) { error("JIRA URL is a mandatory field"); return; } try { BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream(),"UTF-8")); String line; while((line=in.readLine())!=null) { if(line.indexOf("Atlassian JIRA")!=-1) { ok(); // looks like it return; } } error("This is a valid URL but it doesn't look like JIRA"); } catch (IOException e) { - // any invalid URL comes here - error(e.getMessage()); + // any invalid URL comes here + if(e.getMessage().equals(url)) + // Sun JRE (and probably others too) often return just the URL in the error. + error("Unable to connect "+url); + else + error(e.getMessage()); } } }.process(); } } }
false
true
public void doURLCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this can be used to check existence of any file in any URL, so admin only new FormFieldValidator(req,rsp,true) { protected void check() throws IOException, ServletException { String url = Util.fixEmpty(request.getParameter("value")); if(url==null) { error("JIRA URL is a mandatory field"); return; } try { BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream(),"UTF-8")); String line; while((line=in.readLine())!=null) { if(line.indexOf("Atlassian JIRA")!=-1) { ok(); // looks like it return; } } error("This is a valid URL but it doesn't look like JIRA"); } catch (IOException e) { // any invalid URL comes here error(e.getMessage()); } } }.process(); }
public void doUrlCheck(final StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this can be used to check existence of any file in any URL, so admin only new FormFieldValidator(req,rsp,true) { protected void check() throws IOException, ServletException { String url = Util.fixEmpty(request.getParameter("value")); if(url==null) { error("JIRA URL is a mandatory field"); return; } try { BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream(),"UTF-8")); String line; while((line=in.readLine())!=null) { if(line.indexOf("Atlassian JIRA")!=-1) { ok(); // looks like it return; } } error("This is a valid URL but it doesn't look like JIRA"); } catch (IOException e) { // any invalid URL comes here if(e.getMessage().equals(url)) // Sun JRE (and probably others too) often return just the URL in the error. error("Unable to connect "+url); else error(e.getMessage()); } } }.process(); }
diff --git a/src/com/android/providers/downloads/DownloadNotifier.java b/src/com/android/providers/downloads/DownloadNotifier.java index f832eae..df0bf84 100644 --- a/src/com/android/providers/downloads/DownloadNotifier.java +++ b/src/com/android/providers/downloads/DownloadNotifier.java @@ -1,364 +1,366 @@ /* * 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.providers.downloads; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED; import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION; import static android.provider.Downloads.Impl.STATUS_RUNNING; import static com.android.providers.downloads.Constants.TAG; import android.app.DownloadManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.SystemClock; import android.provider.Downloads; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.Log; import android.util.LongSparseLongArray; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import javax.annotation.concurrent.GuardedBy; /** * Update {@link NotificationManager} to reflect current {@link DownloadInfo} * states. Collapses similar downloads into a single notification, and builds * {@link PendingIntent} that launch towards {@link DownloadReceiver}. */ public class DownloadNotifier { private static final int TYPE_ACTIVE = 1; private static final int TYPE_WAITING = 2; private static final int TYPE_COMPLETE = 3; private final Context mContext; private final NotificationManager mNotifManager; /** * Currently active notifications, mapped from clustering tag to timestamp * when first shown. * * @see #buildNotificationTag(DownloadInfo) */ @GuardedBy("mActiveNotifs") private final HashMap<String, Long> mActiveNotifs = Maps.newHashMap(); /** * Current speed of active downloads, mapped from {@link DownloadInfo#mId} * to speed in bytes per second. */ @GuardedBy("mDownloadSpeed") private final LongSparseLongArray mDownloadSpeed = new LongSparseLongArray(); /** * Last time speed was reproted, mapped from {@link DownloadInfo#mId} to * {@link SystemClock#elapsedRealtime()}. */ @GuardedBy("mDownloadSpeed") private final LongSparseLongArray mDownloadTouch = new LongSparseLongArray(); public DownloadNotifier(Context context) { mContext = context; mNotifManager = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE); } public void cancelAll() { mNotifManager.cancelAll(); } /** * Notify the current speed of an active download, used for calculating * estimated remaining time. */ public void notifyDownloadSpeed(long id, long bytesPerSecond) { synchronized (mDownloadSpeed) { if (bytesPerSecond != 0) { mDownloadSpeed.put(id, bytesPerSecond); mDownloadTouch.put(id, SystemClock.elapsedRealtime()); } else { mDownloadSpeed.delete(id); mDownloadTouch.delete(id); } } } /** * Update {@link NotificationManager} to reflect the given set of * {@link DownloadInfo}, adding, collapsing, and removing as needed. */ public void updateWith(Collection<DownloadInfo> downloads) { synchronized (mActiveNotifs) { updateWithLocked(downloads); } } private void updateWithLocked(Collection<DownloadInfo> downloads) { final Resources res = mContext.getResources(); // Cluster downloads together final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create(); for (DownloadInfo info : downloads) { final String tag = buildNotificationTag(info); if (tag != null) { clustered.put(tag, info); } } // Build notification for each cluster for (String tag : clustered.keySet()) { final int type = getNotificationTagType(tag); final Collection<DownloadInfo> cluster = clustered.get(tag); final Notification.Builder builder = new Notification.Builder(mContext); // Use time when cluster was first shown to avoid shuffling final long firstShown; if (mActiveNotifs.containsKey(tag)) { firstShown = mActiveNotifs.get(tag); } else { firstShown = System.currentTimeMillis(); mActiveNotifs.put(tag, firstShown); } builder.setWhen(firstShown); // Show relevant icon if (type == TYPE_ACTIVE) { builder.setSmallIcon(android.R.drawable.stat_sys_download); } else if (type == TYPE_WAITING) { builder.setSmallIcon(android.R.drawable.stat_sys_warning); } else if (type == TYPE_COMPLETE) { builder.setSmallIcon(android.R.drawable.stat_sys_download_done); } // Build action intents if (type == TYPE_ACTIVE || type == TYPE_WAITING) { final Intent intent = new Intent(Constants.ACTION_LIST, null, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); - builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0)); + builder.setContentIntent(PendingIntent.getBroadcast( + mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); builder.setOngoing(true); } else if (type == TYPE_COMPLETE) { final DownloadInfo info = cluster.iterator().next(); final Uri uri = ContentUris.withAppendedId( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId); final String action; if (Downloads.Impl.isStatusError(info.mStatus)) { action = Constants.ACTION_LIST; } else { if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) { action = Constants.ACTION_OPEN; } else { action = Constants.ACTION_LIST; } } final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); - builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0)); + builder.setContentIntent(PendingIntent.getBroadcast( + mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class); builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0)); } // Calculate and show progress String remainingText = null; String percentText = null; if (type == TYPE_ACTIVE) { long current = 0; long total = 0; long speed = 0; synchronized (mDownloadSpeed) { for (DownloadInfo info : cluster) { if (info.mTotalBytes != -1) { current += info.mCurrentBytes; total += info.mTotalBytes; speed += mDownloadSpeed.get(info.mId); } } } if (total > 0) { final int percent = (int) ((current * 100) / total); percentText = res.getString(R.string.download_percent, percent); if (speed > 0) { final long remainingMillis = ((total - current) * 1000) / speed; remainingText = res.getString(R.string.download_remaining, DateUtils.formatDuration(remainingMillis)); } builder.setProgress(100, percent, false); } else { builder.setProgress(100, 0, true); } } // Build titles and description final Notification notif; if (cluster.size() == 1) { final DownloadInfo info = cluster.iterator().next(); builder.setContentTitle(getDownloadTitle(res, info)); if (type == TYPE_ACTIVE) { if (!TextUtils.isEmpty(info.mDescription)) { builder.setContentText(info.mDescription); } else { builder.setContentText(remainingText); } builder.setContentInfo(percentText); } else if (type == TYPE_WAITING) { builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); } else if (type == TYPE_COMPLETE) { if (Downloads.Impl.isStatusError(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_failed)); } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) { builder.setContentText( res.getText(R.string.notification_download_complete)); } } notif = builder.build(); } else { final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder); for (DownloadInfo info : cluster) { inboxStyle.addLine(getDownloadTitle(res, info)); } if (type == TYPE_ACTIVE) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_active, cluster.size(), cluster.size())); builder.setContentText(remainingText); builder.setContentInfo(percentText); inboxStyle.setSummaryText(remainingText); } else if (type == TYPE_WAITING) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_waiting, cluster.size(), cluster.size())); builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); inboxStyle.setSummaryText( res.getString(R.string.notification_need_wifi_for_size)); } notif = inboxStyle.build(); } mNotifManager.notify(tag, 0, notif); } // Remove stale tags that weren't renewed final Iterator<String> it = mActiveNotifs.keySet().iterator(); while (it.hasNext()) { final String tag = it.next(); if (!clustered.containsKey(tag)) { mNotifManager.cancel(tag, 0); it.remove(); } } } private static CharSequence getDownloadTitle(Resources res, DownloadInfo info) { if (!TextUtils.isEmpty(info.mTitle)) { return info.mTitle; } else { return res.getString(R.string.download_unknown_title); } } private long[] getDownloadIds(Collection<DownloadInfo> infos) { final long[] ids = new long[infos.size()]; int i = 0; for (DownloadInfo info : infos) { ids[i++] = info.mId; } return ids; } public void dumpSpeeds() { synchronized (mDownloadSpeed) { for (int i = 0; i < mDownloadSpeed.size(); i++) { final long id = mDownloadSpeed.keyAt(i); final long delta = SystemClock.elapsedRealtime() - mDownloadTouch.get(id); Log.d(TAG, "Download " + id + " speed " + mDownloadSpeed.valueAt(i) + "bps, " + delta + "ms ago"); } } } /** * Build tag used for collapsing several {@link DownloadInfo} into a single * {@link Notification}. */ private static String buildNotificationTag(DownloadInfo info) { if (info.mStatus == Downloads.Impl.STATUS_QUEUED_FOR_WIFI) { return TYPE_WAITING + ":" + info.mPackage; } else if (isActiveAndVisible(info)) { return TYPE_ACTIVE + ":" + info.mPackage; } else if (isCompleteAndVisible(info)) { // Complete downloads always have unique notifs return TYPE_COMPLETE + ":" + info.mId; } else { return null; } } /** * Return the cluster type of the given tag, as created by * {@link #buildNotificationTag(DownloadInfo)}. */ private static int getNotificationTagType(String tag) { return Integer.parseInt(tag.substring(0, tag.indexOf(':'))); } private static boolean isActiveAndVisible(DownloadInfo download) { return download.mStatus == STATUS_RUNNING && (download.mVisibility == VISIBILITY_VISIBLE || download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED); } private static boolean isCompleteAndVisible(DownloadInfo download) { return Downloads.Impl.isStatusCompleted(download.mStatus) && (download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED || download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION); } }
false
true
private void updateWithLocked(Collection<DownloadInfo> downloads) { final Resources res = mContext.getResources(); // Cluster downloads together final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create(); for (DownloadInfo info : downloads) { final String tag = buildNotificationTag(info); if (tag != null) { clustered.put(tag, info); } } // Build notification for each cluster for (String tag : clustered.keySet()) { final int type = getNotificationTagType(tag); final Collection<DownloadInfo> cluster = clustered.get(tag); final Notification.Builder builder = new Notification.Builder(mContext); // Use time when cluster was first shown to avoid shuffling final long firstShown; if (mActiveNotifs.containsKey(tag)) { firstShown = mActiveNotifs.get(tag); } else { firstShown = System.currentTimeMillis(); mActiveNotifs.put(tag, firstShown); } builder.setWhen(firstShown); // Show relevant icon if (type == TYPE_ACTIVE) { builder.setSmallIcon(android.R.drawable.stat_sys_download); } else if (type == TYPE_WAITING) { builder.setSmallIcon(android.R.drawable.stat_sys_warning); } else if (type == TYPE_COMPLETE) { builder.setSmallIcon(android.R.drawable.stat_sys_download_done); } // Build action intents if (type == TYPE_ACTIVE || type == TYPE_WAITING) { final Intent intent = new Intent(Constants.ACTION_LIST, null, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0)); builder.setOngoing(true); } else if (type == TYPE_COMPLETE) { final DownloadInfo info = cluster.iterator().next(); final Uri uri = ContentUris.withAppendedId( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId); final String action; if (Downloads.Impl.isStatusError(info.mStatus)) { action = Constants.ACTION_LIST; } else { if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) { action = Constants.ACTION_OPEN; } else { action = Constants.ACTION_LIST; } } final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0)); final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class); builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0)); } // Calculate and show progress String remainingText = null; String percentText = null; if (type == TYPE_ACTIVE) { long current = 0; long total = 0; long speed = 0; synchronized (mDownloadSpeed) { for (DownloadInfo info : cluster) { if (info.mTotalBytes != -1) { current += info.mCurrentBytes; total += info.mTotalBytes; speed += mDownloadSpeed.get(info.mId); } } } if (total > 0) { final int percent = (int) ((current * 100) / total); percentText = res.getString(R.string.download_percent, percent); if (speed > 0) { final long remainingMillis = ((total - current) * 1000) / speed; remainingText = res.getString(R.string.download_remaining, DateUtils.formatDuration(remainingMillis)); } builder.setProgress(100, percent, false); } else { builder.setProgress(100, 0, true); } } // Build titles and description final Notification notif; if (cluster.size() == 1) { final DownloadInfo info = cluster.iterator().next(); builder.setContentTitle(getDownloadTitle(res, info)); if (type == TYPE_ACTIVE) { if (!TextUtils.isEmpty(info.mDescription)) { builder.setContentText(info.mDescription); } else { builder.setContentText(remainingText); } builder.setContentInfo(percentText); } else if (type == TYPE_WAITING) { builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); } else if (type == TYPE_COMPLETE) { if (Downloads.Impl.isStatusError(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_failed)); } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) { builder.setContentText( res.getText(R.string.notification_download_complete)); } } notif = builder.build(); } else { final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder); for (DownloadInfo info : cluster) { inboxStyle.addLine(getDownloadTitle(res, info)); } if (type == TYPE_ACTIVE) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_active, cluster.size(), cluster.size())); builder.setContentText(remainingText); builder.setContentInfo(percentText); inboxStyle.setSummaryText(remainingText); } else if (type == TYPE_WAITING) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_waiting, cluster.size(), cluster.size())); builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); inboxStyle.setSummaryText( res.getString(R.string.notification_need_wifi_for_size)); } notif = inboxStyle.build(); } mNotifManager.notify(tag, 0, notif); } // Remove stale tags that weren't renewed final Iterator<String> it = mActiveNotifs.keySet().iterator(); while (it.hasNext()) { final String tag = it.next(); if (!clustered.containsKey(tag)) { mNotifManager.cancel(tag, 0); it.remove(); } } }
private void updateWithLocked(Collection<DownloadInfo> downloads) { final Resources res = mContext.getResources(); // Cluster downloads together final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create(); for (DownloadInfo info : downloads) { final String tag = buildNotificationTag(info); if (tag != null) { clustered.put(tag, info); } } // Build notification for each cluster for (String tag : clustered.keySet()) { final int type = getNotificationTagType(tag); final Collection<DownloadInfo> cluster = clustered.get(tag); final Notification.Builder builder = new Notification.Builder(mContext); // Use time when cluster was first shown to avoid shuffling final long firstShown; if (mActiveNotifs.containsKey(tag)) { firstShown = mActiveNotifs.get(tag); } else { firstShown = System.currentTimeMillis(); mActiveNotifs.put(tag, firstShown); } builder.setWhen(firstShown); // Show relevant icon if (type == TYPE_ACTIVE) { builder.setSmallIcon(android.R.drawable.stat_sys_download); } else if (type == TYPE_WAITING) { builder.setSmallIcon(android.R.drawable.stat_sys_warning); } else if (type == TYPE_COMPLETE) { builder.setSmallIcon(android.R.drawable.stat_sys_download_done); } // Build action intents if (type == TYPE_ACTIVE || type == TYPE_WAITING) { final Intent intent = new Intent(Constants.ACTION_LIST, null, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast( mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); builder.setOngoing(true); } else if (type == TYPE_COMPLETE) { final DownloadInfo info = cluster.iterator().next(); final Uri uri = ContentUris.withAppendedId( Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId); final String action; if (Downloads.Impl.isStatusError(info.mStatus)) { action = Constants.ACTION_LIST; } else { if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) { action = Constants.ACTION_OPEN; } else { action = Constants.ACTION_LIST; } } final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class); intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster)); builder.setContentIntent(PendingIntent.getBroadcast( mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class); builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0)); } // Calculate and show progress String remainingText = null; String percentText = null; if (type == TYPE_ACTIVE) { long current = 0; long total = 0; long speed = 0; synchronized (mDownloadSpeed) { for (DownloadInfo info : cluster) { if (info.mTotalBytes != -1) { current += info.mCurrentBytes; total += info.mTotalBytes; speed += mDownloadSpeed.get(info.mId); } } } if (total > 0) { final int percent = (int) ((current * 100) / total); percentText = res.getString(R.string.download_percent, percent); if (speed > 0) { final long remainingMillis = ((total - current) * 1000) / speed; remainingText = res.getString(R.string.download_remaining, DateUtils.formatDuration(remainingMillis)); } builder.setProgress(100, percent, false); } else { builder.setProgress(100, 0, true); } } // Build titles and description final Notification notif; if (cluster.size() == 1) { final DownloadInfo info = cluster.iterator().next(); builder.setContentTitle(getDownloadTitle(res, info)); if (type == TYPE_ACTIVE) { if (!TextUtils.isEmpty(info.mDescription)) { builder.setContentText(info.mDescription); } else { builder.setContentText(remainingText); } builder.setContentInfo(percentText); } else if (type == TYPE_WAITING) { builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); } else if (type == TYPE_COMPLETE) { if (Downloads.Impl.isStatusError(info.mStatus)) { builder.setContentText(res.getText(R.string.notification_download_failed)); } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) { builder.setContentText( res.getText(R.string.notification_download_complete)); } } notif = builder.build(); } else { final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder); for (DownloadInfo info : cluster) { inboxStyle.addLine(getDownloadTitle(res, info)); } if (type == TYPE_ACTIVE) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_active, cluster.size(), cluster.size())); builder.setContentText(remainingText); builder.setContentInfo(percentText); inboxStyle.setSummaryText(remainingText); } else if (type == TYPE_WAITING) { builder.setContentTitle(res.getQuantityString( R.plurals.notif_summary_waiting, cluster.size(), cluster.size())); builder.setContentText( res.getString(R.string.notification_need_wifi_for_size)); inboxStyle.setSummaryText( res.getString(R.string.notification_need_wifi_for_size)); } notif = inboxStyle.build(); } mNotifManager.notify(tag, 0, notif); } // Remove stale tags that weren't renewed final Iterator<String> it = mActiveNotifs.keySet().iterator(); while (it.hasNext()) { final String tag = it.next(); if (!clustered.containsKey(tag)) { mNotifManager.cancel(tag, 0); it.remove(); } } }
diff --git a/52n-wps-io/src/main/java/org/n52/wps/io/datahandler/binary/GTBinZippedBase64SHPParser.java b/52n-wps-io/src/main/java/org/n52/wps/io/datahandler/binary/GTBinZippedBase64SHPParser.java index 97fa3af0..d876c455 100644 --- a/52n-wps-io/src/main/java/org/n52/wps/io/datahandler/binary/GTBinZippedBase64SHPParser.java +++ b/52n-wps-io/src/main/java/org/n52/wps/io/datahandler/binary/GTBinZippedBase64SHPParser.java @@ -1,70 +1,66 @@ package org.n52.wps.io.datahandler.binary; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.geotools.data.DataStore; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.feature.FeatureCollection; import org.n52.wps.io.IOHandler; import org.n52.wps.io.IOUtils; import org.n52.wps.io.data.IData; import org.n52.wps.io.data.binding.complex.GTVectorDataBinding; import org.n52.wps.io.datahandler.xml.AbstractXMLParser; import org.w3c.dom.DOMException; import org.xml.sax.SAXException; public class GTBinZippedBase64SHPParser extends AbstractGTBinZippedSHPParser { public GTBinZippedBase64SHPParser() { super(); } /** * @throws RuntimeException * if an error occurs while writing the stream to disk or * unzipping the written file * @see org.n52.wps.io.IParser#parse(java.io.InputStream) */ @Override public IData parse(InputStream input, String mimeType) throws RuntimeException { try { File zipped = IOUtils.writeBase64ToFile(input, "zip"); List<File> shpList = IOUtils.unzip(zipped, "shp"); if (shpList == null || shpList.size()==0) { throw new RuntimeException( "Cannot find a shapefile inside the zipped file."); } File shp = shpList.get(0); - if (shp == null) { - throw new RuntimeException( - "Cannot find a shapefile inside the zipped file."); - } if (shp == null) { throw new RuntimeException( "Cannot find a shapefile inside the zipped file."); } DataStore store = new ShapefileDataStore(shp.toURI().toURL()); FeatureCollection features = store.getFeatureSource( store.getTypeNames()[0]).getFeatures(); zipped.delete(); - shp.delete(); + //shp.delete(); //TODO; workspace concept return new GTVectorDataBinding(features); } catch (IOException e) { throw new RuntimeException( "An error has occurred while accessing provided data", e); } } }
false
true
public IData parse(InputStream input, String mimeType) throws RuntimeException { try { File zipped = IOUtils.writeBase64ToFile(input, "zip"); List<File> shpList = IOUtils.unzip(zipped, "shp"); if (shpList == null || shpList.size()==0) { throw new RuntimeException( "Cannot find a shapefile inside the zipped file."); } File shp = shpList.get(0); if (shp == null) { throw new RuntimeException( "Cannot find a shapefile inside the zipped file."); } if (shp == null) { throw new RuntimeException( "Cannot find a shapefile inside the zipped file."); } DataStore store = new ShapefileDataStore(shp.toURI().toURL()); FeatureCollection features = store.getFeatureSource( store.getTypeNames()[0]).getFeatures(); zipped.delete(); shp.delete(); return new GTVectorDataBinding(features); } catch (IOException e) { throw new RuntimeException( "An error has occurred while accessing provided data", e); } }
public IData parse(InputStream input, String mimeType) throws RuntimeException { try { File zipped = IOUtils.writeBase64ToFile(input, "zip"); List<File> shpList = IOUtils.unzip(zipped, "shp"); if (shpList == null || shpList.size()==0) { throw new RuntimeException( "Cannot find a shapefile inside the zipped file."); } File shp = shpList.get(0); if (shp == null) { throw new RuntimeException( "Cannot find a shapefile inside the zipped file."); } DataStore store = new ShapefileDataStore(shp.toURI().toURL()); FeatureCollection features = store.getFeatureSource( store.getTypeNames()[0]).getFeatures(); zipped.delete(); //shp.delete(); //TODO; workspace concept return new GTVectorDataBinding(features); } catch (IOException e) { throw new RuntimeException( "An error has occurred while accessing provided data", e); } }
diff --git a/trunk/org/xbill/DNS/Address.java b/trunk/org/xbill/DNS/Address.java index de7e4b3..3e0a74f 100644 --- a/trunk/org/xbill/DNS/Address.java +++ b/trunk/org/xbill/DNS/Address.java @@ -1,153 +1,156 @@ // Copyright (c) 1999 Brian Wellington ([email protected]) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.net.*; /** * Routines dealing with IP addresses. Includes functions similar to * those in the java.net.InetAddress class. * * @author Brian Wellington */ public final class Address { private Address() {} /** * Convert a string containing an IP address to an array of 4 integers. * @param s The string * @return The address */ public static int [] toArray(String s) { int numDigits; int currentOctet; int [] values = new int[4]; int length = s.length(); currentOctet = 0; numDigits = 0; for (int i = 0; i < length; i++) { char c = s.charAt(i); if (c >= '0' && c <= '9') { /* Can't have more than 3 digits per octet. */ if (numDigits == 3) return null; + /* Octets shouldn't start with 0, unless they are 0. */ + if (numDigits > 0 && values[currentOctet] == 0) + return null; numDigits++; values[currentOctet] *= 10; values[currentOctet] += (c - '0'); /* 255 is the maximum value for an octet. */ if (values[currentOctet] > 255) return null; } else if (c == '.') { /* Can't have more than 3 dots. */ if (currentOctet == 3) return null; /* Two consecutive dots are bad. */ if (numDigits == 0) return null; currentOctet++; numDigits = 0; } else return null; } /* Must have 4 octets. */ if (currentOctet != 3) return null; /* The fourth octet can't be empty. */ if (numDigits == 0) return null; return values; } /** * Determines if a string contains a valid IP address. * @param s The string * @return Whether the string contains a valid IP address */ public static boolean isDottedQuad(String s) { int [] address = Address.toArray(s); return (address != null); } /** * Converts a byte array containing an IPv4 address into a dotted quad string. * @param addr The byte array * @return The string representation */ public static String toDottedQuad(byte [] addr) { return ((addr[0] & 0xFF) + "." + (addr[1] & 0xFF) + "." + (addr[2] & 0xFF) + "." + (addr[3] & 0xFF)); } private static Record [] lookupHostName(String name) throws UnknownHostException { try { Record [] records = new Lookup(name).run(); if (records == null) throw new UnknownHostException("unknown host"); return records; } catch (TextParseException e) { throw new UnknownHostException("invalid name"); } } /** * Determines the IP address of a host * @param name The hostname to look up * @return The first matching IP address * @exception UnknownHostException The hostname does not have any addresses */ public static InetAddress getByName(String name) throws UnknownHostException { if (isDottedQuad(name)) return InetAddress.getByName(name); Record [] records = lookupHostName(name); ARecord a = (ARecord) records[0]; return a.getAddress(); } /** * Determines all IP address of a host * @param name The hostname to look up * @return All matching IP addresses * @exception UnknownHostException The hostname does not have any addresses */ public static InetAddress [] getAllByName(String name) throws UnknownHostException { if (isDottedQuad(name)) return InetAddress.getAllByName(name); Record [] records = lookupHostName(name); InetAddress [] addrs = new InetAddress[records.length]; for (int i = 0; i < records.length; i++) { ARecord a = (ARecord) records[i]; addrs[i] = a.getAddress(); } return addrs; } /** * Determines the hostname for an address * @param addr The address to look up * @return The associated host name * @exception UnknownHostException There is no hostname for the address */ public static String getHostName(InetAddress addr) throws UnknownHostException { Name name = ReverseMap.fromAddress(addr); Record [] records = new Lookup(name, Type.PTR).run(); if (records == null) throw new UnknownHostException("unknown address"); PTRRecord ptr = (PTRRecord) records[0]; return ptr.getTarget().toString(); } }
true
true
public static int [] toArray(String s) { int numDigits; int currentOctet; int [] values = new int[4]; int length = s.length(); currentOctet = 0; numDigits = 0; for (int i = 0; i < length; i++) { char c = s.charAt(i); if (c >= '0' && c <= '9') { /* Can't have more than 3 digits per octet. */ if (numDigits == 3) return null; numDigits++; values[currentOctet] *= 10; values[currentOctet] += (c - '0'); /* 255 is the maximum value for an octet. */ if (values[currentOctet] > 255) return null; } else if (c == '.') { /* Can't have more than 3 dots. */ if (currentOctet == 3) return null; /* Two consecutive dots are bad. */ if (numDigits == 0) return null; currentOctet++; numDigits = 0; } else return null; } /* Must have 4 octets. */ if (currentOctet != 3) return null; /* The fourth octet can't be empty. */ if (numDigits == 0) return null; return values; }
public static int [] toArray(String s) { int numDigits; int currentOctet; int [] values = new int[4]; int length = s.length(); currentOctet = 0; numDigits = 0; for (int i = 0; i < length; i++) { char c = s.charAt(i); if (c >= '0' && c <= '9') { /* Can't have more than 3 digits per octet. */ if (numDigits == 3) return null; /* Octets shouldn't start with 0, unless they are 0. */ if (numDigits > 0 && values[currentOctet] == 0) return null; numDigits++; values[currentOctet] *= 10; values[currentOctet] += (c - '0'); /* 255 is the maximum value for an octet. */ if (values[currentOctet] > 255) return null; } else if (c == '.') { /* Can't have more than 3 dots. */ if (currentOctet == 3) return null; /* Two consecutive dots are bad. */ if (numDigits == 0) return null; currentOctet++; numDigits = 0; } else return null; } /* Must have 4 octets. */ if (currentOctet != 3) return null; /* The fourth octet can't be empty. */ if (numDigits == 0) return null; return values; }
diff --git a/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java b/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java index 0d9478f2..0f0b4e69 100644 --- a/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java +++ b/src/kg/apc/jmeter/vizualizers/JSettingsPanel.java @@ -1,558 +1,558 @@ package kg.apc.jmeter.vizualizers; import javax.swing.ToolTipManager; import kg.apc.jmeter.charting.GraphPanelChart; /** * * @author Stéphane Hoblingre */ public class JSettingsPanel extends javax.swing.JPanel { private SettingsInterface parent = null; private int originalTooltipDisplayTime = 0; /** Creates new form JSettingsPanel */ public JSettingsPanel(SettingsInterface parent, boolean showTimelineOption, boolean showGradientOption, boolean showCurrentXOption, boolean showFinalZeroingLinesOption, boolean showLimitPointOption, boolean showBarChartXAxisLimit, boolean showHideNonRepValues, boolean showAggregateOption) { initComponents(); this.parent = parent; postInitComponents(showTimelineOption, showGradientOption, showCurrentXOption, showFinalZeroingLinesOption, showLimitPointOption, showBarChartXAxisLimit, showHideNonRepValues, showAggregateOption); } public JSettingsPanel(SettingsInterface parent, boolean showTimelineOption, boolean showGradientOption, boolean showCurrentXOption, boolean showFinalZeroingLinesOption, boolean showLimitPointOption) { this(parent, showTimelineOption, showGradientOption, showCurrentXOption, showFinalZeroingLinesOption, showLimitPointOption, false, false, false); } public JSettingsPanel(SettingsInterface parent, boolean showTimelineOption, boolean showGradientOption, boolean showCurrentXOption, boolean showFinalZeroingLinesOption, boolean showLimitPointOption, boolean showBarChartXAxisLimit) { this(parent, showTimelineOption, showGradientOption, showCurrentXOption, showFinalZeroingLinesOption, showLimitPointOption, showBarChartXAxisLimit, false, false); } private void postInitComponents(boolean showTimelineOption, boolean showGradientOption, boolean showCurrentXOption, boolean showFinalZeroingLinesOption, boolean showLimitPointOption, boolean showBarChartXAxisLimit, boolean showHideNonRepValues, boolean showAggregateOption) { boolean showGraphOptionPanel = showTimelineOption || showAggregateOption; jPanelTimeLine.setVisible(showGraphOptionPanel); jLabelTimeline1.setVisible(showTimelineOption); jLabelTimeline2.setVisible(showTimelineOption); jComboBoxGranulation.setVisible(showTimelineOption); jLabelInfoGrpValues.setVisible(showTimelineOption); jRadioButtonGraphAggregated.setVisible(showAggregateOption); jRadioButtonGraphDetailed.setVisible(showAggregateOption); jLabelGraphType.setVisible(showAggregateOption); jCheckBoxPaintGradient.setVisible(showGradientOption); jCheckBoxDrawCurrentX.setVisible(showCurrentXOption); jCheckBoxDrawFinalZeroingLines.setVisible(showFinalZeroingLinesOption); jCheckBoxMaxPoints.setVisible(showLimitPointOption); jComboBoxMaxPoints.setVisible(showLimitPointOption); jLabelMaxPoints.setVisible(showLimitPointOption); jLabelInfoMaxPoint.setVisible(showLimitPointOption); originalTooltipDisplayTime = ToolTipManager.sharedInstance().getDismissDelay(); //init default values from global config jCheckBoxPaintGradient.setSelected(parent.getGraphPanelChart().isSettingsDrawGradient()); jCheckBoxDrawCurrentX.setSelected(parent.getGraphPanelChart().isSettingsDrawCurrentX()); if (showFinalZeroingLinesOption) { jCheckBoxDrawFinalZeroingLines.setSelected(GraphPanelChart.isGlobalDrawFinalZeroingLines()); } jCheckBoxLimitMaxXValue.setVisible(showBarChartXAxisLimit); jComboBoxHideNonRepValLimit.setVisible(showHideNonRepValues); jCheckBoxHideNonRepValues.setVisible(showHideNonRepValues); jLabelHideNonRepPoints.setVisible(showHideNonRepValues); } private int getValueFromString(String sValue) { int ret; try { ret = Integer.valueOf(sValue); if (ret <= 0) { ret = -1; } } catch (NumberFormatException ex) { ret = -1; } return ret; } public void setAggregateMode(boolean aggregate) { if(aggregate) { jRadioButtonGraphAggregated.setSelected(true); } else { jRadioButtonGraphDetailed.setSelected(true); } } public void setGranulationValue(int value) { jComboBoxGranulation.setSelectedItem(Integer.toString(value)); } /** 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() { java.awt.GridBagConstraints gridBagConstraints; buttonGroupGraphType = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanelTimeLine = new javax.swing.JPanel(); jLabelTimeline1 = new javax.swing.JLabel(); jLabelTimeline2 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jComboBoxGranulation = new javax.swing.JComboBox(); jLabelInfoGrpValues = new javax.swing.JLabel(); jRadioButtonGraphAggregated = new javax.swing.JRadioButton(); jRadioButtonGraphDetailed = new javax.swing.JRadioButton(); jLabelGraphType = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jCheckBoxPaintGradient = new javax.swing.JCheckBox(); jCheckBoxDrawFinalZeroingLines = new javax.swing.JCheckBox(); jPanel6 = new javax.swing.JPanel(); jCheckBoxDrawCurrentX = new javax.swing.JCheckBox(); jCheckBoxMaxPoints = new javax.swing.JCheckBox(); jLabelMaxPoints = new javax.swing.JLabel(); jComboBoxMaxPoints = new javax.swing.JComboBox(); jLabelInfoMaxPoint = new javax.swing.JLabel(); jCheckBoxLimitMaxXValue = new javax.swing.JCheckBox(); jCheckBoxHideNonRepValues = new javax.swing.JCheckBox(); jComboBoxHideNonRepValLimit = new javax.swing.JComboBox(); jLabelHideNonRepPoints = new javax.swing.JLabel(); setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); setLayout(new java.awt.BorderLayout()); jPanel1.setLayout(new java.awt.GridLayout(1, 0)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/logoSimple.png"))); // NOI18N jPanel1.add(jLabel1); add(jPanel1, java.awt.BorderLayout.PAGE_END); jPanel2.setLayout(new java.awt.GridBagLayout()); jPanelTimeLine.setBorder(javax.swing.BorderFactory.createTitledBorder("Graph Settings")); jPanelTimeLine.setLayout(new java.awt.GridBagLayout()); - jLabelTimeline1.setText("Group timeline values for:"); + jLabelTimeline1.setText("Group timeline values for"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelTimeline1, gridBagConstraints); jLabelTimeline2.setText("ms"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelTimeline2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanelTimeLine.add(jPanel4, gridBagConstraints); jComboBoxGranulation.setEditable(true); jComboBoxGranulation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "100", "500", "1000", "2000", "5000", "10000", "30000", "60000" })); jComboBoxGranulation.setPreferredSize(new java.awt.Dimension(80, 20)); jComboBoxGranulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxGranulationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jComboBoxGranulation, gridBagConstraints); jLabelInfoGrpValues.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N jLabelInfoGrpValues.setToolTipText("<html>You can specify here the duration used internally<br>\nby the plugin to combine the values received during<br>\nthe test. This will result in <b>more readable graphs</b> and<br>\n<b>less resources needs</b>. It <b>cannot be undo</b>.<br>\nYou can change the value during the test, but it is not<br>\nrecomended as it may produce inconsistant graphs.<br>\nThis parameter is saved with the test plan."); jLabelInfoGrpValues.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelInfoGrpValues, gridBagConstraints); buttonGroupGraphType.add(jRadioButtonGraphAggregated); jRadioButtonGraphAggregated.setText("Aggregated display, all Samplers combined"); jRadioButtonGraphAggregated.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonGraphAggregatedActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanelTimeLine.add(jRadioButtonGraphAggregated, gridBagConstraints); buttonGroupGraphType.add(jRadioButtonGraphDetailed); jRadioButtonGraphDetailed.setSelected(true); jRadioButtonGraphDetailed.setText("Detailed display, one row per Sampler"); jRadioButtonGraphDetailed.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonGraphDetailedActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanelTimeLine.add(jRadioButtonGraphDetailed, gridBagConstraints); jLabelGraphType.setText("Type of graph:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 4, 2); jPanelTimeLine.add(jLabelGraphType, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel2.add(jPanelTimeLine, gridBagConstraints); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Rendering Options")); jPanel5.setLayout(new java.awt.GridBagLayout()); jCheckBoxPaintGradient.setText("Paint gradient"); jCheckBoxPaintGradient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxPaintGradientActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxPaintGradient, gridBagConstraints); jCheckBoxDrawFinalZeroingLines.setText("Draw final zeroing lines"); jCheckBoxDrawFinalZeroingLines.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawFinalZeroingLinesActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawFinalZeroingLines, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel5.add(jPanel6, gridBagConstraints); jCheckBoxDrawCurrentX.setText("Draw current X line"); jCheckBoxDrawCurrentX.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawCurrentXActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawCurrentX, gridBagConstraints); jCheckBoxMaxPoints.setText("Limit number of points in row to"); jCheckBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxMaxPoints, gridBagConstraints); jLabelMaxPoints.setText("points"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelMaxPoints, gridBagConstraints); jComboBoxMaxPoints.setEditable(true); jComboBoxMaxPoints.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "20", "50", "100", "150", "200" })); jComboBoxMaxPoints.setSelectedIndex(1); jComboBoxMaxPoints.setPreferredSize(new java.awt.Dimension(50, 20)); jComboBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jComboBoxMaxPoints, gridBagConstraints); jLabelInfoMaxPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N jLabelInfoMaxPoint.setToolTipText("<html>This option will <b>dynamically</b> adjust the graph<br>\nrendering so it is <b>more readable</b>. It <b>can be undo</b>.<br>\nYou can change the value during the test.<br>\nThis parameter is not saved with the test plan.<br>"); jLabelInfoMaxPoint.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelInfoMaxPoint, gridBagConstraints); jCheckBoxLimitMaxXValue.setText("Prevent X axis range to adapt to outliers"); jCheckBoxLimitMaxXValue.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxLimitMaxXValueActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxLimitMaxXValue, gridBagConstraints); jCheckBoxHideNonRepValues.setText("Hide non representative points, if count is less or equal than"); jCheckBoxHideNonRepValues.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxHideNonRepValuesActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 4; jPanel5.add(jCheckBoxHideNonRepValues, gridBagConstraints); jComboBoxHideNonRepValLimit.setEditable(true); jComboBoxHideNonRepValLimit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "10", "15", "20", "50", "100" })); jComboBoxHideNonRepValLimit.setPreferredSize(new java.awt.Dimension(50, 20)); jComboBoxHideNonRepValLimit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxHideNonRepValLimitActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jComboBoxHideNonRepValLimit, gridBagConstraints); jLabelHideNonRepPoints.setText("occurences"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0); jPanel5.add(jLabelHideNonRepPoints, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel2.add(jPanel5, gridBagConstraints); add(jPanel2, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void jComboBoxGranulationActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jComboBoxGranulationActionPerformed {//GEN-HEADEREND:event_jComboBoxGranulationActionPerformed //notify parent if value changed and valid int newValue = getValueFromString((String) jComboBoxGranulation.getSelectedItem()); if (newValue != -1 && parent.getGranulation() != newValue) { parent.setGranulation(newValue); } }//GEN-LAST:event_jComboBoxGranulationActionPerformed private void jCheckBoxPaintGradientActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxPaintGradientActionPerformed {//GEN-HEADEREND:event_jCheckBoxPaintGradientActionPerformed parent.getGraphPanelChart().setSettingsDrawGradient(jCheckBoxPaintGradient.isSelected()); }//GEN-LAST:event_jCheckBoxPaintGradientActionPerformed private void jCheckBoxDrawFinalZeroingLinesActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxDrawFinalZeroingLinesActionPerformed {//GEN-HEADEREND:event_jCheckBoxDrawFinalZeroingLinesActionPerformed parent.getGraphPanelChart().setSettingsDrawFinalZeroingLines(jCheckBoxDrawFinalZeroingLines.isSelected()); }//GEN-LAST:event_jCheckBoxDrawFinalZeroingLinesActionPerformed private void jCheckBoxDrawCurrentXActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxDrawCurrentXActionPerformed {//GEN-HEADEREND:event_jCheckBoxDrawCurrentXActionPerformed parent.getGraphPanelChart().setSettingsDrawCurrentX(jCheckBoxDrawCurrentX.isSelected()); }//GEN-LAST:event_jCheckBoxDrawCurrentXActionPerformed private void jCheckBoxMaxPointsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxMaxPointsActionPerformed {//GEN-HEADEREND:event_jCheckBoxMaxPointsActionPerformed if (jCheckBoxMaxPoints.isSelected()) { parent.getGraphPanelChart().setMaxPoints(getValueFromString((String) jComboBoxMaxPoints.getSelectedItem())); } else { parent.getGraphPanelChart().setMaxPoints(-1); } }//GEN-LAST:event_jCheckBoxMaxPointsActionPerformed private void jComboBoxMaxPointsActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jComboBoxMaxPointsActionPerformed {//GEN-HEADEREND:event_jComboBoxMaxPointsActionPerformed if (jCheckBoxMaxPoints.isSelected()) { parent.getGraphPanelChart().setMaxPoints(getValueFromString((String) jComboBoxMaxPoints.getSelectedItem())); } }//GEN-LAST:event_jComboBoxMaxPointsActionPerformed private void infoLabelMouseEntered(java.awt.event.MouseEvent evt)//GEN-FIRST:event_infoLabelMouseEntered {//GEN-HEADEREND:event_infoLabelMouseEntered //increase tooltip display duration ToolTipManager.sharedInstance().setDismissDelay(60000); }//GEN-LAST:event_infoLabelMouseEntered private void infoLabelMouseExited(java.awt.event.MouseEvent evt)//GEN-FIRST:event_infoLabelMouseExited {//GEN-HEADEREND:event_infoLabelMouseExited ToolTipManager.sharedInstance().setDismissDelay(originalTooltipDisplayTime); }//GEN-LAST:event_infoLabelMouseExited private void jCheckBoxLimitMaxXValueActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxLimitMaxXValueActionPerformed {//GEN-HEADEREND:event_jCheckBoxLimitMaxXValueActionPerformed parent.getGraphPanelChart().setPreventXAxisOverScaling(jCheckBoxLimitMaxXValue.isSelected()); }//GEN-LAST:event_jCheckBoxLimitMaxXValueActionPerformed private void jCheckBoxHideNonRepValuesActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jCheckBoxHideNonRepValuesActionPerformed {//GEN-HEADEREND:event_jCheckBoxHideNonRepValuesActionPerformed if (jCheckBoxHideNonRepValues.isSelected()) { parent.getGraphPanelChart().setSettingsHideNonRepValLimit(getValueFromString((String) jComboBoxHideNonRepValLimit.getSelectedItem())); } else { parent.getGraphPanelChart().setSettingsHideNonRepValLimit(-1); } }//GEN-LAST:event_jCheckBoxHideNonRepValuesActionPerformed private void jComboBoxHideNonRepValLimitActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jComboBoxHideNonRepValLimitActionPerformed {//GEN-HEADEREND:event_jComboBoxHideNonRepValLimitActionPerformed if (jCheckBoxHideNonRepValues.isSelected()) { parent.getGraphPanelChart().setSettingsHideNonRepValLimit(getValueFromString((String) jComboBoxHideNonRepValLimit.getSelectedItem())); } }//GEN-LAST:event_jComboBoxHideNonRepValLimitActionPerformed private void jRadioButtonGraphAggregatedActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jRadioButtonGraphAggregatedActionPerformed {//GEN-HEADEREND:event_jRadioButtonGraphAggregatedActionPerformed parent.switchModel(true); }//GEN-LAST:event_jRadioButtonGraphAggregatedActionPerformed private void jRadioButtonGraphDetailedActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jRadioButtonGraphDetailedActionPerformed {//GEN-HEADEREND:event_jRadioButtonGraphDetailedActionPerformed parent.switchModel(false); }//GEN-LAST:event_jRadioButtonGraphDetailedActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroupGraphType; private javax.swing.JCheckBox jCheckBoxDrawCurrentX; private javax.swing.JCheckBox jCheckBoxDrawFinalZeroingLines; private javax.swing.JCheckBox jCheckBoxHideNonRepValues; private javax.swing.JCheckBox jCheckBoxLimitMaxXValue; private javax.swing.JCheckBox jCheckBoxMaxPoints; private javax.swing.JCheckBox jCheckBoxPaintGradient; private javax.swing.JComboBox jComboBoxGranulation; private javax.swing.JComboBox jComboBoxHideNonRepValLimit; private javax.swing.JComboBox jComboBoxMaxPoints; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabelGraphType; private javax.swing.JLabel jLabelHideNonRepPoints; private javax.swing.JLabel jLabelInfoGrpValues; private javax.swing.JLabel jLabelInfoMaxPoint; private javax.swing.JLabel jLabelMaxPoints; private javax.swing.JLabel jLabelTimeline1; private javax.swing.JLabel jLabelTimeline2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanelTimeLine; private javax.swing.JRadioButton jRadioButtonGraphAggregated; private javax.swing.JRadioButton jRadioButtonGraphDetailed; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroupGraphType = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanelTimeLine = new javax.swing.JPanel(); jLabelTimeline1 = new javax.swing.JLabel(); jLabelTimeline2 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jComboBoxGranulation = new javax.swing.JComboBox(); jLabelInfoGrpValues = new javax.swing.JLabel(); jRadioButtonGraphAggregated = new javax.swing.JRadioButton(); jRadioButtonGraphDetailed = new javax.swing.JRadioButton(); jLabelGraphType = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jCheckBoxPaintGradient = new javax.swing.JCheckBox(); jCheckBoxDrawFinalZeroingLines = new javax.swing.JCheckBox(); jPanel6 = new javax.swing.JPanel(); jCheckBoxDrawCurrentX = new javax.swing.JCheckBox(); jCheckBoxMaxPoints = new javax.swing.JCheckBox(); jLabelMaxPoints = new javax.swing.JLabel(); jComboBoxMaxPoints = new javax.swing.JComboBox(); jLabelInfoMaxPoint = new javax.swing.JLabel(); jCheckBoxLimitMaxXValue = new javax.swing.JCheckBox(); jCheckBoxHideNonRepValues = new javax.swing.JCheckBox(); jComboBoxHideNonRepValLimit = new javax.swing.JComboBox(); jLabelHideNonRepPoints = new javax.swing.JLabel(); setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); setLayout(new java.awt.BorderLayout()); jPanel1.setLayout(new java.awt.GridLayout(1, 0)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/logoSimple.png"))); // NOI18N jPanel1.add(jLabel1); add(jPanel1, java.awt.BorderLayout.PAGE_END); jPanel2.setLayout(new java.awt.GridBagLayout()); jPanelTimeLine.setBorder(javax.swing.BorderFactory.createTitledBorder("Graph Settings")); jPanelTimeLine.setLayout(new java.awt.GridBagLayout()); jLabelTimeline1.setText("Group timeline values for:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelTimeline1, gridBagConstraints); jLabelTimeline2.setText("ms"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelTimeline2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanelTimeLine.add(jPanel4, gridBagConstraints); jComboBoxGranulation.setEditable(true); jComboBoxGranulation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "100", "500", "1000", "2000", "5000", "10000", "30000", "60000" })); jComboBoxGranulation.setPreferredSize(new java.awt.Dimension(80, 20)); jComboBoxGranulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxGranulationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jComboBoxGranulation, gridBagConstraints); jLabelInfoGrpValues.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N jLabelInfoGrpValues.setToolTipText("<html>You can specify here the duration used internally<br>\nby the plugin to combine the values received during<br>\nthe test. This will result in <b>more readable graphs</b> and<br>\n<b>less resources needs</b>. It <b>cannot be undo</b>.<br>\nYou can change the value during the test, but it is not<br>\nrecomended as it may produce inconsistant graphs.<br>\nThis parameter is saved with the test plan."); jLabelInfoGrpValues.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelInfoGrpValues, gridBagConstraints); buttonGroupGraphType.add(jRadioButtonGraphAggregated); jRadioButtonGraphAggregated.setText("Aggregated display, all Samplers combined"); jRadioButtonGraphAggregated.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonGraphAggregatedActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanelTimeLine.add(jRadioButtonGraphAggregated, gridBagConstraints); buttonGroupGraphType.add(jRadioButtonGraphDetailed); jRadioButtonGraphDetailed.setSelected(true); jRadioButtonGraphDetailed.setText("Detailed display, one row per Sampler"); jRadioButtonGraphDetailed.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonGraphDetailedActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanelTimeLine.add(jRadioButtonGraphDetailed, gridBagConstraints); jLabelGraphType.setText("Type of graph:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 4, 2); jPanelTimeLine.add(jLabelGraphType, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel2.add(jPanelTimeLine, gridBagConstraints); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Rendering Options")); jPanel5.setLayout(new java.awt.GridBagLayout()); jCheckBoxPaintGradient.setText("Paint gradient"); jCheckBoxPaintGradient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxPaintGradientActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxPaintGradient, gridBagConstraints); jCheckBoxDrawFinalZeroingLines.setText("Draw final zeroing lines"); jCheckBoxDrawFinalZeroingLines.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawFinalZeroingLinesActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawFinalZeroingLines, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel5.add(jPanel6, gridBagConstraints); jCheckBoxDrawCurrentX.setText("Draw current X line"); jCheckBoxDrawCurrentX.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawCurrentXActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawCurrentX, gridBagConstraints); jCheckBoxMaxPoints.setText("Limit number of points in row to"); jCheckBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxMaxPoints, gridBagConstraints); jLabelMaxPoints.setText("points"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelMaxPoints, gridBagConstraints); jComboBoxMaxPoints.setEditable(true); jComboBoxMaxPoints.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "20", "50", "100", "150", "200" })); jComboBoxMaxPoints.setSelectedIndex(1); jComboBoxMaxPoints.setPreferredSize(new java.awt.Dimension(50, 20)); jComboBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jComboBoxMaxPoints, gridBagConstraints); jLabelInfoMaxPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N jLabelInfoMaxPoint.setToolTipText("<html>This option will <b>dynamically</b> adjust the graph<br>\nrendering so it is <b>more readable</b>. It <b>can be undo</b>.<br>\nYou can change the value during the test.<br>\nThis parameter is not saved with the test plan.<br>"); jLabelInfoMaxPoint.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelInfoMaxPoint, gridBagConstraints); jCheckBoxLimitMaxXValue.setText("Prevent X axis range to adapt to outliers"); jCheckBoxLimitMaxXValue.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxLimitMaxXValueActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxLimitMaxXValue, gridBagConstraints); jCheckBoxHideNonRepValues.setText("Hide non representative points, if count is less or equal than"); jCheckBoxHideNonRepValues.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxHideNonRepValuesActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 4; jPanel5.add(jCheckBoxHideNonRepValues, gridBagConstraints); jComboBoxHideNonRepValLimit.setEditable(true); jComboBoxHideNonRepValLimit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "10", "15", "20", "50", "100" })); jComboBoxHideNonRepValLimit.setPreferredSize(new java.awt.Dimension(50, 20)); jComboBoxHideNonRepValLimit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxHideNonRepValLimitActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jComboBoxHideNonRepValLimit, gridBagConstraints); jLabelHideNonRepPoints.setText("occurences"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0); jPanel5.add(jLabelHideNonRepPoints, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel2.add(jPanel5, gridBagConstraints); add(jPanel2, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroupGraphType = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jPanelTimeLine = new javax.swing.JPanel(); jLabelTimeline1 = new javax.swing.JLabel(); jLabelTimeline2 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jComboBoxGranulation = new javax.swing.JComboBox(); jLabelInfoGrpValues = new javax.swing.JLabel(); jRadioButtonGraphAggregated = new javax.swing.JRadioButton(); jRadioButtonGraphDetailed = new javax.swing.JRadioButton(); jLabelGraphType = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); jCheckBoxPaintGradient = new javax.swing.JCheckBox(); jCheckBoxDrawFinalZeroingLines = new javax.swing.JCheckBox(); jPanel6 = new javax.swing.JPanel(); jCheckBoxDrawCurrentX = new javax.swing.JCheckBox(); jCheckBoxMaxPoints = new javax.swing.JCheckBox(); jLabelMaxPoints = new javax.swing.JLabel(); jComboBoxMaxPoints = new javax.swing.JComboBox(); jLabelInfoMaxPoint = new javax.swing.JLabel(); jCheckBoxLimitMaxXValue = new javax.swing.JCheckBox(); jCheckBoxHideNonRepValues = new javax.swing.JCheckBox(); jComboBoxHideNonRepValLimit = new javax.swing.JComboBox(); jLabelHideNonRepPoints = new javax.swing.JLabel(); setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); setLayout(new java.awt.BorderLayout()); jPanel1.setLayout(new java.awt.GridLayout(1, 0)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/logoSimple.png"))); // NOI18N jPanel1.add(jLabel1); add(jPanel1, java.awt.BorderLayout.PAGE_END); jPanel2.setLayout(new java.awt.GridBagLayout()); jPanelTimeLine.setBorder(javax.swing.BorderFactory.createTitledBorder("Graph Settings")); jPanelTimeLine.setLayout(new java.awt.GridBagLayout()); jLabelTimeline1.setText("Group timeline values for"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelTimeline1, gridBagConstraints); jLabelTimeline2.setText("ms"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelTimeline2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanelTimeLine.add(jPanel4, gridBagConstraints); jComboBoxGranulation.setEditable(true); jComboBoxGranulation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "100", "500", "1000", "2000", "5000", "10000", "30000", "60000" })); jComboBoxGranulation.setPreferredSize(new java.awt.Dimension(80, 20)); jComboBoxGranulation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxGranulationActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jComboBoxGranulation, gridBagConstraints); jLabelInfoGrpValues.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N jLabelInfoGrpValues.setToolTipText("<html>You can specify here the duration used internally<br>\nby the plugin to combine the values received during<br>\nthe test. This will result in <b>more readable graphs</b> and<br>\n<b>less resources needs</b>. It <b>cannot be undo</b>.<br>\nYou can change the value during the test, but it is not<br>\nrecomended as it may produce inconsistant graphs.<br>\nThis parameter is saved with the test plan."); jLabelInfoGrpValues.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 8, 2); jPanelTimeLine.add(jLabelInfoGrpValues, gridBagConstraints); buttonGroupGraphType.add(jRadioButtonGraphAggregated); jRadioButtonGraphAggregated.setText("Aggregated display, all Samplers combined"); jRadioButtonGraphAggregated.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonGraphAggregatedActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanelTimeLine.add(jRadioButtonGraphAggregated, gridBagConstraints); buttonGroupGraphType.add(jRadioButtonGraphDetailed); jRadioButtonGraphDetailed.setSelected(true); jRadioButtonGraphDetailed.setText("Detailed display, one row per Sampler"); jRadioButtonGraphDetailed.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButtonGraphDetailedActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanelTimeLine.add(jRadioButtonGraphDetailed, gridBagConstraints); jLabelGraphType.setText("Type of graph:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 4, 2); jPanelTimeLine.add(jLabelGraphType, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel2.add(jPanelTimeLine, gridBagConstraints); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Rendering Options")); jPanel5.setLayout(new java.awt.GridBagLayout()); jCheckBoxPaintGradient.setText("Paint gradient"); jCheckBoxPaintGradient.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxPaintGradientActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxPaintGradient, gridBagConstraints); jCheckBoxDrawFinalZeroingLines.setText("Draw final zeroing lines"); jCheckBoxDrawFinalZeroingLines.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawFinalZeroingLinesActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawFinalZeroingLines, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel5.add(jPanel6, gridBagConstraints); jCheckBoxDrawCurrentX.setText("Draw current X line"); jCheckBoxDrawCurrentX.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxDrawCurrentXActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxDrawCurrentX, gridBagConstraints); jCheckBoxMaxPoints.setText("Limit number of points in row to"); jCheckBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxMaxPoints, gridBagConstraints); jLabelMaxPoints.setText("points"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelMaxPoints, gridBagConstraints); jComboBoxMaxPoints.setEditable(true); jComboBoxMaxPoints.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "20", "50", "100", "150", "200" })); jComboBoxMaxPoints.setSelectedIndex(1); jComboBoxMaxPoints.setPreferredSize(new java.awt.Dimension(50, 20)); jComboBoxMaxPoints.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxMaxPointsActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jComboBoxMaxPoints, gridBagConstraints); jLabelInfoMaxPoint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kg/apc/jmeter/vizualizers/information.png"))); // NOI18N jLabelInfoMaxPoint.setToolTipText("<html>This option will <b>dynamically</b> adjust the graph<br>\nrendering so it is <b>more readable</b>. It <b>can be undo</b>.<br>\nYou can change the value during the test.<br>\nThis parameter is not saved with the test plan.<br>"); jLabelInfoMaxPoint.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { infoLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { infoLabelMouseExited(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jLabelInfoMaxPoint, gridBagConstraints); jCheckBoxLimitMaxXValue.setText("Prevent X axis range to adapt to outliers"); jCheckBoxLimitMaxXValue.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxLimitMaxXValueActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; jPanel5.add(jCheckBoxLimitMaxXValue, gridBagConstraints); jCheckBoxHideNonRepValues.setText("Hide non representative points, if count is less or equal than"); jCheckBoxHideNonRepValues.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBoxHideNonRepValuesActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 4; jPanel5.add(jCheckBoxHideNonRepValues, gridBagConstraints); jComboBoxHideNonRepValLimit.setEditable(true); jComboBoxHideNonRepValLimit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5", "10", "15", "20", "50", "100" })); jComboBoxHideNonRepValLimit.setPreferredSize(new java.awt.Dimension(50, 20)); jComboBoxHideNonRepValLimit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxHideNonRepValLimitActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); jPanel5.add(jComboBoxHideNonRepValLimit, gridBagConstraints); jLabelHideNonRepPoints.setText("occurences"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0); jPanel5.add(jLabelHideNonRepPoints, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel2.add(jPanel5, gridBagConstraints); add(jPanel2, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISGravityCommands.java b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISGravityCommands.java index be955f22b..bff276a06 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISGravityCommands.java +++ b/src/main/java/me/eccentric_nz/TARDIS/commands/TARDISGravityCommands.java @@ -1,152 +1,153 @@ /* * Copyright (C) 2013 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.commands; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.tardischunkgenerator.TARDISChunkGenerator; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.WorldType; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; import org.bukkit.util.StringUtil; /** * Command /tardisgravity [arguments]. * * A dimension is a property of space, extending in a given direction, which, * when combined with other dimensions of width and height and time, make up the * Universe. * * @author eccentric_nz */ public class TARDISGravityCommands implements CommandExecutor, TabCompleter { private TARDIS plugin; private List<String> directions = new ArrayList<String>(); private HashMap<String, Double> gravityDirection = new HashMap<String, Double>(); private final ImmutableList<String> ROOT_SUBS; public TARDISGravityCommands(TARDIS plugin) { this.plugin = plugin; directions.add("down"); directions.add("up"); directions.add("north"); directions.add("west"); directions.add("south"); directions.add("east"); directions.add("remove"); ROOT_SUBS = ImmutableList.copyOf(directions); gravityDirection.put("down", 0D); gravityDirection.put("up", 1D); gravityDirection.put("north", 2D); gravityDirection.put("west", 3D); gravityDirection.put("south", 4D); gravityDirection.put("east", 5D); gravityDirection.put("remove", 6D); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardisarea then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardisgravity")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + "This command can only be run by a player"); return false; } if (!player.hasPermission("tardis.gravity")) { sender.sendMessage(plugin.pluginName + ChatColor.RED + "You do not have permission to use this command!"); return true; } // check they are still in the TARDIS world World world = player.getLocation().getWorld(); String name = world.getName(); ChunkGenerator gen = world.getGenerator(); boolean special = name.contains("TARDIS_TimeVortex") && (world.getWorldType().equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator); if (!name.equals("TARDIS_WORLD_" + player.getName()) && !special) { - player.sendMessage(plugin.pluginName + "You must be in a TARDIS world to make a gravity well!"); + String mess_stub = (name.contains("TARDIS_WORLD_")) ? "your own" : "a"; + player.sendMessage(plugin.pluginName + "You must be in " + mess_stub + " TARDIS world to make a gravity well!"); return true; } if (args.length < 1) { return false; } String dir = args[0].toLowerCase(Locale.ENGLISH); if (directions.contains(dir)) { Double[] values = new Double[3]; values[0] = gravityDirection.get(dir); if (!dir.equals("remove") && !dir.equals("down")) { if (args.length < 2) { return false; } try { values[1] = Double.parseDouble(args[1]); if (values[1] > plugin.getConfig().getDouble("gravity_max_distance")) { player.sendMessage(plugin.pluginName + "That distance is too far!"); return true; } } catch (NumberFormatException e) { player.sendMessage(plugin.pluginName + "Second argument must be a number!"); return false; } } else { values[1] = 0D; } if (args.length == 3) { values[2] = Double.parseDouble(args[2]); if (values[2] > plugin.getConfig().getDouble("gravity_max_velocity")) { player.sendMessage(plugin.pluginName + "That velocity is too fast!"); return true; } } else { values[2] = 0.5D; } plugin.trackGravity.put(player.getName(), values); String message = (dir.equals("remove")) ? "remove it from the database" : "save its position"; player.sendMessage(plugin.pluginName + "Click the wool block to " + message + "."); return true; } } return false; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { if (args.length <= 1) { return partial(args[0], ROOT_SUBS); } return ImmutableList.of(); } private List<String> partial(String token, Collection<String> from) { return StringUtil.copyPartialMatches(token, from, new ArrayList<String>(from.size())); } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardisarea then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardisgravity")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + "This command can only be run by a player"); return false; } if (!player.hasPermission("tardis.gravity")) { sender.sendMessage(plugin.pluginName + ChatColor.RED + "You do not have permission to use this command!"); return true; } // check they are still in the TARDIS world World world = player.getLocation().getWorld(); String name = world.getName(); ChunkGenerator gen = world.getGenerator(); boolean special = name.contains("TARDIS_TimeVortex") && (world.getWorldType().equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator); if (!name.equals("TARDIS_WORLD_" + player.getName()) && !special) { player.sendMessage(plugin.pluginName + "You must be in a TARDIS world to make a gravity well!"); return true; } if (args.length < 1) { return false; } String dir = args[0].toLowerCase(Locale.ENGLISH); if (directions.contains(dir)) { Double[] values = new Double[3]; values[0] = gravityDirection.get(dir); if (!dir.equals("remove") && !dir.equals("down")) { if (args.length < 2) { return false; } try { values[1] = Double.parseDouble(args[1]); if (values[1] > plugin.getConfig().getDouble("gravity_max_distance")) { player.sendMessage(plugin.pluginName + "That distance is too far!"); return true; } } catch (NumberFormatException e) { player.sendMessage(plugin.pluginName + "Second argument must be a number!"); return false; } } else { values[1] = 0D; } if (args.length == 3) { values[2] = Double.parseDouble(args[2]); if (values[2] > plugin.getConfig().getDouble("gravity_max_velocity")) { player.sendMessage(plugin.pluginName + "That velocity is too fast!"); return true; } } else { values[2] = 0.5D; } plugin.trackGravity.put(player.getName(), values); String message = (dir.equals("remove")) ? "remove it from the database" : "save its position"; player.sendMessage(plugin.pluginName + "Click the wool block to " + message + "."); return true; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If the player typed /tardisarea then do the following... // check there is the right number of arguments if (cmd.getName().equalsIgnoreCase("tardisgravity")) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (player == null) { sender.sendMessage(plugin.pluginName + ChatColor.RED + "This command can only be run by a player"); return false; } if (!player.hasPermission("tardis.gravity")) { sender.sendMessage(plugin.pluginName + ChatColor.RED + "You do not have permission to use this command!"); return true; } // check they are still in the TARDIS world World world = player.getLocation().getWorld(); String name = world.getName(); ChunkGenerator gen = world.getGenerator(); boolean special = name.contains("TARDIS_TimeVortex") && (world.getWorldType().equals(WorldType.FLAT) || gen instanceof TARDISChunkGenerator); if (!name.equals("TARDIS_WORLD_" + player.getName()) && !special) { String mess_stub = (name.contains("TARDIS_WORLD_")) ? "your own" : "a"; player.sendMessage(plugin.pluginName + "You must be in " + mess_stub + " TARDIS world to make a gravity well!"); return true; } if (args.length < 1) { return false; } String dir = args[0].toLowerCase(Locale.ENGLISH); if (directions.contains(dir)) { Double[] values = new Double[3]; values[0] = gravityDirection.get(dir); if (!dir.equals("remove") && !dir.equals("down")) { if (args.length < 2) { return false; } try { values[1] = Double.parseDouble(args[1]); if (values[1] > plugin.getConfig().getDouble("gravity_max_distance")) { player.sendMessage(plugin.pluginName + "That distance is too far!"); return true; } } catch (NumberFormatException e) { player.sendMessage(plugin.pluginName + "Second argument must be a number!"); return false; } } else { values[1] = 0D; } if (args.length == 3) { values[2] = Double.parseDouble(args[2]); if (values[2] > plugin.getConfig().getDouble("gravity_max_velocity")) { player.sendMessage(plugin.pluginName + "That velocity is too fast!"); return true; } } else { values[2] = 0.5D; } plugin.trackGravity.put(player.getName(), values); String message = (dir.equals("remove")) ? "remove it from the database" : "save its position"; player.sendMessage(plugin.pluginName + "Click the wool block to " + message + "."); return true; } } return false; }
diff --git a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/xpl/EditorTestHelper.java b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/xpl/EditorTestHelper.java index 22099728d..684cd0e70 100644 --- a/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/xpl/EditorTestHelper.java +++ b/tests/tests/org.jboss.tools.test/src/org/jboss/tools/test/util/xpl/EditorTestHelper.java @@ -1,266 +1,268 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.jboss.tools.test.util.xpl; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.jobs.IJobManager; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IViewReference; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; /** * @since 3.1 */ public class EditorTestHelper { public static final String TEXT_EDITOR_ID= "org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$ public static final String COMPILATION_UNIT_EDITOR_ID= "org.eclipse.jdt.ui.CompilationUnitEditor"; //$NON-NLS-1$ public static final String RESOURCE_PERSPECTIVE_ID= "org.eclipse.ui.resourcePerspective"; //$NON-NLS-1$ public static final String JAVA_PERSPECTIVE_ID= "org.eclipse.jdt.ui.JavaPerspective"; //$NON-NLS-1$ public static final String OUTLINE_VIEW_ID= "org.eclipse.ui.views.ContentOutline"; //$NON-NLS-1$ public static final String PACKAGE_EXPLORER_VIEW_ID= "org.eclipse.jdt.ui.PackageExplorer"; //$NON-NLS-1$ public static final String NAVIGATOR_VIEW_ID= "org.eclipse.ui.views.ResourceNavigator"; //$NON-NLS-1$ public static final String INTRO_VIEW_ID= "org.eclipse.ui.internal.introview"; //$NON-NLS-1$ public static void closeEditor(IEditorPart editor) { IWorkbenchPartSite site; IWorkbenchPage page; if (editor != null && (site= editor.getSite()) != null && (page= site.getPage()) != null) page.closeEditor(editor, false); } public static void closeAllEditors() { IWorkbenchWindow[] windows= PlatformUI.getWorkbench().getWorkbenchWindows(); for (int i= 0; i < windows.length; i++) { IWorkbenchPage[] pages= windows[i].getPages(); for (int j= 0; j < pages.length; j++) { IEditorReference[] editorReferences= pages[j].getEditorReferences(); for (int k= 0; k < editorReferences.length; k++) closeEditor(editorReferences[k].getEditor(false)); } } } /** * Runs the event queue on the current display until it is empty. */ public static void runEventQueue() { IWorkbenchWindow window= getActiveWorkbenchWindow(); if (window != null) runEventQueue(window.getShell()); } public static void runEventQueue(IWorkbenchPart part) { runEventQueue(part.getSite().getShell()); } public static void runEventQueue(Shell shell) { runEventQueue(shell.getDisplay()); } public static void runEventQueue(Display display) { while (display.readAndDispatch()) { // do nothing } } /** * Runs the event queue on the current display and lets it sleep until the * timeout elapses. * * @param millis the timeout in milliseconds */ public static void runEventQueue(long millis) { runEventQueue(getActiveDisplay(), millis); } public static void runEventQueue(IWorkbenchPart part, long millis) { runEventQueue(part.getSite().getShell(), millis); } public static void runEventQueue(Shell shell, long millis) { runEventQueue(shell.getDisplay(), millis); } public static void runEventQueue(Display display, long minTime) { if (display != null) { DisplayHelper.sleep(display, minTime); } else { sleep((int) minTime); } } public static IWorkbenchWindow getActiveWorkbenchWindow() { return PlatformUI.getWorkbench().getActiveWorkbenchWindow(); } public static void forceFocus() { IWorkbenchWindow window= getActiveWorkbenchWindow(); if (window == null) { IWorkbenchWindow[] wbWindows= PlatformUI.getWorkbench().getWorkbenchWindows(); if (wbWindows.length == 0) return; window= wbWindows[0]; } Shell shell= window.getShell(); if (shell != null && !shell.isDisposed()) { shell.forceActive(); shell.forceFocus(); } } public static IWorkbenchPage getActivePage() { IWorkbenchWindow window= getActiveWorkbenchWindow(); return window != null ? window.getActivePage() : null; } public static Display getActiveDisplay() { IWorkbenchWindow window= getActiveWorkbenchWindow(); return window != null ? window.getShell().getDisplay() : null; } public static void joinBackgroundActivities() throws CoreException { // Join Building Logger.global.entering("EditorTestHelper", "joinBackgroundActivities"); //$NON-NLS-1$ //$NON-NLS-2$ Logger.global.finer("join builder"); //$NON-NLS-1$ boolean interrupted= true; - while (interrupted) { - try { - Platform.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); - interrupted= false; - } catch (InterruptedException e) { - interrupted= true; - } - } + // TODO: Block was commented to fix correlation with ValidationJob that leads + // to conflict with ValidationFramework.join() and test hanging forever + // while (interrupted) { + // try { + // Platform.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); + // interrupted= false; + // } catch (InterruptedException e) { + // interrupted= true; + // } + // } // Join jobs joinJobs(0, 10000, 500); Logger.global.exiting("EditorTestHelper", "joinBackgroundActivities"); //$NON-NLS-1$ //$NON-NLS-2$ } public static boolean joinJobs(long minTime, long maxTime, long intervalTime) { Logger.global.entering("EditorTestHelper", "joinJobs"); //$NON-NLS-1$ //$NON-NLS-2$ runEventQueue(minTime); DisplayHelper helper= new DisplayHelper() { public boolean condition() { return allJobsQuiet(); } }; boolean quiet= helper.waitForCondition(getActiveDisplay(), maxTime > 0 ? maxTime : Long.MAX_VALUE, intervalTime); runEventQueue(minTime); Logger.global.exiting("EditorTestHelper", "joinJobs", new Boolean(quiet)); //$NON-NLS-1$ //$NON-NLS-2$ return quiet; } public static void sleep(int intervalTime) { try { Thread.sleep(intervalTime); } catch (InterruptedException e) { e.printStackTrace(); } } public static boolean allJobsQuiet() { IJobManager jobManager= Platform.getJobManager(); Job[] jobs= jobManager.find(null); for (int i= 0; i < jobs.length; i++) { Job job= jobs[i]; int state= job.getState(); if (state == Job.RUNNING || state == Job.WAITING) { Logger.global.finest(job.getName()); return false; } } return true; } public static boolean isViewShown(String viewId) { return getActivePage().findViewReference(viewId) != null; } public static boolean showView(String viewId, boolean show) throws PartInitException { IWorkbenchPage activePage= getActivePage(); IViewReference view= activePage.findViewReference(viewId); boolean shown= view != null; if (shown != show) if (show) activePage.showView(viewId); else activePage.hideView(view); return shown; } public static void bringToTop() { getActiveWorkbenchWindow().getShell().forceActive(); } public static String showPerspective(String perspective) throws WorkbenchException { String shownPerspective= getActivePage().getPerspective().getId(); if (!perspective.equals(shownPerspective)) { IWorkbench workbench= PlatformUI.getWorkbench(); IWorkbenchWindow activeWindow= workbench.getActiveWorkbenchWindow(); workbench.showPerspective(perspective, activeWindow); } return shownPerspective; } public static IFile[] findFiles(IResource resource) throws CoreException { List files= new ArrayList(); findFiles(resource, files); return (IFile[]) files.toArray(new IFile[files.size()]); } private static void findFiles(IResource resource, List files) throws CoreException { if (resource instanceof IFile) { files.add(resource); return; } if (resource instanceof IContainer) { IResource[] resources= ((IContainer) resource).members(); for (int i= 0; i < resources.length; i++) findFiles(resources[i], files); } } }
true
true
public static void joinBackgroundActivities() throws CoreException { // Join Building Logger.global.entering("EditorTestHelper", "joinBackgroundActivities"); //$NON-NLS-1$ //$NON-NLS-2$ Logger.global.finer("join builder"); //$NON-NLS-1$ boolean interrupted= true; while (interrupted) { try { Platform.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); interrupted= false; } catch (InterruptedException e) { interrupted= true; } } // Join jobs joinJobs(0, 10000, 500); Logger.global.exiting("EditorTestHelper", "joinBackgroundActivities"); //$NON-NLS-1$ //$NON-NLS-2$ }
public static void joinBackgroundActivities() throws CoreException { // Join Building Logger.global.entering("EditorTestHelper", "joinBackgroundActivities"); //$NON-NLS-1$ //$NON-NLS-2$ Logger.global.finer("join builder"); //$NON-NLS-1$ boolean interrupted= true; // TODO: Block was commented to fix correlation with ValidationJob that leads // to conflict with ValidationFramework.join() and test hanging forever // while (interrupted) { // try { // Platform.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, null); // interrupted= false; // } catch (InterruptedException e) { // interrupted= true; // } // } // Join jobs joinJobs(0, 10000, 500); Logger.global.exiting("EditorTestHelper", "joinBackgroundActivities"); //$NON-NLS-1$ //$NON-NLS-2$ }
diff --git a/webapp/src/main/java/net/micwin/elysium/view/stats/StatisticsPage.java b/webapp/src/main/java/net/micwin/elysium/view/stats/StatisticsPage.java index 6c9260b..7762f8d 100644 --- a/webapp/src/main/java/net/micwin/elysium/view/stats/StatisticsPage.java +++ b/webapp/src/main/java/net/micwin/elysium/view/stats/StatisticsPage.java @@ -1,161 +1,162 @@ package net.micwin.elysium.view.stats; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.micwin.elysium.dao.DaoManager; import net.micwin.elysium.entities.characters.Avatar; import net.micwin.elysium.entities.characters.User.Role; import net.micwin.elysium.view.BasePage; import net.micwin.elysium.view.ElysiumApplication; import net.micwin.elysium.view.ElysiumWicketModel; import org.apache.wicket.Component; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.RefreshingView; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; public class StatisticsPage extends BasePage { public StatisticsPage() { super(false); } @Override protected void onInitialize() { super.onInitialize(); addToContentBody(createUserCountLabel()); addToContentBody(createStartupTimeLabel()); addToContentBody(new Label("gateCount", Model.of(DaoManager.I.getGatesDao().countEntries()))); addToContentBody(createRankingTable()); } private Component createStartupTimeLabel() { ElysiumApplication app = (ElysiumApplication) getElysiumSession().getApplication(); return new Label("startupTime", Model.of(app.getStartupTime().toString())); } private Component createUserCountLabel() { return new Label("userCount", Model.of(DaoManager.I.getUserDao().countEntries())); } private Component createRankingTable() { List<Avatar> avatars = new LinkedList<Avatar>(); DaoManager.I.getAvatarDao().loadAll(avatars); filterAdmins(avatars); Collections.sort(avatars, new Comparator<Avatar>() { @Override public int compare(Avatar o1, Avatar o2) { if (o1.getPoints() > o2.getPoints()) return -1; if (o1.getPoints() < o2.getPoints()) { return 1; } return 0; } }); // only show the first 10 - if (avatars.size() > 10 && getAvatar().getUser().getRole() != Role.ADMIN) + boolean notAdmin = getAvatar() == null || getAvatar().getUser().getRole() != Role.ADMIN; + if (avatars.size() > 10 && notAdmin) avatars = avatars.subList(0, 9); final List<IModel<Avatar>> modelList = new LinkedList<IModel<Avatar>>(); for (Avatar avatar : avatars) { modelList.add(new ElysiumWicketModel<Avatar>(avatar)); } RefreshingView<Avatar> rankingTable = new RefreshingView<Avatar>("rankingTable") { @Override protected Iterator<IModel<Avatar>> getItemModels() { return modelList.iterator(); } @Override protected void populateItem(Item<Avatar> item) { Avatar avatar = item.getModelObject(); item.add(new Label("name", avatar.getName())); item.add(new Label("points", Model.of(avatar.getPoints()))); item.add(new Label("groupsCount", Model.of(avatar.getNanites().size()))); item.add(new Label("birthDate", Model.of(avatar.getCreationDate().toString()))); Date lastLoginDate = avatar.getUser().getLastLoginDate(); item.add(new Label("lastLogin", Model.of(lastLoginDate != null ? lastLoginDate.toString() : "<unbekannt>"))); item.add(getLeverageLink(avatar, 51)); item.add(getLeverageLink(avatar, 101)); item.add(getResurectLink(avatar)); } }; return rankingTable; } protected Component getLeverageLink(Avatar avatar, final int targetLevel) { String id = "leverage" + targetLevel + "Link"; if (!isAdmin() || avatar.getLevel() > targetLevel) { return createDummyLink(id, false, false); } final ElysiumWicketModel<Avatar> model = ElysiumWicketModel.of(avatar); Link leverageLink = new Link(id) { @Override public void onClick() { getAvatarBPO().leverage(model.getObject(), targetLevel); setResponsePage(StatisticsPage.class); } }; return leverageLink; } protected Component getResurectLink(Avatar avatar) { if (!isAdmin() || getAvatarBPO().isAlive(avatar)) { return createDummyLink("resurrectLink", false, false); } final ElysiumWicketModel<Avatar> model = ElysiumWicketModel.of(avatar); Link resurrectLink = new Link("resurrectLink") { @Override public void onClick() { getAvatarBPO().resurrect(model.getObject()); setResponsePage(StatisticsPage.class); } }; return resurrectLink; } private void filterAdmins(List<Avatar> avatars) { List<Avatar> admins = new LinkedList<Avatar>(); for (Avatar avatar : avatars) { if (avatar.getUser().getRole() == Role.ADMIN) { admins.add(avatar); } } avatars.removeAll(admins); } }
true
true
private Component createRankingTable() { List<Avatar> avatars = new LinkedList<Avatar>(); DaoManager.I.getAvatarDao().loadAll(avatars); filterAdmins(avatars); Collections.sort(avatars, new Comparator<Avatar>() { @Override public int compare(Avatar o1, Avatar o2) { if (o1.getPoints() > o2.getPoints()) return -1; if (o1.getPoints() < o2.getPoints()) { return 1; } return 0; } }); // only show the first 10 if (avatars.size() > 10 && getAvatar().getUser().getRole() != Role.ADMIN) avatars = avatars.subList(0, 9); final List<IModel<Avatar>> modelList = new LinkedList<IModel<Avatar>>(); for (Avatar avatar : avatars) { modelList.add(new ElysiumWicketModel<Avatar>(avatar)); } RefreshingView<Avatar> rankingTable = new RefreshingView<Avatar>("rankingTable") { @Override protected Iterator<IModel<Avatar>> getItemModels() { return modelList.iterator(); } @Override protected void populateItem(Item<Avatar> item) { Avatar avatar = item.getModelObject(); item.add(new Label("name", avatar.getName())); item.add(new Label("points", Model.of(avatar.getPoints()))); item.add(new Label("groupsCount", Model.of(avatar.getNanites().size()))); item.add(new Label("birthDate", Model.of(avatar.getCreationDate().toString()))); Date lastLoginDate = avatar.getUser().getLastLoginDate(); item.add(new Label("lastLogin", Model.of(lastLoginDate != null ? lastLoginDate.toString() : "<unbekannt>"))); item.add(getLeverageLink(avatar, 51)); item.add(getLeverageLink(avatar, 101)); item.add(getResurectLink(avatar)); } }; return rankingTable; }
private Component createRankingTable() { List<Avatar> avatars = new LinkedList<Avatar>(); DaoManager.I.getAvatarDao().loadAll(avatars); filterAdmins(avatars); Collections.sort(avatars, new Comparator<Avatar>() { @Override public int compare(Avatar o1, Avatar o2) { if (o1.getPoints() > o2.getPoints()) return -1; if (o1.getPoints() < o2.getPoints()) { return 1; } return 0; } }); // only show the first 10 boolean notAdmin = getAvatar() == null || getAvatar().getUser().getRole() != Role.ADMIN; if (avatars.size() > 10 && notAdmin) avatars = avatars.subList(0, 9); final List<IModel<Avatar>> modelList = new LinkedList<IModel<Avatar>>(); for (Avatar avatar : avatars) { modelList.add(new ElysiumWicketModel<Avatar>(avatar)); } RefreshingView<Avatar> rankingTable = new RefreshingView<Avatar>("rankingTable") { @Override protected Iterator<IModel<Avatar>> getItemModels() { return modelList.iterator(); } @Override protected void populateItem(Item<Avatar> item) { Avatar avatar = item.getModelObject(); item.add(new Label("name", avatar.getName())); item.add(new Label("points", Model.of(avatar.getPoints()))); item.add(new Label("groupsCount", Model.of(avatar.getNanites().size()))); item.add(new Label("birthDate", Model.of(avatar.getCreationDate().toString()))); Date lastLoginDate = avatar.getUser().getLastLoginDate(); item.add(new Label("lastLogin", Model.of(lastLoginDate != null ? lastLoginDate.toString() : "<unbekannt>"))); item.add(getLeverageLink(avatar, 51)); item.add(getLeverageLink(avatar, 101)); item.add(getResurectLink(avatar)); } }; return rankingTable; }
diff --git a/src/main/java/org/helix/mobile/component/contextmenuitem/ContextMenuItemRenderer.java b/src/main/java/org/helix/mobile/component/contextmenuitem/ContextMenuItemRenderer.java index 097a344e..15323e00 100644 --- a/src/main/java/org/helix/mobile/component/contextmenuitem/ContextMenuItemRenderer.java +++ b/src/main/java/org/helix/mobile/component/contextmenuitem/ContextMenuItemRenderer.java @@ -1,55 +1,55 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.helix.mobile.component.contextmenuitem; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.renderkit.CoreRenderer; /** * * @author shallem */ public class ContextMenuItemRenderer extends CoreRenderer { /*@Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); ContextMenuItem item = (ContextMenuItem) component; writer.startElement("li", item); writer.startElement("a", null); writer.writeAttribute("href", "javascript:void(0);", null); writer.writeAttribute("onclick", item.getOntap(), null); writer.write((String)item.getValue()); }*/ @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); ContextMenuItem item = (ContextMenuItem) component; /*writer.endElement("a"); writer.endElement("li");*/ writer.write("{"); writer.write("'display' : '" + item.getValue() + "'"); writer.write(",'action' : " + item.getOntap()); - writer.write(",'enabled' : " + item.getEnabled()); + writer.write(",'enabled' : " + Boolean.toString(item.isEnabled())); if (item.getGroup() != null) { writer.write(",'group' : '" + item.getGroup() + "'"); } writer.write("}"); } @Override public void encodeChildren(FacesContext context, UIComponent component) throws IOException { //Rendering happens on encodeEnd } @Override public boolean getRendersChildren() { return true; } }
true
true
public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); ContextMenuItem item = (ContextMenuItem) component; /*writer.endElement("a"); writer.endElement("li");*/ writer.write("{"); writer.write("'display' : '" + item.getValue() + "'"); writer.write(",'action' : " + item.getOntap()); writer.write(",'enabled' : " + item.getEnabled()); if (item.getGroup() != null) { writer.write(",'group' : '" + item.getGroup() + "'"); } writer.write("}"); }
public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); ContextMenuItem item = (ContextMenuItem) component; /*writer.endElement("a"); writer.endElement("li");*/ writer.write("{"); writer.write("'display' : '" + item.getValue() + "'"); writer.write(",'action' : " + item.getOntap()); writer.write(",'enabled' : " + Boolean.toString(item.isEnabled())); if (item.getGroup() != null) { writer.write(",'group' : '" + item.getGroup() + "'"); } writer.write("}"); }
diff --git a/src/java/org/apache/http/protocol/HttpRequestExecutor.java b/src/java/org/apache/http/protocol/HttpRequestExecutor.java index b58e1ece8..10fe7d113 100644 --- a/src/java/org/apache/http/protocol/HttpRequestExecutor.java +++ b/src/java/org/apache/http/protocol/HttpRequestExecutor.java @@ -1,457 +1,459 @@ /* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * * Copyright 1999-2006 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.protocol; import java.io.IOException; import java.net.ProtocolException; import org.apache.http.HttpClientConnection; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; /** * Sends HTTP requests and receives the responses. * Takes care of request preprocessing and response postprocessing * by the respective interceptors. * * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a> * * @version $Revision$ * * @since 4.0 */ public class HttpRequestExecutor extends AbstractHttpProcessor { protected static final int WAIT_FOR_CONTINUE_MS = 10000; /** The context holding the default context information. */ protected final HttpContext defaultContext; private HttpParams params = null; private HttpRequestRetryHandler retryhandler = null; /** * Create a new request executor with default context information. * The attributes in the argument context will be made available * in the context used for executing a request. * * @param parentContext the default context information, * or <code>null</code> */ public HttpRequestExecutor(final HttpContext parentContext) { super(); this.defaultContext = new HttpExecutionContext(parentContext); } /** * Create a new request executor. */ public HttpRequestExecutor() { this(null); } /** * Obtain the default context information. * This is not necessarily the same object passed to the constructor, * but the default context information will be available here. * * @return the context holding the default context information */ public final HttpContext getContext() { return this.defaultContext; } /** * Obtain the parameters for executing requests. * * @return the currently installed parameters */ public final HttpParams getParams() { return this.params; } /** * Set new parameters for executing requests. * * @param params the new parameters to use from now on */ public final void setParams(final HttpParams params) { this.params = params; } /** * Obtain the retry handler. * * @return the handler deciding whether a request should be retried */ public final HttpRequestRetryHandler getRetryHandler() { return this.retryhandler; } /** * Set the retry handler. * * @param retryhandler the handler to decide whether a request * should be retried */ public final void setRetryHandler(final HttpRequestRetryHandler retryhandler) { this.retryhandler = retryhandler; } /** * Decide whether a response comes with an entity. * The implementation in this class is based on RFC 2616. * Unknown methods and response codes are supposed to * indicate responses with an entity. * <br/> * Derived executors can override this method to handle * methods and response codes not specified in RFC 2616. * * @param request the request, to obtain the executed method * @param response the response, to obtain the status code */ protected boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) { if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { return false; } int status = response.getStatusLine().getStatusCode(); return status >= HttpStatus.SC_OK && status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT; } /** * Synchronously send a request and obtain the response. * * @param request the request to send. It will be preprocessed. * @param conn the connection over which to send. * The {@link HttpClientConnection#setTargetHost target} * host has to be set before calling this method. * * @return the response to the request, postprocessed * * @throws HttpException in case of a protocol or processing problem * @throws IOException in case of an I/O problem */ public HttpResponse execute( final HttpRequest request, final HttpClientConnection conn) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("Client connection may not be null"); } //@@@ behavior if proxying - set real target or proxy, or both? this.defaultContext.setAttribute(HttpExecutionContext.HTTP_TARGET_HOST, conn.getTargetHost()); this.defaultContext.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn); doPrepareRequest(request, this.defaultContext); this.defaultContext.setAttribute(HttpExecutionContext.HTTP_REQUEST, request); HttpResponse response = null; // loop until the method is successfully processed, the retryHandler // returns false or a non-recoverable exception is thrown for (int execCount = 0; ; execCount++) { try { doEstablishConnection(conn, conn.getTargetHost(), request.getParams()); response = doSendRequest(request, conn, this.defaultContext); if (response == null) { response = doReceiveResponse(request, conn, this.defaultContext); } // exit retry loop break; } catch (IOException ex) { conn.close(); if (this.retryhandler == null) { throw ex; } if (!this.retryhandler.retryRequest(ex, execCount, null)) { throw ex; } } catch (HttpException ex) { conn.close(); throw ex; } catch (RuntimeException ex) { conn.close(); throw ex; } } doFinishResponse(response, this.defaultContext); return response; } /** * Prepare a request for sending. * * @param request the request to prepare * @param context the context for sending the request * * @throws HttpException in case of a protocol or processing problem * @throws IOException in case of an I/O problem */ protected void doPrepareRequest( final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } // link default parameters request.getParams().setDefaults(this.params); preprocessRequest(request, context); } /** * Establish a connection with the target host. * * @param conn the HTTP connection * @param target the target host for the request, or * <code>null</code> to send to the host already * set as the connection target * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ protected void doEstablishConnection( final HttpClientConnection conn, final HttpHost target, final HttpParams params) throws HttpException, IOException { if (conn == null) { throw new IllegalArgumentException("HTTP connection may not be null"); } if (target == null) { throw new IllegalArgumentException("Target host may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } // make sure the connection is open and points to the target host if ((target == null) || target.equals(conn.getTargetHost())) { // host and port ok, check whether connection needs to be opened if (HttpConnectionParams.isStaleCheckingEnabled(params)) { if (conn.isOpen() && conn.isStale()) { conn.close(); } } if (!conn.isOpen()) { conn.open(params); //TODO: Implement secure tunnelling (@@@ HttpRequestExecutor) } } else { // wrong target, point connection to target if (conn.isOpen()) { conn.close(); } conn.setTargetHost(target); conn.open(params); } // if connection points to target else } /** * Send a request over a connection. * This method also handles the expect-continue handshake if necessary. * If it does not have to handle an expect-continue handshake, it will * not use the connection for reading or anything else that depends on * data coming in over the connection. * * @param request the request to send, already * {@link #doPrepareRequest prepared} * @param conn the connection over which to send the request, already * {@link #doEstablishConnection established} * @param context the context for sending the request * * @return a terminal response received as part of an expect-continue * handshake, or * <code>null</code> if the expect-continue handshake is not used * * @throws HttpException in case of a protocol or processing problem * @throws IOException in case of an I/O problem */ protected HttpResponse doSendRequest( final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("HTTP connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpResponse response = null; context.setAttribute(HttpExecutionContext.HTTP_REQ_SENT, Boolean.FALSE); conn.sendRequestHeader(request); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclRequest = (HttpEntityEnclosingRequest) request; // Check for expect-continue handshake. We have to flush the // headers and wait for an 100-continue response to handle it. // If we get a different response, we must not send the entity. boolean sendentity = true; final HttpVersion ver = request.getRequestLine().getHttpVersion(); if (entityEnclRequest.expectContinue() && ver.greaterEquals(HttpVersion.HTTP_1_1)) { conn.flush(); // As suggested by RFC 2616 section 8.2.3, we don't wait for a // 100-continue response forever. On timeout, send the entity. if (conn.isResponseAvailable(WAIT_FOR_CONTINUE_MS)) { response = conn.receiveResponseHeader(request.getParams()); if (canResponseHaveBody(request, response)) { conn.receiveResponseEntity(response); } int status = response.getStatusLine().getStatusCode(); if (status < 200) { //@@@ TODO: is this in line with RFC 2616, 10.1? if (status != HttpStatus.SC_CONTINUE) { throw new ProtocolException( "Unexpected response: " + response.getStatusLine()); } + // discard 100-continue + response = null; } else { sendentity = false; } } } if (sendentity) { conn.sendRequestEntity(entityEnclRequest); } } conn.flush(); context.setAttribute(HttpExecutionContext.HTTP_REQ_SENT, Boolean.TRUE); return response; } /** * Wait for and receive a response. * This method will automatically ignore intermediate responses * with status code 1xx. * * @param request the request for which to obtain the response * @param conn the connection over which the request was sent * @param context the context for receiving the response * * @return the final response, not yet post-processed * * @throws HttpException in case of a protocol or processing problem * @throws IOException in case of an I/O problem */ protected HttpResponse doReceiveResponse( final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("HTTP connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpResponse response = null; int statuscode = 0; while (response == null || statuscode < HttpStatus.SC_OK) { response = conn.receiveResponseHeader(request.getParams()); if (canResponseHaveBody(request, response)) { conn.receiveResponseEntity(response); } statuscode = response.getStatusLine().getStatusCode(); } // while intermediate response return response; } /** * Finish a response. * This includes post-processing of the response object. * It does <i>not</i> read the response entity, if any. * It does <i>not</i> allow for immediate re-use of the * connection over which the response is coming in. * * @param response the response object to finish * @param context the context for post-processing the response * * @throws HttpException in case of a protocol or processing problem * @throws IOException in case of an I/O problem */ protected void doFinishResponse( final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } postprocessResponse(response, context); } } // class HttpRequestExecutor
true
true
protected HttpResponse doSendRequest( final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("HTTP connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpResponse response = null; context.setAttribute(HttpExecutionContext.HTTP_REQ_SENT, Boolean.FALSE); conn.sendRequestHeader(request); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclRequest = (HttpEntityEnclosingRequest) request; // Check for expect-continue handshake. We have to flush the // headers and wait for an 100-continue response to handle it. // If we get a different response, we must not send the entity. boolean sendentity = true; final HttpVersion ver = request.getRequestLine().getHttpVersion(); if (entityEnclRequest.expectContinue() && ver.greaterEquals(HttpVersion.HTTP_1_1)) { conn.flush(); // As suggested by RFC 2616 section 8.2.3, we don't wait for a // 100-continue response forever. On timeout, send the entity. if (conn.isResponseAvailable(WAIT_FOR_CONTINUE_MS)) { response = conn.receiveResponseHeader(request.getParams()); if (canResponseHaveBody(request, response)) { conn.receiveResponseEntity(response); } int status = response.getStatusLine().getStatusCode(); if (status < 200) { //@@@ TODO: is this in line with RFC 2616, 10.1? if (status != HttpStatus.SC_CONTINUE) { throw new ProtocolException( "Unexpected response: " + response.getStatusLine()); } } else { sendentity = false; } } } if (sendentity) { conn.sendRequestEntity(entityEnclRequest); } } conn.flush(); context.setAttribute(HttpExecutionContext.HTTP_REQ_SENT, Boolean.TRUE); return response; }
protected HttpResponse doSendRequest( final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("HTTP connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpResponse response = null; context.setAttribute(HttpExecutionContext.HTTP_REQ_SENT, Boolean.FALSE); conn.sendRequestHeader(request); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclRequest = (HttpEntityEnclosingRequest) request; // Check for expect-continue handshake. We have to flush the // headers and wait for an 100-continue response to handle it. // If we get a different response, we must not send the entity. boolean sendentity = true; final HttpVersion ver = request.getRequestLine().getHttpVersion(); if (entityEnclRequest.expectContinue() && ver.greaterEquals(HttpVersion.HTTP_1_1)) { conn.flush(); // As suggested by RFC 2616 section 8.2.3, we don't wait for a // 100-continue response forever. On timeout, send the entity. if (conn.isResponseAvailable(WAIT_FOR_CONTINUE_MS)) { response = conn.receiveResponseHeader(request.getParams()); if (canResponseHaveBody(request, response)) { conn.receiveResponseEntity(response); } int status = response.getStatusLine().getStatusCode(); if (status < 200) { //@@@ TODO: is this in line with RFC 2616, 10.1? if (status != HttpStatus.SC_CONTINUE) { throw new ProtocolException( "Unexpected response: " + response.getStatusLine()); } // discard 100-continue response = null; } else { sendentity = false; } } } if (sendentity) { conn.sendRequestEntity(entityEnclRequest); } } conn.flush(); context.setAttribute(HttpExecutionContext.HTTP_REQ_SENT, Boolean.TRUE); return response; }
diff --git a/pmd/regress/test/net/sourceforge/pmd/ExcludeLinesTest.java b/pmd/regress/test/net/sourceforge/pmd/ExcludeLinesTest.java index 286772706..a6af69482 100644 --- a/pmd/regress/test/net/sourceforge/pmd/ExcludeLinesTest.java +++ b/pmd/regress/test/net/sourceforge/pmd/ExcludeLinesTest.java @@ -1,82 +1,85 @@ package test.net.sourceforge.pmd; import net.sourceforge.pmd.ExcludeLines; import net.sourceforge.pmd.PMD; import net.sourceforge.pmd.Rule; import test.net.sourceforge.pmd.testframework.RuleTst; import java.io.BufferedReader; import java.io.StringReader; public class ExcludeLinesTest extends RuleTst { public void testExcludeOne() throws Throwable { ExcludeLines e = new ExcludeLines(new StringReader(TEST1)); assertFalse(e.getLinesToExclude().isEmpty()); Integer i = (Integer)e.getLinesToExclude().iterator().next(); assertEquals(3, i.intValue()); } public void testExcludeMultiple() throws Throwable { ExcludeLines e = new ExcludeLines(new StringReader(TEST2)); assertEquals(3, e.getLinesToExclude().size()); assertTrue(e.getLinesToExclude().contains(new Integer(3))); assertTrue(e.getLinesToExclude().contains(new Integer(4))); assertTrue(e.getLinesToExclude().contains(new Integer(5))); } public void testCopyMatches() throws Throwable { ExcludeLines e = new ExcludeLines(new StringReader(TEST1)); BufferedReader br = new BufferedReader(e.getCopyReader()); StringBuffer copyBuffer = new StringBuffer(); String tmp; while ((tmp = br.readLine()) != null) { copyBuffer.append(tmp + PMD.EOL); } copyBuffer.deleteCharAt(copyBuffer.length()-1); + if (PMD.EOL.length() == 2) { + copyBuffer.deleteCharAt(copyBuffer.length()-1); + } assertEquals(TEST1, copyBuffer.toString()); } public void testAlternateMarker() throws Throwable { ExcludeLines e = new ExcludeLines(new StringReader(TEST4), "FOOBAR"); assertFalse(e.getLinesToExclude().isEmpty()); } public void testAcceptance() throws Throwable { Rule rule = findRule("rulesets/unusedcode.xml", "UnusedLocalVariable"); runTestFromString(TEST1, 0, rule); runTestFromString(TEST3, 1, rule); } private static final String TEST1 = "public class Foo {" + PMD.EOL + " void foo() {" + PMD.EOL + " int x; //NOPMD " + PMD.EOL + " } " + PMD.EOL + "}"; private static final String TEST2 = "public class Foo {" + PMD.EOL + " void foo() {" + PMD.EOL + " int x; //NOPMD " + PMD.EOL + " int y; //NOPMD " + PMD.EOL + " int z; //NOPMD " + PMD.EOL + " } " + PMD.EOL + "}"; private static final String TEST3 = "public class Foo {" + PMD.EOL + " void foo() {" + PMD.EOL + " int x;" + PMD.EOL + " } " + PMD.EOL + "}"; private static final String TEST4 = "public class Foo {" + PMD.EOL + " void foo() {" + PMD.EOL + " int x; // FOOBAR" + PMD.EOL + " } " + PMD.EOL + "}"; }
true
true
public void testCopyMatches() throws Throwable { ExcludeLines e = new ExcludeLines(new StringReader(TEST1)); BufferedReader br = new BufferedReader(e.getCopyReader()); StringBuffer copyBuffer = new StringBuffer(); String tmp; while ((tmp = br.readLine()) != null) { copyBuffer.append(tmp + PMD.EOL); } copyBuffer.deleteCharAt(copyBuffer.length()-1); assertEquals(TEST1, copyBuffer.toString()); }
public void testCopyMatches() throws Throwable { ExcludeLines e = new ExcludeLines(new StringReader(TEST1)); BufferedReader br = new BufferedReader(e.getCopyReader()); StringBuffer copyBuffer = new StringBuffer(); String tmp; while ((tmp = br.readLine()) != null) { copyBuffer.append(tmp + PMD.EOL); } copyBuffer.deleteCharAt(copyBuffer.length()-1); if (PMD.EOL.length() == 2) { copyBuffer.deleteCharAt(copyBuffer.length()-1); } assertEquals(TEST1, copyBuffer.toString()); }
diff --git a/Currency/src/info/tregmine/currency/Main.java b/Currency/src/info/tregmine/currency/Main.java index f60647c..d6f0a82 100644 --- a/Currency/src/info/tregmine/currency/Main.java +++ b/Currency/src/info/tregmine/currency/Main.java @@ -1,196 +1,198 @@ package info.tregmine.currency; import java.text.NumberFormat; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import info.tregmine.Tregmine; import info.tregmine.zones.ZonesPlugin; public class Main extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft"); public Tregmine tregmine = null; public ZonesPlugin zones = null; NumberFormat nf = NumberFormat.getNumberInstance(); @Override public void onEnable(){ Plugin test = this.getServer().getPluginManager().getPlugin("Tregmine"); if(this.tregmine == null) { if(test != null) { this.tregmine = ((Tregmine)test); } else { log.info(this.getDescription().getName() + " " + this.getDescription().getVersion() + " - could not find Tregmine"); this.getServer().getPluginManager().disablePlugin(this); } } Plugin zonesTest = this.getServer().getPluginManager().getPlugin("ZonesPlugin"); if(this.zones == null) { if(test != null) { this.zones = ((ZonesPlugin)zonesTest); } else { log.info(this.getDescription().getName() + " " + this.getDescription().getVersion() + " - could not find zones"); this.getServer().getPluginManager().disablePlugin(this); } } getServer().getPluginManager().registerEvents(new CurrencyPlayer(this), this); } @Override public void onDisable(){ } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); if(!(sender instanceof Player)) { return false; } Player player = (Player) sender; info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(player.getName()); if (commandName.matches("wallet") && args.length > 0) { if (args[0].matches("balance")) { Wallet wallet = new Wallet(player); long balance = wallet.balance(); if (balance >= 0) { player.sendMessage("You have " + ChatColor.GOLD + nf.format( balance ) + ChatColor.WHITE + " Tregs" ); } else { player.sendMessage(ChatColor.RED + "You have have no wallet. Contact an administrator." ); } return true; } if (args[0].matches("tell")) { Wallet wallet = new Wallet(player); // ChatColor color = this.tregmine.playerSetting.get(player.getName()).getColor(); long balance = wallet.balance(); if (balance >= 0) { if (!tregminePlayer.isAdmin()) { this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " has " + ChatColor.GOLD + nf.format( balance ) + ChatColor.AQUA + " Tregs." ); } else { player.sendMessage(tregminePlayer.getChatName() + " has " + ChatColor.GOLD + "more" + ChatColor.WHITE + " Tregs than you." ); } } else { this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.RED + " has no wallet. Contact an administrator."); } return true; } if (args[0].matches("donate") && args.length > 2) { int amount; Player to; try { amount = Integer.parseInt(args[2]); } catch (Exception e) { amount = 0; } try { to = this.getServer().matchPlayer(args[1]).get(0); } catch (Exception e) { to = null; } if (to != null && amount > 0) { if (info.tregmine.api.math.Distance.calc2d(player.getLocation(), to.getLocation()) > 5) { player.sendMessage(ChatColor.RED + to.getName() + " is to far away for a wallet transaction, please move closer"); + return true; } info.tregmine.api.TregminePlayer toPlayer = this.tregmine.tregminePlayer.get(to.getName()); Wallet wallet = new Wallet(player); Wallet toWallet = new Wallet(to); long newAmount = wallet.balance() - amount; if (newAmount >= 0) { toWallet.add(amount); wallet.take(amount); player.sendMessage(ChatColor.AQUA + "You donated to " + toPlayer.getChatName() + " " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs."); to.sendMessage(ChatColor.AQUA + "You received " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs from a secret admirer."); this.log.info(amount+ ":TREG_DONATED " + player.getName() + " => " + to.getName()); } else { player.sendMessage(ChatColor.RED + "You cant give more then you have!"); } } return true; } if (args[0].matches("give") && args.length > 2) { int amount; Player to; try { amount = Integer.parseInt(args[2]); } catch (Exception e) { amount = 0; } try { to = this.getServer().matchPlayer(args[1]).get(0); } catch (Exception e) { to = null; } if (to != null && amount > 0) { info.tregmine.api.TregminePlayer toPlayer = this.tregmine.tregminePlayer.get(to.getName()); Wallet wallet = new Wallet(player); Wallet toWallet = new Wallet(to); if (info.tregmine.api.math.Distance.calc2d(player.getLocation(), to.getLocation()) > 5) { player.sendMessage(ChatColor.RED + to.getName() + " is to far away for a wallet transaction, please move closer"); + return true; } long newAmount = wallet.balance() - amount; if (newAmount >= 0) { toWallet.add(amount); wallet.take(amount); player.sendMessage(ChatColor.AQUA + "You gave " + toPlayer.getChatName() + " " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs."); to.sendMessage(ChatColor.AQUA + "You received " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs from " + tregminePlayer.getChatName() + "."); this.log.info(amount+ ":TREG " + player.getName() + " => " + to.getName()); } else { player.sendMessage(ChatColor.RED + "You cant give more then you have!"); } } } return true; } return false; } @Override public void onLoad() { } } //TODO: Add following messages to wallet help /* event.getPlayer().sendMessage("/wallet " + "balance - to see your current balance"); event.getPlayer().sendMessage("/wallet " + "tell - to tell others your current balance"); event.getPlayer().sendMessage("/wallet give <player> <amount> - go give <amount> of tregs"); event.getPlayer().sendMessage("/wallet realtime - see in realtime when you gain or lose treg"); */
false
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); if(!(sender instanceof Player)) { return false; } Player player = (Player) sender; info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(player.getName()); if (commandName.matches("wallet") && args.length > 0) { if (args[0].matches("balance")) { Wallet wallet = new Wallet(player); long balance = wallet.balance(); if (balance >= 0) { player.sendMessage("You have " + ChatColor.GOLD + nf.format( balance ) + ChatColor.WHITE + " Tregs" ); } else { player.sendMessage(ChatColor.RED + "You have have no wallet. Contact an administrator." ); } return true; } if (args[0].matches("tell")) { Wallet wallet = new Wallet(player); // ChatColor color = this.tregmine.playerSetting.get(player.getName()).getColor(); long balance = wallet.balance(); if (balance >= 0) { if (!tregminePlayer.isAdmin()) { this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " has " + ChatColor.GOLD + nf.format( balance ) + ChatColor.AQUA + " Tregs." ); } else { player.sendMessage(tregminePlayer.getChatName() + " has " + ChatColor.GOLD + "more" + ChatColor.WHITE + " Tregs than you." ); } } else { this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.RED + " has no wallet. Contact an administrator."); } return true; } if (args[0].matches("donate") && args.length > 2) { int amount; Player to; try { amount = Integer.parseInt(args[2]); } catch (Exception e) { amount = 0; } try { to = this.getServer().matchPlayer(args[1]).get(0); } catch (Exception e) { to = null; } if (to != null && amount > 0) { if (info.tregmine.api.math.Distance.calc2d(player.getLocation(), to.getLocation()) > 5) { player.sendMessage(ChatColor.RED + to.getName() + " is to far away for a wallet transaction, please move closer"); } info.tregmine.api.TregminePlayer toPlayer = this.tregmine.tregminePlayer.get(to.getName()); Wallet wallet = new Wallet(player); Wallet toWallet = new Wallet(to); long newAmount = wallet.balance() - amount; if (newAmount >= 0) { toWallet.add(amount); wallet.take(amount); player.sendMessage(ChatColor.AQUA + "You donated to " + toPlayer.getChatName() + " " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs."); to.sendMessage(ChatColor.AQUA + "You received " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs from a secret admirer."); this.log.info(amount+ ":TREG_DONATED " + player.getName() + " => " + to.getName()); } else { player.sendMessage(ChatColor.RED + "You cant give more then you have!"); } } return true; } if (args[0].matches("give") && args.length > 2) { int amount; Player to; try { amount = Integer.parseInt(args[2]); } catch (Exception e) { amount = 0; } try { to = this.getServer().matchPlayer(args[1]).get(0); } catch (Exception e) { to = null; } if (to != null && amount > 0) { info.tregmine.api.TregminePlayer toPlayer = this.tregmine.tregminePlayer.get(to.getName()); Wallet wallet = new Wallet(player); Wallet toWallet = new Wallet(to); if (info.tregmine.api.math.Distance.calc2d(player.getLocation(), to.getLocation()) > 5) { player.sendMessage(ChatColor.RED + to.getName() + " is to far away for a wallet transaction, please move closer"); } long newAmount = wallet.balance() - amount; if (newAmount >= 0) { toWallet.add(amount); wallet.take(amount); player.sendMessage(ChatColor.AQUA + "You gave " + toPlayer.getChatName() + " " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs."); to.sendMessage(ChatColor.AQUA + "You received " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs from " + tregminePlayer.getChatName() + "."); this.log.info(amount+ ":TREG " + player.getName() + " => " + to.getName()); } else { player.sendMessage(ChatColor.RED + "You cant give more then you have!"); } } } return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); if(!(sender instanceof Player)) { return false; } Player player = (Player) sender; info.tregmine.api.TregminePlayer tregminePlayer = this.tregmine.tregminePlayer.get(player.getName()); if (commandName.matches("wallet") && args.length > 0) { if (args[0].matches("balance")) { Wallet wallet = new Wallet(player); long balance = wallet.balance(); if (balance >= 0) { player.sendMessage("You have " + ChatColor.GOLD + nf.format( balance ) + ChatColor.WHITE + " Tregs" ); } else { player.sendMessage(ChatColor.RED + "You have have no wallet. Contact an administrator." ); } return true; } if (args[0].matches("tell")) { Wallet wallet = new Wallet(player); // ChatColor color = this.tregmine.playerSetting.get(player.getName()).getColor(); long balance = wallet.balance(); if (balance >= 0) { if (!tregminePlayer.isAdmin()) { this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.AQUA + " has " + ChatColor.GOLD + nf.format( balance ) + ChatColor.AQUA + " Tregs." ); } else { player.sendMessage(tregminePlayer.getChatName() + " has " + ChatColor.GOLD + "more" + ChatColor.WHITE + " Tregs than you." ); } } else { this.getServer().broadcastMessage(tregminePlayer.getChatName() + ChatColor.RED + " has no wallet. Contact an administrator."); } return true; } if (args[0].matches("donate") && args.length > 2) { int amount; Player to; try { amount = Integer.parseInt(args[2]); } catch (Exception e) { amount = 0; } try { to = this.getServer().matchPlayer(args[1]).get(0); } catch (Exception e) { to = null; } if (to != null && amount > 0) { if (info.tregmine.api.math.Distance.calc2d(player.getLocation(), to.getLocation()) > 5) { player.sendMessage(ChatColor.RED + to.getName() + " is to far away for a wallet transaction, please move closer"); return true; } info.tregmine.api.TregminePlayer toPlayer = this.tregmine.tregminePlayer.get(to.getName()); Wallet wallet = new Wallet(player); Wallet toWallet = new Wallet(to); long newAmount = wallet.balance() - amount; if (newAmount >= 0) { toWallet.add(amount); wallet.take(amount); player.sendMessage(ChatColor.AQUA + "You donated to " + toPlayer.getChatName() + " " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs."); to.sendMessage(ChatColor.AQUA + "You received " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs from a secret admirer."); this.log.info(amount+ ":TREG_DONATED " + player.getName() + " => " + to.getName()); } else { player.sendMessage(ChatColor.RED + "You cant give more then you have!"); } } return true; } if (args[0].matches("give") && args.length > 2) { int amount; Player to; try { amount = Integer.parseInt(args[2]); } catch (Exception e) { amount = 0; } try { to = this.getServer().matchPlayer(args[1]).get(0); } catch (Exception e) { to = null; } if (to != null && amount > 0) { info.tregmine.api.TregminePlayer toPlayer = this.tregmine.tregminePlayer.get(to.getName()); Wallet wallet = new Wallet(player); Wallet toWallet = new Wallet(to); if (info.tregmine.api.math.Distance.calc2d(player.getLocation(), to.getLocation()) > 5) { player.sendMessage(ChatColor.RED + to.getName() + " is to far away for a wallet transaction, please move closer"); return true; } long newAmount = wallet.balance() - amount; if (newAmount >= 0) { toWallet.add(amount); wallet.take(amount); player.sendMessage(ChatColor.AQUA + "You gave " + toPlayer.getChatName() + " " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs."); to.sendMessage(ChatColor.AQUA + "You received " + ChatColor.GOLD + this.nf.format( amount ) + ChatColor.AQUA +" Tregs from " + tregminePlayer.getChatName() + "."); this.log.info(amount+ ":TREG " + player.getName() + " => " + to.getName()); } else { player.sendMessage(ChatColor.RED + "You cant give more then you have!"); } } } return true; } return false; }
diff --git a/src/main/java/com/github/gwtbootstrap/datepicker/client/ui/util/LocaleUtil.java b/src/main/java/com/github/gwtbootstrap/datepicker/client/ui/util/LocaleUtil.java index f3240d39e..f1ffd2efe 100644 --- a/src/main/java/com/github/gwtbootstrap/datepicker/client/ui/util/LocaleUtil.java +++ b/src/main/java/com/github/gwtbootstrap/datepicker/client/ui/util/LocaleUtil.java @@ -1,181 +1,182 @@ /* * Copyright 2012 GWT-Bootstrap * * 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.gwtbootstrap.datepicker.client.ui.util; import java.util.ArrayList; import java.util.List; import com.github.gwtbootstrap.client.ui.resources.JavaScriptInjector; import com.github.gwtbootstrap.datepicker.client.ui.resources.Resources; import com.google.gwt.resources.client.TextResource; /** * A utility class to get the User's Browser Locale. * * @author Carlos A Becker * @since 2.0.4.0 */ public class LocaleUtil { private static String locale = null; private static String LANGUAGE = null; private static List<String> loaded = new ArrayList<String>(); public static String getLanguage() { if (LANGUAGE == null) { setupLocale(); } return LANGUAGE; } /** * Get the string of locale based on user's browser configuration. * * @return */ public static String getLocale() { if (locale == null) { locale = getBrowserLocale(); } return locale; } public static TextResource getLocaleJsResource() { String locale = getLocale(); if (locale == null) { return null; } return setupLocale(); } private static final native String getBrowserLocale() /*-{ return $wnd.navigator.userLanguage || $wnd.navigator.language; }-*/; public static final void forceLocale(String locale_) { locale = locale_; TextResource t = setupLocale(); if (!loaded.contains(locale) && t != null) { JavaScriptInjector.inject(t.getText()); } } private static TextResource setupLocale() { Resources r = Resources.RESOURCES; TextResource tr = null; /* Script used to gen the basic if-else block: for a in `ls`; do echo "else if(locale.equals(\"`echo $a | cut -f2 -d.`\")) { tr = r.`echo $a | cut -f2 -d.`(); LANGUAGE = \"`echo $a | cut -f2 -d.`\"; }"; done */ + String locale = getLocale(); if (locale.equals("bg")){ tr = r.bg(); LANGUAGE = "bg"; } else if (locale.equals("br")) { tr = r.br(); LANGUAGE = "br"; } else if (locale.equals("cs")) { tr = r.cs(); LANGUAGE = "cs"; } else if (locale.equals("da")) { tr = r.da(); LANGUAGE = "da"; } else if (locale.equals("de")) { tr = r.de(); LANGUAGE = "de"; } else if (locale.equals("es")) { tr = r.es(); LANGUAGE = "es"; } else if (locale.equals("fi")) { tr = r.fi(); LANGUAGE = "fi"; } else if (locale.equals("fr")) { tr = r.fr(); LANGUAGE = "fr"; } else if (locale.equals("id")) { tr = r.id(); LANGUAGE = "id"; } else if (locale.equals("is")) { tr = r.is(); LANGUAGE = "is"; } else if (locale.equals("it")) { tr = r.it(); LANGUAGE = "it"; } else if (locale.equals("ja")) { tr = r.ja(); LANGUAGE = "ja"; } else if (locale.equals("kr")) { tr = r.kr(); LANGUAGE = "kr"; } else if (locale.equals("lt")) { tr = r.lt(); LANGUAGE = "lt"; } else if (locale.equals("lv")) { tr = r.lv(); LANGUAGE = "lv"; } else if (locale.equals("ms")) { tr = r.ms(); LANGUAGE = "ms"; } else if (locale.equals("nb")) { tr = r.nb(); LANGUAGE = "nb"; } else if (locale.equals("nl")) { tr = r.nl(); LANGUAGE = "nl"; } else if (locale.equals("pl")) { tr = r.pl(); LANGUAGE = "pl"; } else if (locale.equals("pt-BR")) { tr = r.pt_BR(); LANGUAGE = "pt-BR"; } else if (locale.equals("pt")) { tr = r.pt(); LANGUAGE = "pt"; } else if (locale.equals("ru")) { tr = r.ru(); LANGUAGE = "ru"; } else if (locale.equals("sl")) { tr = r.sl(); LANGUAGE = "sl"; } else if (locale.equals("sv")) { tr = r.sv(); LANGUAGE = "sv"; } else if (locale.equals("th")) { tr = r.th(); LANGUAGE = "th"; } else if (locale.equals("tr")) { tr = r.tr(); LANGUAGE = "tr"; } else if (locale.equals("zh-CN")) { tr = r.zh_CN(); LANGUAGE = "zh-TW"; } else if (locale.equals("zh-TW")) { tr = r.zh_TW(); LANGUAGE = "zh-TW"; } else { tr = null; LANGUAGE = "en"; } loaded.add(LANGUAGE); return tr; } }
true
true
private static TextResource setupLocale() { Resources r = Resources.RESOURCES; TextResource tr = null; /* Script used to gen the basic if-else block: for a in `ls`; do echo "else if(locale.equals(\"`echo $a | cut -f2 -d.`\")) { tr = r.`echo $a | cut -f2 -d.`(); LANGUAGE = \"`echo $a | cut -f2 -d.`\"; }"; done */ if (locale.equals("bg")){ tr = r.bg(); LANGUAGE = "bg"; } else if (locale.equals("br")) { tr = r.br(); LANGUAGE = "br"; } else if (locale.equals("cs")) { tr = r.cs(); LANGUAGE = "cs"; } else if (locale.equals("da")) { tr = r.da(); LANGUAGE = "da"; } else if (locale.equals("de")) { tr = r.de(); LANGUAGE = "de"; } else if (locale.equals("es")) { tr = r.es(); LANGUAGE = "es"; } else if (locale.equals("fi")) { tr = r.fi(); LANGUAGE = "fi"; } else if (locale.equals("fr")) { tr = r.fr(); LANGUAGE = "fr"; } else if (locale.equals("id")) { tr = r.id(); LANGUAGE = "id"; } else if (locale.equals("is")) { tr = r.is(); LANGUAGE = "is"; } else if (locale.equals("it")) { tr = r.it(); LANGUAGE = "it"; } else if (locale.equals("ja")) { tr = r.ja(); LANGUAGE = "ja"; } else if (locale.equals("kr")) { tr = r.kr(); LANGUAGE = "kr"; } else if (locale.equals("lt")) { tr = r.lt(); LANGUAGE = "lt"; } else if (locale.equals("lv")) { tr = r.lv(); LANGUAGE = "lv"; } else if (locale.equals("ms")) { tr = r.ms(); LANGUAGE = "ms"; } else if (locale.equals("nb")) { tr = r.nb(); LANGUAGE = "nb"; } else if (locale.equals("nl")) { tr = r.nl(); LANGUAGE = "nl"; } else if (locale.equals("pl")) { tr = r.pl(); LANGUAGE = "pl"; } else if (locale.equals("pt-BR")) { tr = r.pt_BR(); LANGUAGE = "pt-BR"; } else if (locale.equals("pt")) { tr = r.pt(); LANGUAGE = "pt"; } else if (locale.equals("ru")) { tr = r.ru(); LANGUAGE = "ru"; } else if (locale.equals("sl")) { tr = r.sl(); LANGUAGE = "sl"; } else if (locale.equals("sv")) { tr = r.sv(); LANGUAGE = "sv"; } else if (locale.equals("th")) { tr = r.th(); LANGUAGE = "th"; } else if (locale.equals("tr")) { tr = r.tr(); LANGUAGE = "tr"; } else if (locale.equals("zh-CN")) { tr = r.zh_CN(); LANGUAGE = "zh-TW"; } else if (locale.equals("zh-TW")) { tr = r.zh_TW(); LANGUAGE = "zh-TW"; } else { tr = null; LANGUAGE = "en"; } loaded.add(LANGUAGE); return tr; }
private static TextResource setupLocale() { Resources r = Resources.RESOURCES; TextResource tr = null; /* Script used to gen the basic if-else block: for a in `ls`; do echo "else if(locale.equals(\"`echo $a | cut -f2 -d.`\")) { tr = r.`echo $a | cut -f2 -d.`(); LANGUAGE = \"`echo $a | cut -f2 -d.`\"; }"; done */ String locale = getLocale(); if (locale.equals("bg")){ tr = r.bg(); LANGUAGE = "bg"; } else if (locale.equals("br")) { tr = r.br(); LANGUAGE = "br"; } else if (locale.equals("cs")) { tr = r.cs(); LANGUAGE = "cs"; } else if (locale.equals("da")) { tr = r.da(); LANGUAGE = "da"; } else if (locale.equals("de")) { tr = r.de(); LANGUAGE = "de"; } else if (locale.equals("es")) { tr = r.es(); LANGUAGE = "es"; } else if (locale.equals("fi")) { tr = r.fi(); LANGUAGE = "fi"; } else if (locale.equals("fr")) { tr = r.fr(); LANGUAGE = "fr"; } else if (locale.equals("id")) { tr = r.id(); LANGUAGE = "id"; } else if (locale.equals("is")) { tr = r.is(); LANGUAGE = "is"; } else if (locale.equals("it")) { tr = r.it(); LANGUAGE = "it"; } else if (locale.equals("ja")) { tr = r.ja(); LANGUAGE = "ja"; } else if (locale.equals("kr")) { tr = r.kr(); LANGUAGE = "kr"; } else if (locale.equals("lt")) { tr = r.lt(); LANGUAGE = "lt"; } else if (locale.equals("lv")) { tr = r.lv(); LANGUAGE = "lv"; } else if (locale.equals("ms")) { tr = r.ms(); LANGUAGE = "ms"; } else if (locale.equals("nb")) { tr = r.nb(); LANGUAGE = "nb"; } else if (locale.equals("nl")) { tr = r.nl(); LANGUAGE = "nl"; } else if (locale.equals("pl")) { tr = r.pl(); LANGUAGE = "pl"; } else if (locale.equals("pt-BR")) { tr = r.pt_BR(); LANGUAGE = "pt-BR"; } else if (locale.equals("pt")) { tr = r.pt(); LANGUAGE = "pt"; } else if (locale.equals("ru")) { tr = r.ru(); LANGUAGE = "ru"; } else if (locale.equals("sl")) { tr = r.sl(); LANGUAGE = "sl"; } else if (locale.equals("sv")) { tr = r.sv(); LANGUAGE = "sv"; } else if (locale.equals("th")) { tr = r.th(); LANGUAGE = "th"; } else if (locale.equals("tr")) { tr = r.tr(); LANGUAGE = "tr"; } else if (locale.equals("zh-CN")) { tr = r.zh_CN(); LANGUAGE = "zh-TW"; } else if (locale.equals("zh-TW")) { tr = r.zh_TW(); LANGUAGE = "zh-TW"; } else { tr = null; LANGUAGE = "en"; } loaded.add(LANGUAGE); return tr; }
diff --git a/fstcomp/printer/FeaturePrintVisitor.java b/fstcomp/printer/FeaturePrintVisitor.java index c825aed15..95569b1fd 100644 --- a/fstcomp/printer/FeaturePrintVisitor.java +++ b/fstcomp/printer/FeaturePrintVisitor.java @@ -1,90 +1,90 @@ package printer; import java.io.File; import java.util.LinkedList; import de.ovgu.cide.fstgen.ast.FSTNode; import de.ovgu.cide.fstgen.ast.FSTNonTerminal; public class FeaturePrintVisitor { private String workingDir = "."; private String expressionName = "default.expression"; //private File featurePath; //private File folderPath; //private File oldFolderPath; private LinkedList<PrintVisitorInterface> visitors = new LinkedList<PrintVisitorInterface>(); public FeaturePrintVisitor() { } public FeaturePrintVisitor(String workingDir, String expressionName) { this.setWorkingDir(workingDir); this.setExpressionName(expressionName); } public void setWorkingDir(String workingDir) { this.workingDir = workingDir; } public String getWorkingDir() { return workingDir; } public void setExpressionName(String expressionName) { this.expressionName = expressionName; } public String getExpressionName() { return expressionName; } public void registerPrintVisitor(PrintVisitorInterface visitor) { this.visitors.add(visitor); } public void unregisterPrintVisitor(PrintVisitorInterface visitor) { this.visitors.remove(visitor); } public LinkedList<PrintVisitorInterface> getPrintVisitors() { return visitors; } public void visit(FSTNonTerminal root) throws PrintVisitorException { visit(root, null, null, null); } private void visit(FSTNonTerminal nonterminal, File featurePath, File folderPath, File oldFolderPath) throws PrintVisitorException { if(nonterminal != null) { if(nonterminal.getType().equals("Feature")) { StringBuffer sb = new StringBuffer(getExpressionName()); sb.setLength(sb.lastIndexOf(".")); sb.delete(0, sb.lastIndexOf(File.separator) + 1); - featurePath = new File(getWorkingDir() + sb.toString()); + featurePath = new File(getWorkingDir() + File.separator + sb.toString()); featurePath.mkdir(); folderPath = featurePath; for(FSTNode child : nonterminal.getChildren()) { visit((FSTNonTerminal)child, featurePath, folderPath, oldFolderPath); } } else if(nonterminal.getType().equals("Folder")) { oldFolderPath = folderPath; folderPath = new File(folderPath, nonterminal.getName()); folderPath.mkdir(); for(FSTNode child : nonterminal.getChildren()) { visit((FSTNonTerminal)child, featurePath, folderPath, oldFolderPath); } folderPath = oldFolderPath; } else { boolean processed = false; for(PrintVisitorInterface visitor : getPrintVisitors()) { if(visitor.acceptNode(nonterminal)) { visitor.processNode(nonterminal, folderPath); processed = true; } } if(!processed) System.err.println("Nonterminal type not supported: " + nonterminal.getType()); } } } }
true
true
private void visit(FSTNonTerminal nonterminal, File featurePath, File folderPath, File oldFolderPath) throws PrintVisitorException { if(nonterminal != null) { if(nonterminal.getType().equals("Feature")) { StringBuffer sb = new StringBuffer(getExpressionName()); sb.setLength(sb.lastIndexOf(".")); sb.delete(0, sb.lastIndexOf(File.separator) + 1); featurePath = new File(getWorkingDir() + sb.toString()); featurePath.mkdir(); folderPath = featurePath; for(FSTNode child : nonterminal.getChildren()) { visit((FSTNonTerminal)child, featurePath, folderPath, oldFolderPath); } } else if(nonterminal.getType().equals("Folder")) { oldFolderPath = folderPath; folderPath = new File(folderPath, nonterminal.getName()); folderPath.mkdir(); for(FSTNode child : nonterminal.getChildren()) { visit((FSTNonTerminal)child, featurePath, folderPath, oldFolderPath); } folderPath = oldFolderPath; } else { boolean processed = false; for(PrintVisitorInterface visitor : getPrintVisitors()) { if(visitor.acceptNode(nonterminal)) { visitor.processNode(nonterminal, folderPath); processed = true; } } if(!processed) System.err.println("Nonterminal type not supported: " + nonterminal.getType()); } } }
private void visit(FSTNonTerminal nonterminal, File featurePath, File folderPath, File oldFolderPath) throws PrintVisitorException { if(nonterminal != null) { if(nonterminal.getType().equals("Feature")) { StringBuffer sb = new StringBuffer(getExpressionName()); sb.setLength(sb.lastIndexOf(".")); sb.delete(0, sb.lastIndexOf(File.separator) + 1); featurePath = new File(getWorkingDir() + File.separator + sb.toString()); featurePath.mkdir(); folderPath = featurePath; for(FSTNode child : nonterminal.getChildren()) { visit((FSTNonTerminal)child, featurePath, folderPath, oldFolderPath); } } else if(nonterminal.getType().equals("Folder")) { oldFolderPath = folderPath; folderPath = new File(folderPath, nonterminal.getName()); folderPath.mkdir(); for(FSTNode child : nonterminal.getChildren()) { visit((FSTNonTerminal)child, featurePath, folderPath, oldFolderPath); } folderPath = oldFolderPath; } else { boolean processed = false; for(PrintVisitorInterface visitor : getPrintVisitors()) { if(visitor.acceptNode(nonterminal)) { visitor.processNode(nonterminal, folderPath); processed = true; } } if(!processed) System.err.println("Nonterminal type not supported: " + nonterminal.getType()); } } }
diff --git a/samples/domino/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewJavaScriptHandler.java b/samples/domino/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewJavaScriptHandler.java index 4d92e7372..3b9c2150d 100644 --- a/samples/domino/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewJavaScriptHandler.java +++ b/samples/domino/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewJavaScriptHandler.java @@ -1,385 +1,388 @@ package nsf.playground.playground; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringReader; import java.util.Iterator; import java.util.List; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import nsf.playground.beans.DataAccessBean; import nsf.playground.environments.PlaygroundEnvironment; import com.ibm.commons.runtime.util.ParameterProcessor; import com.ibm.commons.runtime.util.UrlUtil; import com.ibm.commons.util.PathUtil; import com.ibm.commons.util.StringUtil; import com.ibm.commons.util.io.ReaderInputStream; import com.ibm.commons.util.io.json.JsonJavaFactory; import com.ibm.commons.util.io.json.JsonJavaObject; import com.ibm.commons.util.io.json.JsonObject; import com.ibm.commons.util.io.json.JsonParser; import com.ibm.sbt.playground.extension.JavaScriptPreviewExtension; import com.ibm.sbt.playground.extension.PlaygroundExtensionFactory; import com.ibm.xsp.extlib.util.ExtLibUtil; import com.ibm.xsp.sbtsdk.servlets.JavaScriptLibraries; public class PreviewJavaScriptHandler extends PreviewHandler { protected static class DominoPlaygroundContext extends JavaScriptPreviewExtension.Context { private PlaygroundEnvironment environment; private Properties properties; private JavaScriptLibraries.JSLibrary jsLibrary; protected DominoPlaygroundContext(PlaygroundEnvironment environment, Properties properties, JavaScriptLibraries.JSLibrary jsLibrary) { this.environment = environment; this.properties = properties; this.jsLibrary = jsLibrary; } @Override public PlaygroundEnvironment getEnvironment() { return environment; } @Override public Properties getProperties() { return properties; } @Override public String getJavaScriptLibrary() { return jsLibrary.getLibType().toString(); } @Override public String getJavaScriptLibraryVersion() { return jsLibrary.getLibVersion(); } } private static final String LAST_REQUEST = "javascriptsnippet.lastrequest"; static class RequestParams implements Serializable { private static final long serialVersionUID = 1L; String sOptions; String html; String js; String css; String properties; public RequestParams(String sOptions, String html, String js, String css, String properties) { this.sOptions = sOptions; this.html = html; this.js = js; this.css = css; this.properties = properties; } } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String sOptions = req.getParameter("fm_options"); String html = req.getParameter("fm_html"); String js = req.getParameter("fm_js"); String css = req.getParameter("fm_css"); String properties = req.getParameter("fm_properties"); RequestParams requestParams = new RequestParams(sOptions,html,js,css,properties); req.getSession().setAttribute(LAST_REQUEST, requestParams); resp.sendRedirect(UrlUtil.getRequestUrl(req)); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestParams requestParams = (RequestParams)req.getSession().getAttribute(LAST_REQUEST); if(requestParams!=null) { execRequest(req, resp, requestParams); } else { PrintWriter pw = resp.getWriter(); pw.println("Social Business Toolkit Playground - JavaScript Snippet Preview Servlet"); pw.flush(); } } protected void execRequest(HttpServletRequest req, HttpServletResponse resp, RequestParams requestParams) throws ServletException, IOException { resp.setContentType("text/html"); String sOptions = requestParams.sOptions; JsonJavaObject options = new JsonJavaObject(); try { options = (JsonJavaObject)JsonParser.fromJson(JsonJavaFactory.instanceEx, sOptions); } catch(Exception ex) {} boolean debug = options.getBoolean("debug"); Properties properties = new Properties(); try { // Pass the properties from the file if(StringUtil.isNotEmpty(requestParams.properties)) { properties.load(new ReaderInputStream(new StringReader(requestParams.properties))); } } catch(Exception ex) {} DataAccessBean dataAccess = DataAccessBean.get(); String envName = options.getString("env"); PlaygroundEnvironment env = dataAccess.getEnvironment(envName); env.prepareEndpoints(); // Push the dynamic parameters to the user session JsonObject p = (JsonObject)options.get("params"); if(p!=null) { for(Iterator<String> it= p.getJsonProperties(); it.hasNext(); ) { String name = it.next(); String value = (String)p.getJsonProperty(name); env.pushSessionParams(name, value); } } String serverUrl = composeServerUrl(req); String dbUrl = composeDatabaseUrl(req,serverUrl); //DojoLibrary dojoLib = DojoLibraryFactory.getDefaultLibrary(); int libIdx = Math.max(0, options.getInt("lib")); JavaScriptLibraries.JSLibrary jsLib = JavaScriptLibraries.LIBRARIES[libIdx]; String jsLibraryPath = jsLib.getLibUrl(); if(libIdx==0) { jsLibraryPath = getDefautLibraryPath(serverUrl); } + if(jsLibraryPath.endsWith("/")) { + jsLibraryPath = jsLibraryPath.substring(0,jsLibraryPath.length()-1); + } DominoPlaygroundContext pgContext = new DominoPlaygroundContext(env, properties, jsLib); List<JavaScriptPreviewExtension> pgExtensions = (List<JavaScriptPreviewExtension>)(List)PlaygroundExtensionFactory.getExtensions(JavaScriptPreviewExtension.class); // Map m = req.getParameterMap(); // for(Object k: m.keySet()) { // Object v = m.get(k); // System.out.println("Key:"+k+", Value:"+StringUtil.toString(v,32)); // } PrintWriter pw = resp.getWriter(); String theme = properties.getProperty("theme"); String bodyTheme = null; pw.println("<!DOCTYPE html>"); pw.println("<html lang=\"en\">"); //pw.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); //pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); pw.println("<head>"); pw.println(" <title>Social Business Playground</title>"); // Extension: head starts for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).headerStart(pgContext,pw); } boolean isDojo = jsLib.getLibType()==JavaScriptLibraries.LibType.DOJO; if(StringUtil.equals(theme, "bootstrap")) { pw.println(" <style type=\"text/css\">"); // pw.println(" @import \""+dojoPath+"dijit/themes/claro/claro.css\";"); // pw.println(" @import \""+dojoPath+"dojo/resources/dojo.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.sbtsdk/bootstrap/css/bootstrap.min.css\";"); pw.println(" </style>"); // bodyTheme = "claro"; } else if( (ExtLibUtil.isXPages853() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneuiv2.1")) { pw.println(" <style type=\"text/css\">"); if(isDojo) { - pw.println(" @import \""+jsLibraryPath+"dijit/themes/claro/claro.css\";"); - pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); - pw.println(" @import \""+jsLibraryPath+"dijit/themes/dijit.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/claro/claro.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/dijit.css\";"); } pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/base/core.css\";"); pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/base/dojo.css\";"); if(isDojo) { pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/defaultTheme/defaultTheme.css\";"); pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/defaultTheme/dojoTheme.css\";"); } pw.println(" </style>"); bodyTheme = "lotusui"; //} else if( (ExtLibUtil.isXPages900() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneui302")) { } else if( (!ExtLibUtil.isXPages853() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneui302")) { pw.println(" <style type=\"text/css\">"); if(isDojo) { - pw.println(" @import \""+jsLibraryPath+"dijit/themes/claro/claro.css\";"); - pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); - pw.println(" @import \""+jsLibraryPath+"dijit/themes/dijit.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/claro/claro.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/dijit.css\";"); } pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/base/core.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/base/dojo.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/defaultTheme/defaultTheme.css\";"); if(isDojo) { pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/defaultTheme/dojoTheme.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/dojoTheme/lotusui30dojo/lotusui30dojo.css\";"); } pw.println(" </style>"); bodyTheme = "lotusui30_body lotusui30_fonts lotusui30 lotusui30dojo"; } else if(StringUtil.equals(theme, "dojo") || StringUtil.equals(theme, "dojo-claro")) { pw.println(" <style type=\"text/css\">"); - pw.println(" @import \""+jsLibraryPath+"dijit/themes/claro/claro.css\";"); - pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/claro/claro.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "claro"; } else if(StringUtil.equals(theme, "dojo-tundra")) { pw.println(" <style type=\"text/css\">"); - pw.println(" @import \""+jsLibraryPath+"dijit/themes/tundra/tundra.css\";"); - pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/tundra/tundra.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "tundra"; } else if(StringUtil.equals(theme, "dojo-soria")) { pw.println(" <style type=\"text/css\">"); - pw.println(" @import \""+jsLibraryPath+"dijit/themes/soria/soria.css\";"); - pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/soria/soria.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "soria"; } else if(StringUtil.equals(theme, "dojo-nihilo")) { pw.println(" <style type=\"text/css\">"); - pw.println(" @import \""+jsLibraryPath+"dijit/themes/nihilo/nihilo.css\";"); - pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dijit/themes/nihilo/nihilo.css\";"); + pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "soria"; } switch(jsLib.getLibType()) { case DOJO: { jsLibraryPath = PathUtil.concat(jsLibraryPath,"/dojo/dojo.js",'/'); pw.println(" <script type=\"text/javascript\">"); pw.println(" dojoConfig = {"); if(jsLib.isAsync()) { pw.println(" async: true,"); } if(debug) { pw.println(" isDebug: true,"); } pw.println(" parseOnLoad: true"); pw.println(" };"); pw.println(" </script>"); pw.println(" <script type=\"text/javascript\" src=\""+jsLibraryPath+"\"></script>"); } break; case JQUERY: { if(true) { String jqueryPath = PathUtil.concat(jsLibraryPath,"/jquery.min",'/'); String jqueryUiPath = PathUtil.concat(jsLibraryPath,"/jquery-ui.min",'/'); //String jqueryUiCssPath = PathUtil.concat(jsLibraryPath,"/themes/base/jquery-ui.css",'/'); String jqueryUiCssPath = "//ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"; pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.sbtsdk/js/libs/require.js\"></script>"); pw.println(" <script type=\"text/javascript\">"); pw.println(" requirejs.config({"); pw.println(" paths: {"); pw.println(" 'jquery' : '"+jqueryPath+"',"); pw.println(" 'jqueryui' : '"+jqueryUiPath+"'"); pw.println(" },"); pw.println(" shim: {"); pw.println(" 'jquery/ui': {"); pw.println(" deps: ['jquery'],"); pw.println(" exports: '$'"); pw.println(" }"); pw.println(" }"); pw.println(" });"); pw.println(" </script>"); pw.println(" <link rel=\"stylesheet\" type=\"text/css\" title=\"Style\" href=\""+jqueryUiCssPath+"\">"); } else { jsLibraryPath = PathUtil.concat(jsLibraryPath,"/jquery.min.js",'/'); pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.sbtsdk/js/libs/require.js\"></script>"); pw.println(" <script type=\"text/javascript\" src=\""+jsLibraryPath+"\"></script>"); } } break; } String libType = jsLib.getLibType().toString(); String libVersion = jsLib.getLibVersion(); pw.print(" <script type=\"text/javascript\" src=\""+composeToolkitUrl(dbUrl)+"?lib="+libType+"&ver="+libVersion); pw.print("&env="); pw.print(envName); pw.println("\"></script>"); //pw.println(" <script type=\"text/javascript\" src=\""+PathUtil.concat(env.getSbt(),"toolkit",'/')+"?ver=1.6.1&\"+(Stringendpoints?endpoints)+"></script>"); EnvParameterProvider prov = new EnvParameterProvider(env); // Text content for simple output String html = "<div id=\"content\"></div>\n"; // Read and process the HTML/JS/CSS // Custom HTML String customHtml = requestParams.html; html = html + ParameterProcessor.process(customHtml, prov); // Hidden progress indicator image html = html + "\n<img id='loading' src='../progressIndicator.gif' style='visibility: hidden'></img>"; // Read an process the JS String js = requestParams.js; js = ParameterProcessor.process(js, prov); // Read and process the CSS String css = requestParams.css; css = ParameterProcessor.process(css, prov); if(StringUtil.isNotEmpty(css)) { String s = " <style>"+css+"</style>"; pw.println(s); } // Script for the dojo parser if(isDojo) { pw.println(" <script>"); pw.println(" require(['dojo/parser']);"); // avoid dojo warning pw.println(" </script>"); } // Add the firebug lite debugging tools if(debug) { pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.extlib/firebug/js/firebug-lite.js\"></script>\n"); } // Extension: head ends for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).headerEnd(pgContext,pw); } pw.println("</head>"); pw.print("<body"); if(StringUtil.isNotEmpty(bodyTheme)) { pw.print(" class=\""); pw.print(bodyTheme); pw.print("\""); } pw.println(">"); pw.print("<div id='_jsErrors'>"); pw.print("</div>"); pw.print("<script type='text/javascript'>"); pw.print(" window.onerror = function(msg, url, linenumber) {"); pw.print(" var d = document.createElement('div');"); pw.print(" d.innerHTML += 'Unhandled error: '+msg.replace('<', '&lt;').replace('>', '&gt;')+'<br> in page: '+url+'<br>at: '+linenumber;"); pw.print(" document.getElementById('_jsErrors').appendChild(d);"); pw.print(" return true;"); pw.print(" }"); pw.print("</script>"); // Extension: body starts for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).bodyStart(pgContext,pw); } pw.println(html); if(StringUtil.isNotEmpty(js)) { String s = "<script>\n" +js +"</script>\n"; pw.println(s); } // Extension: body ends for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).bodyEnd(pgContext,pw); } pw.println("</body>"); pw.println("</html>"); pw.flush(); pw.close(); } }
false
true
protected void execRequest(HttpServletRequest req, HttpServletResponse resp, RequestParams requestParams) throws ServletException, IOException { resp.setContentType("text/html"); String sOptions = requestParams.sOptions; JsonJavaObject options = new JsonJavaObject(); try { options = (JsonJavaObject)JsonParser.fromJson(JsonJavaFactory.instanceEx, sOptions); } catch(Exception ex) {} boolean debug = options.getBoolean("debug"); Properties properties = new Properties(); try { // Pass the properties from the file if(StringUtil.isNotEmpty(requestParams.properties)) { properties.load(new ReaderInputStream(new StringReader(requestParams.properties))); } } catch(Exception ex) {} DataAccessBean dataAccess = DataAccessBean.get(); String envName = options.getString("env"); PlaygroundEnvironment env = dataAccess.getEnvironment(envName); env.prepareEndpoints(); // Push the dynamic parameters to the user session JsonObject p = (JsonObject)options.get("params"); if(p!=null) { for(Iterator<String> it= p.getJsonProperties(); it.hasNext(); ) { String name = it.next(); String value = (String)p.getJsonProperty(name); env.pushSessionParams(name, value); } } String serverUrl = composeServerUrl(req); String dbUrl = composeDatabaseUrl(req,serverUrl); //DojoLibrary dojoLib = DojoLibraryFactory.getDefaultLibrary(); int libIdx = Math.max(0, options.getInt("lib")); JavaScriptLibraries.JSLibrary jsLib = JavaScriptLibraries.LIBRARIES[libIdx]; String jsLibraryPath = jsLib.getLibUrl(); if(libIdx==0) { jsLibraryPath = getDefautLibraryPath(serverUrl); } DominoPlaygroundContext pgContext = new DominoPlaygroundContext(env, properties, jsLib); List<JavaScriptPreviewExtension> pgExtensions = (List<JavaScriptPreviewExtension>)(List)PlaygroundExtensionFactory.getExtensions(JavaScriptPreviewExtension.class); // Map m = req.getParameterMap(); // for(Object k: m.keySet()) { // Object v = m.get(k); // System.out.println("Key:"+k+", Value:"+StringUtil.toString(v,32)); // } PrintWriter pw = resp.getWriter(); String theme = properties.getProperty("theme"); String bodyTheme = null; pw.println("<!DOCTYPE html>"); pw.println("<html lang=\"en\">"); //pw.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); //pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); pw.println("<head>"); pw.println(" <title>Social Business Playground</title>"); // Extension: head starts for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).headerStart(pgContext,pw); } boolean isDojo = jsLib.getLibType()==JavaScriptLibraries.LibType.DOJO; if(StringUtil.equals(theme, "bootstrap")) { pw.println(" <style type=\"text/css\">"); // pw.println(" @import \""+dojoPath+"dijit/themes/claro/claro.css\";"); // pw.println(" @import \""+dojoPath+"dojo/resources/dojo.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.sbtsdk/bootstrap/css/bootstrap.min.css\";"); pw.println(" </style>"); // bodyTheme = "claro"; } else if( (ExtLibUtil.isXPages853() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneuiv2.1")) { pw.println(" <style type=\"text/css\">"); if(isDojo) { pw.println(" @import \""+jsLibraryPath+"dijit/themes/claro/claro.css\";"); pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); pw.println(" @import \""+jsLibraryPath+"dijit/themes/dijit.css\";"); } pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/base/core.css\";"); pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/base/dojo.css\";"); if(isDojo) { pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/defaultTheme/defaultTheme.css\";"); pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/defaultTheme/dojoTheme.css\";"); } pw.println(" </style>"); bodyTheme = "lotusui"; //} else if( (ExtLibUtil.isXPages900() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneui302")) { } else if( (!ExtLibUtil.isXPages853() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneui302")) { pw.println(" <style type=\"text/css\">"); if(isDojo) { pw.println(" @import \""+jsLibraryPath+"dijit/themes/claro/claro.css\";"); pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); pw.println(" @import \""+jsLibraryPath+"dijit/themes/dijit.css\";"); } pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/base/core.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/base/dojo.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/defaultTheme/defaultTheme.css\";"); if(isDojo) { pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/defaultTheme/dojoTheme.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/dojoTheme/lotusui30dojo/lotusui30dojo.css\";"); } pw.println(" </style>"); bodyTheme = "lotusui30_body lotusui30_fonts lotusui30 lotusui30dojo"; } else if(StringUtil.equals(theme, "dojo") || StringUtil.equals(theme, "dojo-claro")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"dijit/themes/claro/claro.css\";"); pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "claro"; } else if(StringUtil.equals(theme, "dojo-tundra")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"dijit/themes/tundra/tundra.css\";"); pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "tundra"; } else if(StringUtil.equals(theme, "dojo-soria")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"dijit/themes/soria/soria.css\";"); pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "soria"; } else if(StringUtil.equals(theme, "dojo-nihilo")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"dijit/themes/nihilo/nihilo.css\";"); pw.println(" @import \""+jsLibraryPath+"dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "soria"; } switch(jsLib.getLibType()) { case DOJO: { jsLibraryPath = PathUtil.concat(jsLibraryPath,"/dojo/dojo.js",'/'); pw.println(" <script type=\"text/javascript\">"); pw.println(" dojoConfig = {"); if(jsLib.isAsync()) { pw.println(" async: true,"); } if(debug) { pw.println(" isDebug: true,"); } pw.println(" parseOnLoad: true"); pw.println(" };"); pw.println(" </script>"); pw.println(" <script type=\"text/javascript\" src=\""+jsLibraryPath+"\"></script>"); } break; case JQUERY: { if(true) { String jqueryPath = PathUtil.concat(jsLibraryPath,"/jquery.min",'/'); String jqueryUiPath = PathUtil.concat(jsLibraryPath,"/jquery-ui.min",'/'); //String jqueryUiCssPath = PathUtil.concat(jsLibraryPath,"/themes/base/jquery-ui.css",'/'); String jqueryUiCssPath = "//ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"; pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.sbtsdk/js/libs/require.js\"></script>"); pw.println(" <script type=\"text/javascript\">"); pw.println(" requirejs.config({"); pw.println(" paths: {"); pw.println(" 'jquery' : '"+jqueryPath+"',"); pw.println(" 'jqueryui' : '"+jqueryUiPath+"'"); pw.println(" },"); pw.println(" shim: {"); pw.println(" 'jquery/ui': {"); pw.println(" deps: ['jquery'],"); pw.println(" exports: '$'"); pw.println(" }"); pw.println(" }"); pw.println(" });"); pw.println(" </script>"); pw.println(" <link rel=\"stylesheet\" type=\"text/css\" title=\"Style\" href=\""+jqueryUiCssPath+"\">"); } else { jsLibraryPath = PathUtil.concat(jsLibraryPath,"/jquery.min.js",'/'); pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.sbtsdk/js/libs/require.js\"></script>"); pw.println(" <script type=\"text/javascript\" src=\""+jsLibraryPath+"\"></script>"); } } break; } String libType = jsLib.getLibType().toString(); String libVersion = jsLib.getLibVersion(); pw.print(" <script type=\"text/javascript\" src=\""+composeToolkitUrl(dbUrl)+"?lib="+libType+"&ver="+libVersion); pw.print("&env="); pw.print(envName); pw.println("\"></script>"); //pw.println(" <script type=\"text/javascript\" src=\""+PathUtil.concat(env.getSbt(),"toolkit",'/')+"?ver=1.6.1&\"+(Stringendpoints?endpoints)+"></script>"); EnvParameterProvider prov = new EnvParameterProvider(env); // Text content for simple output String html = "<div id=\"content\"></div>\n"; // Read and process the HTML/JS/CSS // Custom HTML String customHtml = requestParams.html; html = html + ParameterProcessor.process(customHtml, prov); // Hidden progress indicator image html = html + "\n<img id='loading' src='../progressIndicator.gif' style='visibility: hidden'></img>"; // Read an process the JS String js = requestParams.js; js = ParameterProcessor.process(js, prov); // Read and process the CSS String css = requestParams.css; css = ParameterProcessor.process(css, prov); if(StringUtil.isNotEmpty(css)) { String s = " <style>"+css+"</style>"; pw.println(s); } // Script for the dojo parser if(isDojo) { pw.println(" <script>"); pw.println(" require(['dojo/parser']);"); // avoid dojo warning pw.println(" </script>"); } // Add the firebug lite debugging tools if(debug) { pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.extlib/firebug/js/firebug-lite.js\"></script>\n"); } // Extension: head ends for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).headerEnd(pgContext,pw); } pw.println("</head>"); pw.print("<body"); if(StringUtil.isNotEmpty(bodyTheme)) { pw.print(" class=\""); pw.print(bodyTheme); pw.print("\""); } pw.println(">"); pw.print("<div id='_jsErrors'>"); pw.print("</div>"); pw.print("<script type='text/javascript'>"); pw.print(" window.onerror = function(msg, url, linenumber) {"); pw.print(" var d = document.createElement('div');"); pw.print(" d.innerHTML += 'Unhandled error: '+msg.replace('<', '&lt;').replace('>', '&gt;')+'<br> in page: '+url+'<br>at: '+linenumber;"); pw.print(" document.getElementById('_jsErrors').appendChild(d);"); pw.print(" return true;"); pw.print(" }"); pw.print("</script>"); // Extension: body starts for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).bodyStart(pgContext,pw); } pw.println(html); if(StringUtil.isNotEmpty(js)) { String s = "<script>\n" +js +"</script>\n"; pw.println(s); } // Extension: body ends for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).bodyEnd(pgContext,pw); } pw.println("</body>"); pw.println("</html>"); pw.flush(); pw.close(); }
protected void execRequest(HttpServletRequest req, HttpServletResponse resp, RequestParams requestParams) throws ServletException, IOException { resp.setContentType("text/html"); String sOptions = requestParams.sOptions; JsonJavaObject options = new JsonJavaObject(); try { options = (JsonJavaObject)JsonParser.fromJson(JsonJavaFactory.instanceEx, sOptions); } catch(Exception ex) {} boolean debug = options.getBoolean("debug"); Properties properties = new Properties(); try { // Pass the properties from the file if(StringUtil.isNotEmpty(requestParams.properties)) { properties.load(new ReaderInputStream(new StringReader(requestParams.properties))); } } catch(Exception ex) {} DataAccessBean dataAccess = DataAccessBean.get(); String envName = options.getString("env"); PlaygroundEnvironment env = dataAccess.getEnvironment(envName); env.prepareEndpoints(); // Push the dynamic parameters to the user session JsonObject p = (JsonObject)options.get("params"); if(p!=null) { for(Iterator<String> it= p.getJsonProperties(); it.hasNext(); ) { String name = it.next(); String value = (String)p.getJsonProperty(name); env.pushSessionParams(name, value); } } String serverUrl = composeServerUrl(req); String dbUrl = composeDatabaseUrl(req,serverUrl); //DojoLibrary dojoLib = DojoLibraryFactory.getDefaultLibrary(); int libIdx = Math.max(0, options.getInt("lib")); JavaScriptLibraries.JSLibrary jsLib = JavaScriptLibraries.LIBRARIES[libIdx]; String jsLibraryPath = jsLib.getLibUrl(); if(libIdx==0) { jsLibraryPath = getDefautLibraryPath(serverUrl); } if(jsLibraryPath.endsWith("/")) { jsLibraryPath = jsLibraryPath.substring(0,jsLibraryPath.length()-1); } DominoPlaygroundContext pgContext = new DominoPlaygroundContext(env, properties, jsLib); List<JavaScriptPreviewExtension> pgExtensions = (List<JavaScriptPreviewExtension>)(List)PlaygroundExtensionFactory.getExtensions(JavaScriptPreviewExtension.class); // Map m = req.getParameterMap(); // for(Object k: m.keySet()) { // Object v = m.get(k); // System.out.println("Key:"+k+", Value:"+StringUtil.toString(v,32)); // } PrintWriter pw = resp.getWriter(); String theme = properties.getProperty("theme"); String bodyTheme = null; pw.println("<!DOCTYPE html>"); pw.println("<html lang=\"en\">"); //pw.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); //pw.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); pw.println("<head>"); pw.println(" <title>Social Business Playground</title>"); // Extension: head starts for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).headerStart(pgContext,pw); } boolean isDojo = jsLib.getLibType()==JavaScriptLibraries.LibType.DOJO; if(StringUtil.equals(theme, "bootstrap")) { pw.println(" <style type=\"text/css\">"); // pw.println(" @import \""+dojoPath+"dijit/themes/claro/claro.css\";"); // pw.println(" @import \""+dojoPath+"dojo/resources/dojo.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.sbtsdk/bootstrap/css/bootstrap.min.css\";"); pw.println(" </style>"); // bodyTheme = "claro"; } else if( (ExtLibUtil.isXPages853() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneuiv2.1")) { pw.println(" <style type=\"text/css\">"); if(isDojo) { pw.println(" @import \""+jsLibraryPath+"/dijit/themes/claro/claro.css\";"); pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" @import \""+jsLibraryPath+"/dijit/themes/dijit.css\";"); } pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/base/core.css\";"); pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/base/dojo.css\";"); if(isDojo) { pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/defaultTheme/defaultTheme.css\";"); pw.println(" @import \"/xsp/.ibmxspres/domino/oneuiv2.1/defaultTheme/dojoTheme.css\";"); } pw.println(" </style>"); bodyTheme = "lotusui"; //} else if( (ExtLibUtil.isXPages900() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneui302")) { } else if( (!ExtLibUtil.isXPages853() && StringUtil.equals(theme, "oneui")) || StringUtil.equals(theme, "oneui302")) { pw.println(" <style type=\"text/css\">"); if(isDojo) { pw.println(" @import \""+jsLibraryPath+"/dijit/themes/claro/claro.css\";"); pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" @import \""+jsLibraryPath+"/dijit/themes/dijit.css\";"); } pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/base/core.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/base/dojo.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/defaultTheme/defaultTheme.css\";"); if(isDojo) { pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/css/defaultTheme/dojoTheme.css\";"); pw.println(" @import \"/xsp/.ibmxspres/.oneuiv302/oneui/dojoTheme/lotusui30dojo/lotusui30dojo.css\";"); } pw.println(" </style>"); bodyTheme = "lotusui30_body lotusui30_fonts lotusui30 lotusui30dojo"; } else if(StringUtil.equals(theme, "dojo") || StringUtil.equals(theme, "dojo-claro")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"/dijit/themes/claro/claro.css\";"); pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "claro"; } else if(StringUtil.equals(theme, "dojo-tundra")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"/dijit/themes/tundra/tundra.css\";"); pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "tundra"; } else if(StringUtil.equals(theme, "dojo-soria")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"/dijit/themes/soria/soria.css\";"); pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "soria"; } else if(StringUtil.equals(theme, "dojo-nihilo")) { pw.println(" <style type=\"text/css\">"); pw.println(" @import \""+jsLibraryPath+"/dijit/themes/nihilo/nihilo.css\";"); pw.println(" @import \""+jsLibraryPath+"/dojo/resources/dojo.css\";"); pw.println(" </style>"); bodyTheme = "soria"; } switch(jsLib.getLibType()) { case DOJO: { jsLibraryPath = PathUtil.concat(jsLibraryPath,"/dojo/dojo.js",'/'); pw.println(" <script type=\"text/javascript\">"); pw.println(" dojoConfig = {"); if(jsLib.isAsync()) { pw.println(" async: true,"); } if(debug) { pw.println(" isDebug: true,"); } pw.println(" parseOnLoad: true"); pw.println(" };"); pw.println(" </script>"); pw.println(" <script type=\"text/javascript\" src=\""+jsLibraryPath+"\"></script>"); } break; case JQUERY: { if(true) { String jqueryPath = PathUtil.concat(jsLibraryPath,"/jquery.min",'/'); String jqueryUiPath = PathUtil.concat(jsLibraryPath,"/jquery-ui.min",'/'); //String jqueryUiCssPath = PathUtil.concat(jsLibraryPath,"/themes/base/jquery-ui.css",'/'); String jqueryUiCssPath = "//ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"; pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.sbtsdk/js/libs/require.js\"></script>"); pw.println(" <script type=\"text/javascript\">"); pw.println(" requirejs.config({"); pw.println(" paths: {"); pw.println(" 'jquery' : '"+jqueryPath+"',"); pw.println(" 'jqueryui' : '"+jqueryUiPath+"'"); pw.println(" },"); pw.println(" shim: {"); pw.println(" 'jquery/ui': {"); pw.println(" deps: ['jquery'],"); pw.println(" exports: '$'"); pw.println(" }"); pw.println(" }"); pw.println(" });"); pw.println(" </script>"); pw.println(" <link rel=\"stylesheet\" type=\"text/css\" title=\"Style\" href=\""+jqueryUiCssPath+"\">"); } else { jsLibraryPath = PathUtil.concat(jsLibraryPath,"/jquery.min.js",'/'); pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.sbtsdk/js/libs/require.js\"></script>"); pw.println(" <script type=\"text/javascript\" src=\""+jsLibraryPath+"\"></script>"); } } break; } String libType = jsLib.getLibType().toString(); String libVersion = jsLib.getLibVersion(); pw.print(" <script type=\"text/javascript\" src=\""+composeToolkitUrl(dbUrl)+"?lib="+libType+"&ver="+libVersion); pw.print("&env="); pw.print(envName); pw.println("\"></script>"); //pw.println(" <script type=\"text/javascript\" src=\""+PathUtil.concat(env.getSbt(),"toolkit",'/')+"?ver=1.6.1&\"+(Stringendpoints?endpoints)+"></script>"); EnvParameterProvider prov = new EnvParameterProvider(env); // Text content for simple output String html = "<div id=\"content\"></div>\n"; // Read and process the HTML/JS/CSS // Custom HTML String customHtml = requestParams.html; html = html + ParameterProcessor.process(customHtml, prov); // Hidden progress indicator image html = html + "\n<img id='loading' src='../progressIndicator.gif' style='visibility: hidden'></img>"; // Read an process the JS String js = requestParams.js; js = ParameterProcessor.process(js, prov); // Read and process the CSS String css = requestParams.css; css = ParameterProcessor.process(css, prov); if(StringUtil.isNotEmpty(css)) { String s = " <style>"+css+"</style>"; pw.println(s); } // Script for the dojo parser if(isDojo) { pw.println(" <script>"); pw.println(" require(['dojo/parser']);"); // avoid dojo warning pw.println(" </script>"); } // Add the firebug lite debugging tools if(debug) { pw.println(" <script type=\"text/javascript\" src=\"/xsp/.ibmxspres/.extlib/firebug/js/firebug-lite.js\"></script>\n"); } // Extension: head ends for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).headerEnd(pgContext,pw); } pw.println("</head>"); pw.print("<body"); if(StringUtil.isNotEmpty(bodyTheme)) { pw.print(" class=\""); pw.print(bodyTheme); pw.print("\""); } pw.println(">"); pw.print("<div id='_jsErrors'>"); pw.print("</div>"); pw.print("<script type='text/javascript'>"); pw.print(" window.onerror = function(msg, url, linenumber) {"); pw.print(" var d = document.createElement('div');"); pw.print(" d.innerHTML += 'Unhandled error: '+msg.replace('<', '&lt;').replace('>', '&gt;')+'<br> in page: '+url+'<br>at: '+linenumber;"); pw.print(" document.getElementById('_jsErrors').appendChild(d);"); pw.print(" return true;"); pw.print(" }"); pw.print("</script>"); // Extension: body starts for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).bodyStart(pgContext,pw); } pw.println(html); if(StringUtil.isNotEmpty(js)) { String s = "<script>\n" +js +"</script>\n"; pw.println(s); } // Extension: body ends for(int i=0; i<pgExtensions.size(); i++) { pgExtensions.get(i).bodyEnd(pgContext,pw); } pw.println("</body>"); pw.println("</html>"); pw.flush(); pw.close(); }
diff --git a/libraries/javalib/java/util/Properties.java b/libraries/javalib/java/util/Properties.java index d2056560d..ecdc26652 100644 --- a/libraries/javalib/java/util/Properties.java +++ b/libraries/javalib/java/util/Properties.java @@ -1,344 +1,354 @@ package java.util; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Writer; import java.lang.String; import java.lang.System; /* * Java core library component. * * Copyright (c) 1997, 1998 * Transvirtual Technologies, Inc. All rights reserved. * * See the file "license.terms" for information on usage and redistribution * of this file. */ public class Properties extends Hashtable { private static final long serialVersionUID = 4112578634029874840L; protected Properties defaults; private StringBuffer key, value; public Properties() { this(null); } public Properties(Properties defaults) { this.defaults=defaults; } private static String escape(String str, boolean isKey) { StringBuffer sb = new StringBuffer(); for (int pos = 0; pos < str.length(); pos++) { char ch = str.charAt(pos); switch (ch) { case '!': case '#': if (pos == 0) sb.append("\\"); sb.append(ch); break; case ':': case '=': case ' ': if (!isKey) { sb.append(ch); break; } // fall through case '\\': sb.append("\\" + ch); break; case '\n': sb.append("\\n"); break; case '\t': sb.append("\\t"); break; case '\r': sb.append("\\r"); break; default: if (ch > 0x7e) { sb.append("\\\\u"); sb.append(Character.forDigit((ch >> 12) & 0xf, 16)); sb.append(Character.forDigit((ch >> 8) & 0xf, 16)); sb.append(Character.forDigit((ch >> 4) & 0xf, 16)); sb.append(Character.forDigit(ch & 0xf, 16)); } else sb.append(ch); break; } } return sb.toString(); } public String getProperty(String key) { // Apparently we should use the superclass get method rather than // our own because it may be overridden // Software: HotJava // if (System.out != null) System.out.println("getProperty: " + key); Object propSearch = super.get(key); if (propSearch != null) { return ((String)propSearch); } else if (defaults != null) { return (defaults.getProperty(key)); } else { return (null); } } public String getProperty(String key, String defaultValue) { String result=getProperty(key); if (result==null) return defaultValue; else return result; } public void list(PrintStream out) { list(new PrintWriter(out, true)); } public void list(PrintWriter out) { try { save(out, "Properties list"); } catch (IOException _) { System.err.println("unable to list properties"); } } public Enumeration propertyNames() { final Vector result = new Vector(); // Add main properties for (Enumeration e = keys(); e.hasMoreElements(); ) { result.addElement(e.nextElement()); } // Add non-overridden default properties if (defaults != null) { for (Enumeration e = defaults.keys(); e.hasMoreElements(); ) { Object def = e.nextElement(); if (!result.contains(def)) result.addElement(def); } } // Return enumeration of vector return new Enumeration() { private int posn = 0; public boolean hasMoreElements() { return (posn < result.size()); } public Object nextElement() { if (posn == result.size()) throw new NoSuchElementException(); return result.elementAt(posn++); } } // not unreachable ; } public synchronized void load(InputStream in) throws IOException { PushbackInputStream pin = new PushbackInputStream(in, 16); while (readKeyAndValue(pin)) { put(key.toString(), value.toString()); } key = null; value = null; //pin.close(); ?? } private boolean readKeyAndValue(PushbackInputStream in) throws IOException { int ch; while (true) { // Eat initial white space while ((ch = in.read()) != -1 && ch <= ' '); // Skip comments switch (ch) { case '#': case '!': while ((ch = in.read()) != '\n'); continue; case -1: return false; } // Initialize this.key = new StringBuffer(); this.value = new StringBuffer(); // Read in key + boolean eatSeparator = false; getKey: while (true) { switch (ch) { case '=': case ':': break getKey; case '\r': switch ((ch = in.read())) { case '\n': break; case -1: return true; default: in.unread(ch); break getKey; } // fall through case -1: case '\n': return true; default: - if (ch <= ' ') + if (ch <= ' ') { + eatSeparator = true; break getKey; + } in.unread(ch); key.append((char) getEscapedChar(in)); } ch = in.read(); } - // Eat white space before value - while ((ch = in.read()) <= ' ') { - if (ch == -1 || ch == '\n') - return true; + // Eat white space (and separator, if expecting) before value + while (true) { + while ((ch = in.read()) <= ' ') { + if (ch == -1 || ch == '\n') + return true; + } + if (eatSeparator && (ch == '=' || ch == ':')) { + eatSeparator = false; + } else { + break; + } } // Read in value while (true) { switch (ch) { case '\r': switch ((ch = in.read())) { case -1: value.append('\r'); // fall through case '\n': return true; default: in.unread(ch); value.append('\r'); break; } break; case -1: case '\n': return true; default: in.unread(ch); value.append((char) getEscapedChar(in)); break; } ch = in.read(); } } } // Get next char, respecting backslash escape codes and end-of-line stuff private static int getEscapedChar(PushbackInputStream in) throws IOException { int ch; switch ((ch = in.read())) { case '\\': switch ((ch = in.read())) { case '\r': switch ((ch = in.read())) { default: in.unread(ch); // fall through case -1: in.unread('\r'); return '\\'; case '\n': break; } // fall through case '\n': while ((ch = in.read()) != -1 && ch <= ' '); return ch; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case '\\': switch ((ch = in.read())) { case 'u': int[] dig = new int[4]; int n; getUnicode: { int dval, cval = 0; for (n = 0; n < 4; ) { if ((dig[n] = in.read()) == -1) break getUnicode; if ((dval = Character.digit( (char) dig[n++], 16)) == -1) break getUnicode; cval = (cval << 4) | dval; } return cval; } // not unreachable, break getUnicode go here while (n > 0) in.unread(dig[--n]); // fall through default: in.unread(ch); return '\\'; } // not fall through, previous switch always return case -1: return '\\'; default: return ch; } // not fall through, previous switch always return case '\r': switch ((ch = in.read())) { default: in.unread(ch); // fall through case -1: return '\r'; case '\n': break; } // fall through default: return ch; } } public synchronized void save(OutputStream out, String header) { try { store(out, header); } catch (IOException e) { System.err.println("Unable to save properties: "+header); } } public synchronized void store(OutputStream out, String header) throws IOException { save(new PrintWriter(out, true), header); } // NB: use a PrintWriter here to get platform-specific line separator private synchronized void save(PrintWriter out, String header) throws IOException { if (header != null) { out.println("# " + escape(header, false)); } Enumeration keys = propertyNames(); while (keys.hasMoreElements()) { String key=(String)keys.nextElement(); out.println(escape(key, true) + "=" + escape(getProperty(key), false)); } out.flush(); // shouldn't be necessary } }
false
true
private boolean readKeyAndValue(PushbackInputStream in) throws IOException { int ch; while (true) { // Eat initial white space while ((ch = in.read()) != -1 && ch <= ' '); // Skip comments switch (ch) { case '#': case '!': while ((ch = in.read()) != '\n'); continue; case -1: return false; } // Initialize this.key = new StringBuffer(); this.value = new StringBuffer(); // Read in key getKey: while (true) { switch (ch) { case '=': case ':': break getKey; case '\r': switch ((ch = in.read())) { case '\n': break; case -1: return true; default: in.unread(ch); break getKey; } // fall through case -1: case '\n': return true; default: if (ch <= ' ') break getKey; in.unread(ch); key.append((char) getEscapedChar(in)); } ch = in.read(); } // Eat white space before value while ((ch = in.read()) <= ' ') { if (ch == -1 || ch == '\n') return true; } // Read in value while (true) { switch (ch) { case '\r': switch ((ch = in.read())) { case -1: value.append('\r'); // fall through case '\n': return true; default: in.unread(ch); value.append('\r'); break; } break; case -1: case '\n': return true; default: in.unread(ch); value.append((char) getEscapedChar(in)); break; } ch = in.read(); } } }
private boolean readKeyAndValue(PushbackInputStream in) throws IOException { int ch; while (true) { // Eat initial white space while ((ch = in.read()) != -1 && ch <= ' '); // Skip comments switch (ch) { case '#': case '!': while ((ch = in.read()) != '\n'); continue; case -1: return false; } // Initialize this.key = new StringBuffer(); this.value = new StringBuffer(); // Read in key boolean eatSeparator = false; getKey: while (true) { switch (ch) { case '=': case ':': break getKey; case '\r': switch ((ch = in.read())) { case '\n': break; case -1: return true; default: in.unread(ch); break getKey; } // fall through case -1: case '\n': return true; default: if (ch <= ' ') { eatSeparator = true; break getKey; } in.unread(ch); key.append((char) getEscapedChar(in)); } ch = in.read(); } // Eat white space (and separator, if expecting) before value while (true) { while ((ch = in.read()) <= ' ') { if (ch == -1 || ch == '\n') return true; } if (eatSeparator && (ch == '=' || ch == ':')) { eatSeparator = false; } else { break; } } // Read in value while (true) { switch (ch) { case '\r': switch ((ch = in.read())) { case -1: value.append('\r'); // fall through case '\n': return true; default: in.unread(ch); value.append('\r'); break; } break; case -1: case '\n': return true; default: in.unread(ch); value.append((char) getEscapedChar(in)); break; } ch = in.read(); } } }
diff --git a/oneway/g4/Player.java b/oneway/g4/Player.java index 250d832..e9fa8f9 100644 --- a/oneway/g4/Player.java +++ b/oneway/g4/Player.java @@ -1,71 +1,71 @@ package oneway.g4; import java.util.Arrays; import java.util.Collections; import java.util.List; import oneway.sim.MovingCar; import oneway.sim.Parking; public class Player extends oneway.sim.Player { private int currentTime = -1; public Player() {} public void init(int nsegments, int[] nblocks, int[] capacity) { this.nsegments = nsegments; this.nblocks = nblocks; this.capacity = capacity.clone(); } public void setLights(MovingCar[] movingCars, Parking[] left, Parking[] right, boolean[] llights, boolean[] rlights) { currentTime++; Node node = new Node(currentTime, nsegments, nblocks, movingCars, left, right, capacity, llights, rlights); // List<Node> children = node.successors(); // Collections.sort(children); // if (children.size() == 0) return; // Node choice = children.get(0); // Strategy 0: On the first turn, just let cars come in since search will // instantly terminate boolean moreThanOneRoad = left.length > 2; - if (moreThanOneRoad && movingCars.length == 0 && !anyParkedCars(left, right)){ + if (moreThanOneRoad && movingCars.length == 0 && !anyParkedCars(left, right) && capacity[1] > 0){ System.out.println("First turn with 2+ segments, so lettings cars in."); llights[llights.length-1] = true; rlights[0] = true; return; } Node choice = new Searcher().best(node); boolean[] newLLights = choice.getLLights(); boolean[] newRLights = choice.getRLights(); for(int i = 0; i < nsegments; i++) { llights[i] = newLLights[i]; rlights[i] = newRLights[i]; } } private boolean anyParkedCars(Parking[] left, Parking[] right){ for (int i = 0; i < left.length; i++){ if (left[i] != null && left[i].size() != 0) return true; if (right[i] != null && right[i].size() != 0) return true; } return false; } private int nsegments; private int[] nblocks; private int[] capacity; }
true
true
public void setLights(MovingCar[] movingCars, Parking[] left, Parking[] right, boolean[] llights, boolean[] rlights) { currentTime++; Node node = new Node(currentTime, nsegments, nblocks, movingCars, left, right, capacity, llights, rlights); // List<Node> children = node.successors(); // Collections.sort(children); // if (children.size() == 0) return; // Node choice = children.get(0); // Strategy 0: On the first turn, just let cars come in since search will // instantly terminate boolean moreThanOneRoad = left.length > 2; if (moreThanOneRoad && movingCars.length == 0 && !anyParkedCars(left, right)){ System.out.println("First turn with 2+ segments, so lettings cars in."); llights[llights.length-1] = true; rlights[0] = true; return; } Node choice = new Searcher().best(node); boolean[] newLLights = choice.getLLights(); boolean[] newRLights = choice.getRLights(); for(int i = 0; i < nsegments; i++) { llights[i] = newLLights[i]; rlights[i] = newRLights[i]; } }
public void setLights(MovingCar[] movingCars, Parking[] left, Parking[] right, boolean[] llights, boolean[] rlights) { currentTime++; Node node = new Node(currentTime, nsegments, nblocks, movingCars, left, right, capacity, llights, rlights); // List<Node> children = node.successors(); // Collections.sort(children); // if (children.size() == 0) return; // Node choice = children.get(0); // Strategy 0: On the first turn, just let cars come in since search will // instantly terminate boolean moreThanOneRoad = left.length > 2; if (moreThanOneRoad && movingCars.length == 0 && !anyParkedCars(left, right) && capacity[1] > 0){ System.out.println("First turn with 2+ segments, so lettings cars in."); llights[llights.length-1] = true; rlights[0] = true; return; } Node choice = new Searcher().best(node); boolean[] newLLights = choice.getLLights(); boolean[] newRLights = choice.getRLights(); for(int i = 0; i < nsegments; i++) { llights[i] = newLLights[i]; rlights[i] = newRLights[i]; } }
diff --git a/src/main/java/hex/nn/NNModel.java b/src/main/java/hex/nn/NNModel.java index a0bf6acb3..2d43abfbf 100644 --- a/src/main/java/hex/nn/NNModel.java +++ b/src/main/java/hex/nn/NNModel.java @@ -1,800 +1,800 @@ package hex.nn; import hex.FrameTask.DataInfo; import water.*; import water.api.Cancel; import water.api.ConfusionMatrix; import water.api.DocGen; import water.api.Inspect2; import water.api.Request.API; import water.fvec.Frame; import water.util.D3Plot; import water.util.Log; import water.util.Utils; import java.util.Arrays; import java.util.Random; public class NNModel extends Model { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. @API(help="Model info", json = true) private volatile NNModelInfo model_info; void set_model_info(NNModelInfo mi) { model_info = mi; } final public NNModelInfo model_info() { return model_info; } @API(help="Job that built the model", json = true) private Key jobKey; @API(help="Time to build the model", json = true) private long run_time; private long start_time; @API(help="Number of training epochs", json = true) public double epoch_counter; @API(help = "Scoring during model building") public Errors[] errors; @Override public void delete() { super.delete(); model_info.cleanUp(); } public static class Errors extends Iced { static final int API_WEAVER = 1; static public DocGen.FieldDoc[] DOC_FIELDS; @API(help = "How many epochs the algorithm has processed") public double epoch_counter; @API(help = "How many rows the algorithm has processed") public long training_samples; @API(help = "How long the algorithm ran in ms") public long training_time_ms; //training/validation sets @API(help = "Whether a validation set was provided") boolean validation; @API(help = "Number of training set samples for scoring") public long score_training_samples; @API(help = "Number of validation set samples for scoring") public long score_validation_samples; @API(help="Do classification or regression") public boolean classification; // classification @API(help = "Confusion matrix on training data") public water.api.ConfusionMatrix train_confusion_matrix; @API(help = "Confusion matrix on validation data") public water.api.ConfusionMatrix valid_confusion_matrix; @API(help = "Classification error on training data") public double train_err = 1; @API(help = "Classification error on validation data") public double valid_err = 1; // regression @API(help = "Training MSE") public double train_mse = Double.POSITIVE_INFINITY; @API(help = "Validation MSE") public double valid_mse = Double.POSITIVE_INFINITY; // @API(help = "Training MCE") // public double train_mce = Double.POSITIVE_INFINITY; // @API(help = "Validation MCE") // public double valid_mce = Double.POSITIVE_INFINITY; @Override public String toString() { StringBuilder sb = new StringBuilder(); if (classification) { sb.append("Training misclassification: " + String.format("%.2f", (100 * train_err)) + "%"); if (validation) sb.append(", validation misclassification: " + String.format("%.2f", (100 * valid_err)) + "%"); } else { sb.append("Training MSE: " + train_mse); if (validation) sb.append(", validation MSE: " + valid_mse); } return sb.toString(); } } /** for grid search error reporting */ @Override public hex.ConfusionMatrix cm() { if (errors == null) return null; water.api.ConfusionMatrix cm = errors[errors.length-1].validation ? errors[errors.length-1].valid_confusion_matrix : errors[errors.length-1].train_confusion_matrix; if (cm == null) return null; return new hex.ConfusionMatrix(cm.cm); } // This describes the model, together with the parameters // This will be shared: one per node public static class NNModelInfo extends Iced { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. @API(help="Input data info") final private DataInfo data_info; public DataInfo data_info() { return data_info; } // model is described by parameters and the following 2 arrays final private float[][] weights; //one 2D weight matrix per layer (stored as a 1D array each) final private double[][] biases; //one 1D bias array per layer // helpers for storing previous step deltas // Note: These two arrays *could* be made transient and then initialized freshly in makeNeurons() and in NNTask.initLocal() // But then, after each reduction, the weights would be lost and would have to restart afresh -> not *exactly* right, but close... private float[][] weights_momenta; private double[][] biases_momenta; // compute model size (number of model parameters required for making predictions) // momenta are not counted here, but they are needed for model building public long size() { long siz = 0; for (float[] w : weights) siz += w.length; for (double[] b : biases) siz += b.length; return siz; } // accessors to (shared) weights and biases - those will be updated racily (c.f. Hogwild!) final boolean _has_momenta; boolean has_momenta() { return _has_momenta; } public final float[] get_weights(int i) { return weights[i]; } public final double[] get_biases(int i) { return biases[i]; } public final float[] get_weights_momenta(int i) { return weights_momenta[i]; } public final double[] get_biases_momenta(int i) { return biases_momenta[i]; } @API(help = "Model parameters", json = true) final private NN parameters; public final NN get_params() { return parameters; } public final NN job() { return get_params(); } @API(help = "Mean bias", json = true) private double[] mean_bias; @API(help = "RMS bias", json = true) private double[] rms_bias; @API(help = "Mean weight", json = true) private double[] mean_weight; @API(help = "RMS weight", json = true) public double[] rms_weight; @API(help = "Unstable", json = true) private boolean unstable = false; public boolean unstable() { return unstable; } @API(help = "Processed samples", json = true) private long processed_global; public synchronized long get_processed_global() { return processed_global; } public synchronized void set_processed_global(long p) { processed_global = p; } public synchronized void add_processed_global(long p) { processed_global += p; } private long processed_local; public synchronized long get_processed_local() { return processed_local; } public synchronized void set_processed_local(long p) { processed_local = p; } public synchronized void add_processed_local(long p) { processed_local += p; } public synchronized long get_processed_total() { return processed_global + processed_local; } // package local helpers final int[] units; //number of neurons per layer, extracted from parameters and from datainfo // public NNModelInfo(NN params, int num_input, int num_output) { public NNModelInfo(NN params, DataInfo dinfo) { data_info = dinfo; //should be deep_clone()? final int num_input = dinfo.fullN(); final int num_output = params.classification ? dinfo._adaptedFrame.lastVec().domain().length : 1; assert(num_input > 0); assert(num_output > 0); parameters = params; _has_momenta = ( parameters.momentum_start != 0 || parameters.momentum_stable != 0 ); final int layers=parameters.hidden.length; // units (# neurons for each layer) units = new int[layers+2]; units[0] = num_input; System.arraycopy(parameters.hidden, 0, units, 1, layers); units[layers+1] = num_output; // weights (to connect layers) weights = new float[layers+1][]; for (int i=0; i<=layers; ++i) weights[i] = new float[units[i]*units[i+1]]; // biases (only for hidden layers and output layer) biases = new double[layers+1][]; for (int i=0; i<=layers; ++i) biases[i] = new double[units[i+1]]; createMomenta(); // for diagnostics mean_bias = new double[units.length]; rms_bias = new double[units.length]; mean_weight = new double[units.length]; rms_weight = new double[units.length]; } public NNModelInfo(NNModelInfo other) { this(other.parameters, other.data_info()); set_processed_local(other.get_processed_local()); set_processed_global(other.get_processed_global()); for (int i=0; i<other.weights.length; ++i) weights[i] = other.weights[i].clone(); for (int i=0; i<other.biases.length; ++i) biases[i] = other.biases[i].clone(); if (has_momenta()) { for (int i=0; i<other.weights_momenta.length; ++i) weights_momenta[i] = other.weights_momenta[i].clone(); for (int i=0; i<other.biases_momenta.length; ++i) biases_momenta[i] = other.biases_momenta[i].clone(); } mean_bias = other.mean_bias.clone(); rms_bias = other.rms_bias.clone(); mean_weight = other.mean_weight.clone(); rms_weight = other.rms_weight.clone(); unstable = other.unstable; } protected void createMomenta() { if (has_momenta() && weights_momenta == null) { weights_momenta = new float[weights.length][]; for (int i=0; i<weights_momenta.length; ++i) weights_momenta[i] = new float[units[i]*units[i+1]]; biases_momenta = new double[biases.length][]; for (int i=0; i<biases_momenta.length; ++i) biases_momenta[i] = new double[units[i+1]]; } } public void cleanUp() { // ugly: whoever made data_info should also clean this up... but sometimes it was made by Weaver from UKV! UKV.remove(data_info()._adaptedFrame.lastVec()._key); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (parameters.diagnostics) { Neurons[] neurons = NNTask.makeNeuronsForTesting(this); computeStats(); sb.append("Status of Neuron Layers:\n"); sb.append("# Units Type Dropout Rate L1 L2 Momentum Weight (Mean, RMS) Bias (Mean,RMS)\n"); final String format = "%7g"; for (int i=0; i<neurons.length; ++i) { sb.append((i+1) + " " + String.format("%6d", neurons[i].units) + " " + String.format("%16s", neurons[i].getClass().getSimpleName())); if (i == 0) { sb.append(" " + String.format("%.5g", neurons[i].params.input_dropout_ratio*100) + "%\n"); continue; } else if (i < neurons.length-1) { sb.append( neurons[i] instanceof Neurons.TanhDropout || neurons[i] instanceof Neurons.RectifierDropout || neurons[i] instanceof Neurons.MaxoutDropout ? " 50% " : " 0% "); } else { sb.append(" "); } sb.append( " " + String.format("%10g", neurons[i].rate(get_processed_total())) + " " + String.format("%5f", neurons[i].params.l1) + " " + String.format("%5f", neurons[i].params.l2) + " " + String.format("%5f", neurons[i].momentum(get_processed_total())) + " (" + String.format(format, mean_weight[i]) + ", " + String.format(format, rms_weight[i]) + ")" + " (" + String.format(format, mean_bias[i]) + ", " + String.format(format, rms_bias[i]) + ")\n"); } } // DEBUGGING // for (int i=0; i<weights.length; ++i) // sb.append("\nweights["+i+"][]="+Arrays.toString(weights[i])); // for (int i=0; i<biases.length; ++i) // sb.append("\nbiases["+i+"][]="+Arrays.toString(biases[i])); //// if (weights_momenta != null) { //// for (int i=0; i<weights_momenta.length; ++i) //// sb.append("\nweights_momenta["+i+"][]="+Arrays.toString(weights_momenta[i])); //// } //// if (biases_momenta != null) { //// for (int i=0; i<biases_momenta.length; ++i) //// sb.append("\nbiases_momenta["+i+"][]="+Arrays.toString(biases_momenta[i])); //// } //// sb.append("\nunits[]="+Arrays.toString(units)); //// sb.append("\nprocessed global: "+get_processed_global()); //// sb.append("\nprocessed local: "+get_processed_local()); //// sb.append("\nprocessed total: " + get_processed_total()); // sb.append("\n"); return sb.toString(); } void initializeMembers() { randomizeWeights(); //TODO: determine good/optimal/best initialization scheme for biases // hidden layers for (int i=0; i<parameters.hidden.length; ++i) { if (parameters.activation == NN.Activation.Rectifier || parameters.activation == NN.Activation.RectifierWithDropout || parameters.activation == NN.Activation.Maxout || parameters.activation == NN.Activation.MaxoutWithDropout ) { // Arrays.fill(biases[i], 1.); //old behavior Arrays.fill(biases[i], i == 0 ? 0.5 : 1.); //new behavior, might be slightly better } else if (parameters.activation == NN.Activation.Tanh || parameters.activation == NN.Activation.TanhWithDropout) { Arrays.fill(biases[i], 0.0); } } Arrays.fill(biases[biases.length-1], 0.0); //output layer } public void add(NNModelInfo other) { Utils.add(weights, other.weights); Utils.add(biases, other.biases); if (has_momenta()) { assert(other.has_momenta()); Utils.add(weights_momenta, other.weights_momenta); Utils.add(biases_momenta, other.biases_momenta); } add_processed_local(other.get_processed_local()); } protected void div(double N) { for (float[] weight : weights) Utils.div(weight, (float) N); for (double[] bias : biases) Utils.div(bias, N); if (has_momenta()) { for (float[] weight_momenta : weights_momenta) Utils.div(weight_momenta, (float) N); for (double[] bias_momenta : biases_momenta) Utils.div(bias_momenta, N); } } double uniformDist(Random rand, double min, double max) { return min + rand.nextFloat() * (max - min); } void randomizeWeights() { for (int i=0; i<weights.length; ++i) { final Random rng = water.util.Utils.getDeterRNG(get_params().seed + 0xBAD5EED + i+1); //to match NeuralNet behavior for( int j = 0; j < weights[i].length; j++ ) { if (parameters.initial_weight_distribution == NN.InitialWeightDistribution.UniformAdaptive) { // cf. http://machinelearning.wustl.edu/mlpapers/paper_files/AISTATS2010_GlorotB10.pdf final double range = Math.sqrt(6. / (units[i] + units[i+1])); weights[i][j] = (float)uniformDist(rng, -range, range); if (i==weights.length-1 && parameters.classification) weights[i][j] *= 4; //Softmax might need an extra factor 4, since it's like a sigmoid } else if (parameters.initial_weight_distribution == NN.InitialWeightDistribution.Uniform) { weights[i][j] = (float)uniformDist(rng, -parameters.initial_weight_scale, parameters.initial_weight_scale); } else if (parameters.initial_weight_distribution == NN.InitialWeightDistribution.Normal) { weights[i][j] = (float)(rng.nextGaussian() * parameters.initial_weight_scale); } } } } // TODO: Add "subset randomize" function // int count = Math.min(15, _previous.units); // double min = -.1f, max = +.1f; // //double min = -1f, max = +1f; // for( int o = 0; o < units; o++ ) { // for( int n = 0; n < count; n++ ) { // int i = rand.nextInt(_previous.units); // int w = o * _previous.units + i; // _w[w] = uniformDist(rand, min, max); // } // } // compute stats on all nodes public void computeStats() { for( int y = 1; y < units.length; y++ ) { mean_bias[y] = rms_bias[y] = 0; mean_weight[y] = rms_weight[y] = 0; for(int u = 0; u < biases[y-1].length; u++) { mean_bias[y] += biases[y-1][u]; } for(int u = 0; u < weights[y-1].length; u++) { mean_weight[y] += weights[y-1][u]; } mean_bias[y] /= biases[y-1].length; mean_weight[y] /= weights[y-1].length; for(int u = 0; u < biases[y-1].length; u++) { final double db = biases[y-1][u] - mean_bias[y]; rms_bias[y] += db * db; } for(int u = 0; u < weights[y-1].length; u++) { final double dw = weights[y-1][u] - mean_weight[y]; rms_weight[y] += dw * dw; } rms_bias[y] = Math.sqrt(rms_bias[y]/biases[y-1].length); rms_weight[y] = Math.sqrt(rms_weight[y]/weights[y-1].length); unstable |= Double.isNaN(mean_bias[y]) || Double.isNaN(rms_bias[y]) || Double.isNaN(mean_weight[y]) || Double.isNaN(rms_weight[y]); // Abort the run if weights or biases are unreasonably large (Note that all input values are normalized upfront) // This can happen with Rectifier units when L1/L2/max_w2 are all set to 0, especially when using more than 1 hidden layer. final double thresh = 1e10; unstable |= mean_bias[y] > thresh || Double.isNaN(mean_bias[y]) || rms_bias[y] > thresh || Double.isNaN(rms_bias[y]) || mean_weight[y] > thresh || Double.isNaN(mean_weight[y]) || rms_weight[y] > thresh || Double.isNaN(rms_weight[y]); } } } public NNModel(Key selfKey, Key jobKey, Key dataKey, DataInfo dinfo, NN params) { super(selfKey, dataKey, dinfo._adaptedFrame); this.jobKey = jobKey; run_time = 0; start_time = System.currentTimeMillis(); model_info = new NNModelInfo(params, dinfo); errors = new Errors[1]; errors[0] = new Errors(); errors[0].validation = (params.validation != null); } transient long _now, _timeLastScoreStart, _timeLastPrintStart; /** * * @param ftrain potentially downsampled training data for scoring * @param ftest potentially downsampled validation data for scoring * @param timeStart start time in milliseconds, used to report training speed * @param dest_key where to store the model with the diagnostics in it * @return true if model building is ongoing */ boolean doDiagnostics(Frame ftrain, Frame ftest, long timeStart, Key dest_key) { epoch_counter = (float)model_info().get_processed_total()/model_info().data_info._adaptedFrame.numRows(); run_time = (System.currentTimeMillis()-start_time); boolean keep_running = (epoch_counter < model_info().parameters.epochs); _now = System.currentTimeMillis(); final long sinceLastScore = _now-_timeLastScoreStart; final long sinceLastPrint = _now-_timeLastPrintStart; final long samples = model_info().get_processed_total(); if (sinceLastPrint > model_info().parameters.score_interval*1000) { _timeLastPrintStart = _now; Log.info("Training time: " + PrettyPrint.msecs(_now - start_time, true) + " processed " + samples + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs)." + " Speed: " + String.format("%.3f", (double)samples/((_now - start_time)/1000.)) + " samples/sec."); } // this is potentially slow - only do every so often if( !keep_running || sinceLastScore > model_info().parameters.score_interval*1000) { Log.info("Scoring the model."); _timeLastScoreStart = _now; boolean printCM = false; // compute errors Errors err = new Errors(); err.classification = isClassifier(); assert(err.classification == model_info().get_params().classification); err.training_time_ms = _now - timeStart; err.epoch_counter = epoch_counter; err.validation = ftest != null; err.training_samples = model_info().get_processed_total(); err.score_training_samples = ftrain.numRows(); err.train_confusion_matrix = new ConfusionMatrix(); final double trainErr = calcError(ftrain, "Error on training data:", printCM, err.train_confusion_matrix); if (err.classification) err.train_err = trainErr; else err.train_mse = trainErr; if (err.validation) { err.score_validation_samples = ftest.numRows(); err.valid_confusion_matrix = new ConfusionMatrix(); final double validErr = calcError(ftest, "Error on validation data:", printCM, err.valid_confusion_matrix); if (err.classification) err.valid_err = validErr; else err.valid_mse = validErr; } // enlarge the error array by one, push latest score back if (errors == null) { errors = new Errors[]{err}; } else { Errors[] err2 = new Errors[errors.length+1]; System.arraycopy(errors, 0, err2, 0, errors.length); err2[err2.length-1] = err; errors = err2; } // print the freshly scored model to ASCII for (String s : toString().split("\n")) Log.info(s); Log.info("Scoring time: " + PrettyPrint.msecs(System.currentTimeMillis() - _now, true)); } if (model_info().unstable()) { Log.err("Canceling job since the model is unstable (exponential growth observed)."); Log.err("Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing."); keep_running = false; } else if (ftest == null && (model_info().parameters.classification && errors[errors.length-1].train_err == 0) || (!model_info().parameters.classification && errors[errors.length-1].train_mse == 0) ) { Log.info("Achieved 100% modeling accuracy on the training data. We are done here."); keep_running = false; } else if (ftest != null && (model_info().parameters.classification && errors[errors.length-1].valid_err == 0) || (!model_info().parameters.classification && errors[errors.length-1].valid_mse == 0) ) { Log.info("Achieved 100% modeling accuracy on the validation data. We are done here."); keep_running = false; } update(dest_key); //update model in UKV // System.out.println(this); return keep_running; } @Override public String toString() { StringBuilder sb = new StringBuilder(); // sb.append(super.toString()); // sb.append("\n"+data_info.toString()); //not implemented yet sb.append(model_info.toString()); sb.append(errors[errors.length-1].toString()); // sb.append("\nrun time: " + PrettyPrint.msecs(run_time, true)); // sb.append("\nepoch counter: " + epoch_counter); return sb.toString(); } @Override public float[] score0(double[] data, float[] preds) { Neurons[] neurons = NNTask.makeNeuronsForTesting(model_info); ((Neurons.Input)neurons[0]).setInput(-1, data); NNTask.step(-1, neurons, model_info, false, null); double[] out = neurons[neurons.length - 1]._a; assert((isClassifier() && preds.length == out.length+1) || (!isClassifier() && preds.length == 1 && out.length == 1)); for (int i=0; i<preds.length-1; ++i) preds[i+1] = (float)out[i]; preds[0] = getPrediction(preds, data); return preds; } public double calcError(Frame ftest, String label, boolean printCM, ConfusionMatrix CM) { Frame fpreds; fpreds = score(ftest); if (CM == null) CM = new ConfusionMatrix(); CM.actual = ftest; CM.vactual = ftest.lastVec(); CM.predict = fpreds; CM.vpredict = fpreds.vecs()[0]; CM.serve(); StringBuilder sb = new StringBuilder(); final double error = CM.toASCII(sb); if (printCM) { Log.info(label); for (String s : sb.toString().split("\n")) Log.info(s); } fpreds.delete(); return error; } public boolean generateHTML(String title, StringBuilder sb) { if (_key == null) { DocGen.HTML.title(sb, "No model yet"); return true; } final String mse_format = "%2.6f"; final String cross_entropy_format = "%2.6f"; DocGen.HTML.title(sb, title); DocGen.HTML.paragraph(sb, "Model type: " + (model_info().parameters.classification ? " Classification" : " Regression")); DocGen.HTML.paragraph(sb, "Model Key: " + _key); DocGen.HTML.paragraph(sb, "Job Key: " + jobKey); Inspect2 is2 = new Inspect2(); DocGen.HTML.paragraph(sb, "Training Data Key: " + _dataKey); if (model_info.parameters.validation != null) { DocGen.HTML.paragraph(sb, "Validation Data Key: " + model_info.parameters.validation._key); } DocGen.HTML.paragraph(sb, "Number of model parameters (weights/biases): " + String.format("%,d", model_info().size())); model_info.job().toHTML(sb); sb.append("<div class='alert'>Actions: " + (Job.isRunning(jobKey) ? Cancel.link(jobKey, "Cancel job") + ", " : "") + is2.link("Inspect training data", _dataKey) + ", " + (model_info().parameters.validation != null ? (is2.link("Inspect validation data", model_info().parameters.validation._key) + ", ") : "") + water.api.Predict.link(_key, "Score on dataset") + ", " + NN.link(_dataKey, "Compute new model") + "</div>"); // stats for training and validation final Errors error = errors[errors.length - 1]; assert(error != null); if (errors.length > 1) { if (isClassifier()) { // Plot training error float[] err = new float[errors.length]; float[] samples = new float[errors.length]; for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].train_err; samples[i] = errors[i].training_samples; } new D3Plot(samples, err, "training samples", "classification error", "Classification Error on Training Set").generate(sb); // Plot validation error if (model_info.parameters.validation != null) { for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].valid_err; } new D3Plot(samples, err, "training samples", "classification error", "Classification Error on Validation Set").generate(sb); } } else { // Plot training MSE float[] err = new float[errors.length]; float[] samples = new float[errors.length]; for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].train_mse; samples[i] = errors[i].training_samples; } new D3Plot(samples, err, "training samples", "mean squared error", "Regression Error on Training Set").generate(sb); // Plot validation MSE if (model_info.parameters.validation != null) { for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].valid_mse; } new D3Plot(samples, err, "training samples", "mean squared error", "Regression Error on Validation Set").generate(sb); } } } if (isClassifier()) { DocGen.HTML.section(sb, "Training classification error: " + formatPct(error.train_err)); // DocGen.HTML.section(sb, "Training cross entropy: " + String.format(cross_entropy_format, error.train_mce)); if(error.validation) { DocGen.HTML.section(sb, "Validation classification error: " + formatPct(error.valid_err)); // DocGen.HTML.section(sb, "Validation mean cross entropy: " + String.format(cross_entropy_format, error.valid_mce)); } } else { DocGen.HTML.section(sb, "Training mean square error: " + String.format(mse_format, error.train_mse)); if(error.validation) { DocGen.HTML.section(sb, "Validation mean square error: " + String.format(mse_format, error.valid_mse)); } } if (error.training_time_ms > 0) DocGen.HTML.section(sb, "Training speed: " + error.training_samples * 1000 / error.training_time_ms + " samples/s"); if (model_info.parameters != null && model_info.parameters.diagnostics) { DocGen.HTML.section(sb, "Status of Neuron Layers"); sb.append("<table class='table table-striped table-bordered table-condensed'>"); sb.append("<tr>"); sb.append("<th>").append("#").append("</th>"); sb.append("<th>").append("Units").append("</th>"); sb.append("<th>").append("Type").append("</th>"); sb.append("<th>").append("Dropout").append("</th>"); sb.append("<th>").append("Rate").append("</th>"); sb.append("<th>").append("L1").append("</th>"); sb.append("<th>").append("L2").append("</th>"); sb.append("<th>").append("Momentum").append("</th>"); sb.append("<th>").append("Weight (Mean, RMS)").append("</th>"); sb.append("<th>").append("Bias (Mean, RMS)").append("</th>"); sb.append("</tr>"); Neurons[] neurons = NNTask.makeNeuronsForTesting(model_info()); //link the weights to the neurons, for easy access for (int i=0; i<neurons.length; ++i) { sb.append("<tr>"); sb.append("<td>").append("<b>").append(i+1).append("</b>").append("</td>"); sb.append("<td>").append("<b>").append(neurons[i].units).append("</b>").append("</td>"); sb.append("<td>").append(neurons[i].getClass().getSimpleName()).append("</td>"); if (i == 0) { sb.append("<td>"); sb.append(formatPct(neurons[i].params.input_dropout_ratio)); sb.append("</td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); continue; } else if (i < neurons.length-1) { sb.append("<td>"); sb.append( neurons[i] instanceof Neurons.TanhDropout || neurons[i] instanceof Neurons.RectifierDropout || neurons[i] instanceof Neurons.MaxoutDropout ? "50%" : "0%"); sb.append("</td>"); } else { sb.append("<td></td>"); } sb.append("<td>").append(String.format("%.5g", neurons[i].rate(error.training_samples))).append("</td>"); sb.append("<td>").append(neurons[i].params.l1).append("</td>"); sb.append("<td>").append(neurons[i].params.l2).append("</td>"); final String format = "%g"; sb.append("<td>").append(String.format("%.5f", neurons[i].momentum(error.training_samples))).append("</td>"); sb.append("<td>(").append(String.format(format, model_info.mean_weight[i])). append(", ").append(String.format(format, model_info.rms_weight[i])).append(")</td>"); sb.append("<td>(").append(String.format(format, model_info.mean_bias[i])). append(", ").append(String.format(format, model_info.rms_bias[i])).append(")</td>"); sb.append("</tr>"); } sb.append("</table>"); } if (model_info.unstable()) { final String msg = "Job was aborted due to observed numerical instability (exponential growth)." + " Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing."; DocGen.HTML.section(sb, "======================================================================================="); DocGen.HTML.section(sb, msg); DocGen.HTML.section(sb, "======================================================================================="); } long score_valid = error.score_validation_samples; long score_train = error.score_training_samples; final boolean fulltrain = score_train==0 || score_train == model_info().data_info()._adaptedFrame.numRows(); final boolean fullvalid = score_valid==0 || score_valid == model_info().get_params().validation.numRows(); if (isClassifier()) { final String cmTitle = "Confusion Matrix on " + (error.validation ? "Validation Data" + (fullvalid ? "" : " (" + score_valid + " samples)") : "Training Data" + (fulltrain ? "" : " (" + score_train + " samples)")); DocGen.HTML.section(sb, cmTitle); if (error.train_confusion_matrix != null) { if (error.train_confusion_matrix.cm != null && error.train_confusion_matrix.cm.length < 100) { if (error.validation && error.valid_confusion_matrix != null && error.valid_confusion_matrix.cm != null) error.valid_confusion_matrix.toHTML(sb); else if (error.train_confusion_matrix != null) error.train_confusion_matrix.toHTML(sb); } else { sb.append("<h5>Not shown here (too large).</h5>"); } } else sb.append("<h5>Not yet computed.</h5>"); } sb.append("<h3>" + "Progress" + "</h3>"); sb.append("<h4>" + "Epochs: " + String.format("%.3f", epoch_counter) + "</h4>"); - String training = "Number of training set samples for scoring: " + (fulltrain ? "all" : "") + score_train; + String training = "Number of training set samples for scoring: " + (fulltrain ? "all " + model_info().data_info()._adaptedFrame.numRows() : score_train); if (score_train > 0) { if (score_train < 1000 && model_info().data_info()._adaptedFrame.numRows() >= 1000) training += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)"; if (score_train > 100000) training += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)"; } DocGen.HTML.section(sb, training); if (error.validation) { - String validation = "Number of validation set samples for scoring: " + (fullvalid ? "all" : "") + score_valid; + String validation = "Number of validation set samples for scoring: " + (fullvalid ? "all " + model_info().get_params().validation.numRows() : score_valid); if (score_valid > 0) { if (score_valid < 1000 && model_info().get_params().validation.numRows() >= 1000) validation += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)"; if (score_valid > 100000) validation += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)"; } DocGen.HTML.section(sb, validation); } // String training = "Number of training set samples for scoring: " + error.score_training; if (error.validation) { // String validation = "Number of validation set samples for scoring: " + error.score_validation; } sb.append("<table class='table table-striped table-bordered table-condensed'>"); sb.append("<tr>"); sb.append("<th>Training Time</th>"); sb.append("<th>Training Epochs</th>"); sb.append("<th>Training Samples</th>"); if (isClassifier()) { // sb.append("<th>Training MCE</th>"); sb.append("<th>Training Error</th>"); } else { sb.append("<th>Training MSE</th>"); } if (error.validation) { if (isClassifier()) { // sb.append("<th>Validation MCE</th>"); sb.append("<th>Validation Error</th>"); } else { sb.append("<th>Validation MSE</th>"); } } sb.append("</tr>"); for( int i = errors.length - 1; i >= 0; i-- ) { final Errors e = errors[i]; sb.append("<tr>"); sb.append("<td>" + PrettyPrint.msecs(e.training_time_ms, true) + "</td>"); sb.append("<td>" + String.format("%g", e.epoch_counter) + "</td>"); sb.append("<td>" + String.format("%,d", e.training_samples) + "</td>"); if (isClassifier()) { // sb.append("<td>" + String.format(cross_entropy_format, e.train_mce) + "</td>"); sb.append("<td>" + formatPct(e.train_err) + "</td>"); } else { sb.append("<td>" + String.format(mse_format, e.train_mse) + "</td>"); } if(e.validation) { if (isClassifier()) { // sb.append("<td>" + String.format(cross_entropy_format, e.valid_mce) + "</td>"); sb.append("<td>" + formatPct(e.valid_err) + "</td>"); } else { sb.append("<td>" + String.format(mse_format, e.valid_mse) + "</td>"); } } sb.append("</tr>"); } sb.append("</table>"); return true; } private static String formatPct(double pct) { String s = "N/A"; if( !Double.isNaN(pct) ) s = String.format("%5.2f %%", 100 * pct); return s; } public boolean toJavaHtml(StringBuilder sb) { return false; } @Override public String toJava() { return "Not yet implemented."; } }
false
true
public boolean generateHTML(String title, StringBuilder sb) { if (_key == null) { DocGen.HTML.title(sb, "No model yet"); return true; } final String mse_format = "%2.6f"; final String cross_entropy_format = "%2.6f"; DocGen.HTML.title(sb, title); DocGen.HTML.paragraph(sb, "Model type: " + (model_info().parameters.classification ? " Classification" : " Regression")); DocGen.HTML.paragraph(sb, "Model Key: " + _key); DocGen.HTML.paragraph(sb, "Job Key: " + jobKey); Inspect2 is2 = new Inspect2(); DocGen.HTML.paragraph(sb, "Training Data Key: " + _dataKey); if (model_info.parameters.validation != null) { DocGen.HTML.paragraph(sb, "Validation Data Key: " + model_info.parameters.validation._key); } DocGen.HTML.paragraph(sb, "Number of model parameters (weights/biases): " + String.format("%,d", model_info().size())); model_info.job().toHTML(sb); sb.append("<div class='alert'>Actions: " + (Job.isRunning(jobKey) ? Cancel.link(jobKey, "Cancel job") + ", " : "") + is2.link("Inspect training data", _dataKey) + ", " + (model_info().parameters.validation != null ? (is2.link("Inspect validation data", model_info().parameters.validation._key) + ", ") : "") + water.api.Predict.link(_key, "Score on dataset") + ", " + NN.link(_dataKey, "Compute new model") + "</div>"); // stats for training and validation final Errors error = errors[errors.length - 1]; assert(error != null); if (errors.length > 1) { if (isClassifier()) { // Plot training error float[] err = new float[errors.length]; float[] samples = new float[errors.length]; for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].train_err; samples[i] = errors[i].training_samples; } new D3Plot(samples, err, "training samples", "classification error", "Classification Error on Training Set").generate(sb); // Plot validation error if (model_info.parameters.validation != null) { for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].valid_err; } new D3Plot(samples, err, "training samples", "classification error", "Classification Error on Validation Set").generate(sb); } } else { // Plot training MSE float[] err = new float[errors.length]; float[] samples = new float[errors.length]; for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].train_mse; samples[i] = errors[i].training_samples; } new D3Plot(samples, err, "training samples", "mean squared error", "Regression Error on Training Set").generate(sb); // Plot validation MSE if (model_info.parameters.validation != null) { for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].valid_mse; } new D3Plot(samples, err, "training samples", "mean squared error", "Regression Error on Validation Set").generate(sb); } } } if (isClassifier()) { DocGen.HTML.section(sb, "Training classification error: " + formatPct(error.train_err)); // DocGen.HTML.section(sb, "Training cross entropy: " + String.format(cross_entropy_format, error.train_mce)); if(error.validation) { DocGen.HTML.section(sb, "Validation classification error: " + formatPct(error.valid_err)); // DocGen.HTML.section(sb, "Validation mean cross entropy: " + String.format(cross_entropy_format, error.valid_mce)); } } else { DocGen.HTML.section(sb, "Training mean square error: " + String.format(mse_format, error.train_mse)); if(error.validation) { DocGen.HTML.section(sb, "Validation mean square error: " + String.format(mse_format, error.valid_mse)); } } if (error.training_time_ms > 0) DocGen.HTML.section(sb, "Training speed: " + error.training_samples * 1000 / error.training_time_ms + " samples/s"); if (model_info.parameters != null && model_info.parameters.diagnostics) { DocGen.HTML.section(sb, "Status of Neuron Layers"); sb.append("<table class='table table-striped table-bordered table-condensed'>"); sb.append("<tr>"); sb.append("<th>").append("#").append("</th>"); sb.append("<th>").append("Units").append("</th>"); sb.append("<th>").append("Type").append("</th>"); sb.append("<th>").append("Dropout").append("</th>"); sb.append("<th>").append("Rate").append("</th>"); sb.append("<th>").append("L1").append("</th>"); sb.append("<th>").append("L2").append("</th>"); sb.append("<th>").append("Momentum").append("</th>"); sb.append("<th>").append("Weight (Mean, RMS)").append("</th>"); sb.append("<th>").append("Bias (Mean, RMS)").append("</th>"); sb.append("</tr>"); Neurons[] neurons = NNTask.makeNeuronsForTesting(model_info()); //link the weights to the neurons, for easy access for (int i=0; i<neurons.length; ++i) { sb.append("<tr>"); sb.append("<td>").append("<b>").append(i+1).append("</b>").append("</td>"); sb.append("<td>").append("<b>").append(neurons[i].units).append("</b>").append("</td>"); sb.append("<td>").append(neurons[i].getClass().getSimpleName()).append("</td>"); if (i == 0) { sb.append("<td>"); sb.append(formatPct(neurons[i].params.input_dropout_ratio)); sb.append("</td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); continue; } else if (i < neurons.length-1) { sb.append("<td>"); sb.append( neurons[i] instanceof Neurons.TanhDropout || neurons[i] instanceof Neurons.RectifierDropout || neurons[i] instanceof Neurons.MaxoutDropout ? "50%" : "0%"); sb.append("</td>"); } else { sb.append("<td></td>"); } sb.append("<td>").append(String.format("%.5g", neurons[i].rate(error.training_samples))).append("</td>"); sb.append("<td>").append(neurons[i].params.l1).append("</td>"); sb.append("<td>").append(neurons[i].params.l2).append("</td>"); final String format = "%g"; sb.append("<td>").append(String.format("%.5f", neurons[i].momentum(error.training_samples))).append("</td>"); sb.append("<td>(").append(String.format(format, model_info.mean_weight[i])). append(", ").append(String.format(format, model_info.rms_weight[i])).append(")</td>"); sb.append("<td>(").append(String.format(format, model_info.mean_bias[i])). append(", ").append(String.format(format, model_info.rms_bias[i])).append(")</td>"); sb.append("</tr>"); } sb.append("</table>"); } if (model_info.unstable()) { final String msg = "Job was aborted due to observed numerical instability (exponential growth)." + " Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing."; DocGen.HTML.section(sb, "======================================================================================="); DocGen.HTML.section(sb, msg); DocGen.HTML.section(sb, "======================================================================================="); } long score_valid = error.score_validation_samples; long score_train = error.score_training_samples; final boolean fulltrain = score_train==0 || score_train == model_info().data_info()._adaptedFrame.numRows(); final boolean fullvalid = score_valid==0 || score_valid == model_info().get_params().validation.numRows(); if (isClassifier()) { final String cmTitle = "Confusion Matrix on " + (error.validation ? "Validation Data" + (fullvalid ? "" : " (" + score_valid + " samples)") : "Training Data" + (fulltrain ? "" : " (" + score_train + " samples)")); DocGen.HTML.section(sb, cmTitle); if (error.train_confusion_matrix != null) { if (error.train_confusion_matrix.cm != null && error.train_confusion_matrix.cm.length < 100) { if (error.validation && error.valid_confusion_matrix != null && error.valid_confusion_matrix.cm != null) error.valid_confusion_matrix.toHTML(sb); else if (error.train_confusion_matrix != null) error.train_confusion_matrix.toHTML(sb); } else { sb.append("<h5>Not shown here (too large).</h5>"); } } else sb.append("<h5>Not yet computed.</h5>"); } sb.append("<h3>" + "Progress" + "</h3>"); sb.append("<h4>" + "Epochs: " + String.format("%.3f", epoch_counter) + "</h4>"); String training = "Number of training set samples for scoring: " + (fulltrain ? "all" : "") + score_train; if (score_train > 0) { if (score_train < 1000 && model_info().data_info()._adaptedFrame.numRows() >= 1000) training += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)"; if (score_train > 100000) training += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)"; } DocGen.HTML.section(sb, training); if (error.validation) { String validation = "Number of validation set samples for scoring: " + (fullvalid ? "all" : "") + score_valid; if (score_valid > 0) { if (score_valid < 1000 && model_info().get_params().validation.numRows() >= 1000) validation += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)"; if (score_valid > 100000) validation += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)"; } DocGen.HTML.section(sb, validation); } // String training = "Number of training set samples for scoring: " + error.score_training; if (error.validation) { // String validation = "Number of validation set samples for scoring: " + error.score_validation; } sb.append("<table class='table table-striped table-bordered table-condensed'>"); sb.append("<tr>"); sb.append("<th>Training Time</th>"); sb.append("<th>Training Epochs</th>"); sb.append("<th>Training Samples</th>"); if (isClassifier()) { // sb.append("<th>Training MCE</th>"); sb.append("<th>Training Error</th>"); } else { sb.append("<th>Training MSE</th>"); } if (error.validation) { if (isClassifier()) { // sb.append("<th>Validation MCE</th>"); sb.append("<th>Validation Error</th>"); } else { sb.append("<th>Validation MSE</th>"); } } sb.append("</tr>"); for( int i = errors.length - 1; i >= 0; i-- ) { final Errors e = errors[i]; sb.append("<tr>"); sb.append("<td>" + PrettyPrint.msecs(e.training_time_ms, true) + "</td>"); sb.append("<td>" + String.format("%g", e.epoch_counter) + "</td>"); sb.append("<td>" + String.format("%,d", e.training_samples) + "</td>"); if (isClassifier()) { // sb.append("<td>" + String.format(cross_entropy_format, e.train_mce) + "</td>"); sb.append("<td>" + formatPct(e.train_err) + "</td>"); } else { sb.append("<td>" + String.format(mse_format, e.train_mse) + "</td>"); } if(e.validation) { if (isClassifier()) { // sb.append("<td>" + String.format(cross_entropy_format, e.valid_mce) + "</td>"); sb.append("<td>" + formatPct(e.valid_err) + "</td>"); } else { sb.append("<td>" + String.format(mse_format, e.valid_mse) + "</td>"); } } sb.append("</tr>"); } sb.append("</table>"); return true; }
public boolean generateHTML(String title, StringBuilder sb) { if (_key == null) { DocGen.HTML.title(sb, "No model yet"); return true; } final String mse_format = "%2.6f"; final String cross_entropy_format = "%2.6f"; DocGen.HTML.title(sb, title); DocGen.HTML.paragraph(sb, "Model type: " + (model_info().parameters.classification ? " Classification" : " Regression")); DocGen.HTML.paragraph(sb, "Model Key: " + _key); DocGen.HTML.paragraph(sb, "Job Key: " + jobKey); Inspect2 is2 = new Inspect2(); DocGen.HTML.paragraph(sb, "Training Data Key: " + _dataKey); if (model_info.parameters.validation != null) { DocGen.HTML.paragraph(sb, "Validation Data Key: " + model_info.parameters.validation._key); } DocGen.HTML.paragraph(sb, "Number of model parameters (weights/biases): " + String.format("%,d", model_info().size())); model_info.job().toHTML(sb); sb.append("<div class='alert'>Actions: " + (Job.isRunning(jobKey) ? Cancel.link(jobKey, "Cancel job") + ", " : "") + is2.link("Inspect training data", _dataKey) + ", " + (model_info().parameters.validation != null ? (is2.link("Inspect validation data", model_info().parameters.validation._key) + ", ") : "") + water.api.Predict.link(_key, "Score on dataset") + ", " + NN.link(_dataKey, "Compute new model") + "</div>"); // stats for training and validation final Errors error = errors[errors.length - 1]; assert(error != null); if (errors.length > 1) { if (isClassifier()) { // Plot training error float[] err = new float[errors.length]; float[] samples = new float[errors.length]; for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].train_err; samples[i] = errors[i].training_samples; } new D3Plot(samples, err, "training samples", "classification error", "Classification Error on Training Set").generate(sb); // Plot validation error if (model_info.parameters.validation != null) { for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].valid_err; } new D3Plot(samples, err, "training samples", "classification error", "Classification Error on Validation Set").generate(sb); } } else { // Plot training MSE float[] err = new float[errors.length]; float[] samples = new float[errors.length]; for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].train_mse; samples[i] = errors[i].training_samples; } new D3Plot(samples, err, "training samples", "mean squared error", "Regression Error on Training Set").generate(sb); // Plot validation MSE if (model_info.parameters.validation != null) { for (int i=0; i<err.length; ++i) { err[i] = (float)errors[i].valid_mse; } new D3Plot(samples, err, "training samples", "mean squared error", "Regression Error on Validation Set").generate(sb); } } } if (isClassifier()) { DocGen.HTML.section(sb, "Training classification error: " + formatPct(error.train_err)); // DocGen.HTML.section(sb, "Training cross entropy: " + String.format(cross_entropy_format, error.train_mce)); if(error.validation) { DocGen.HTML.section(sb, "Validation classification error: " + formatPct(error.valid_err)); // DocGen.HTML.section(sb, "Validation mean cross entropy: " + String.format(cross_entropy_format, error.valid_mce)); } } else { DocGen.HTML.section(sb, "Training mean square error: " + String.format(mse_format, error.train_mse)); if(error.validation) { DocGen.HTML.section(sb, "Validation mean square error: " + String.format(mse_format, error.valid_mse)); } } if (error.training_time_ms > 0) DocGen.HTML.section(sb, "Training speed: " + error.training_samples * 1000 / error.training_time_ms + " samples/s"); if (model_info.parameters != null && model_info.parameters.diagnostics) { DocGen.HTML.section(sb, "Status of Neuron Layers"); sb.append("<table class='table table-striped table-bordered table-condensed'>"); sb.append("<tr>"); sb.append("<th>").append("#").append("</th>"); sb.append("<th>").append("Units").append("</th>"); sb.append("<th>").append("Type").append("</th>"); sb.append("<th>").append("Dropout").append("</th>"); sb.append("<th>").append("Rate").append("</th>"); sb.append("<th>").append("L1").append("</th>"); sb.append("<th>").append("L2").append("</th>"); sb.append("<th>").append("Momentum").append("</th>"); sb.append("<th>").append("Weight (Mean, RMS)").append("</th>"); sb.append("<th>").append("Bias (Mean, RMS)").append("</th>"); sb.append("</tr>"); Neurons[] neurons = NNTask.makeNeuronsForTesting(model_info()); //link the weights to the neurons, for easy access for (int i=0; i<neurons.length; ++i) { sb.append("<tr>"); sb.append("<td>").append("<b>").append(i+1).append("</b>").append("</td>"); sb.append("<td>").append("<b>").append(neurons[i].units).append("</b>").append("</td>"); sb.append("<td>").append(neurons[i].getClass().getSimpleName()).append("</td>"); if (i == 0) { sb.append("<td>"); sb.append(formatPct(neurons[i].params.input_dropout_ratio)); sb.append("</td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); sb.append("<td></td>"); continue; } else if (i < neurons.length-1) { sb.append("<td>"); sb.append( neurons[i] instanceof Neurons.TanhDropout || neurons[i] instanceof Neurons.RectifierDropout || neurons[i] instanceof Neurons.MaxoutDropout ? "50%" : "0%"); sb.append("</td>"); } else { sb.append("<td></td>"); } sb.append("<td>").append(String.format("%.5g", neurons[i].rate(error.training_samples))).append("</td>"); sb.append("<td>").append(neurons[i].params.l1).append("</td>"); sb.append("<td>").append(neurons[i].params.l2).append("</td>"); final String format = "%g"; sb.append("<td>").append(String.format("%.5f", neurons[i].momentum(error.training_samples))).append("</td>"); sb.append("<td>(").append(String.format(format, model_info.mean_weight[i])). append(", ").append(String.format(format, model_info.rms_weight[i])).append(")</td>"); sb.append("<td>(").append(String.format(format, model_info.mean_bias[i])). append(", ").append(String.format(format, model_info.rms_bias[i])).append(")</td>"); sb.append("</tr>"); } sb.append("</table>"); } if (model_info.unstable()) { final String msg = "Job was aborted due to observed numerical instability (exponential growth)." + " Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing."; DocGen.HTML.section(sb, "======================================================================================="); DocGen.HTML.section(sb, msg); DocGen.HTML.section(sb, "======================================================================================="); } long score_valid = error.score_validation_samples; long score_train = error.score_training_samples; final boolean fulltrain = score_train==0 || score_train == model_info().data_info()._adaptedFrame.numRows(); final boolean fullvalid = score_valid==0 || score_valid == model_info().get_params().validation.numRows(); if (isClassifier()) { final String cmTitle = "Confusion Matrix on " + (error.validation ? "Validation Data" + (fullvalid ? "" : " (" + score_valid + " samples)") : "Training Data" + (fulltrain ? "" : " (" + score_train + " samples)")); DocGen.HTML.section(sb, cmTitle); if (error.train_confusion_matrix != null) { if (error.train_confusion_matrix.cm != null && error.train_confusion_matrix.cm.length < 100) { if (error.validation && error.valid_confusion_matrix != null && error.valid_confusion_matrix.cm != null) error.valid_confusion_matrix.toHTML(sb); else if (error.train_confusion_matrix != null) error.train_confusion_matrix.toHTML(sb); } else { sb.append("<h5>Not shown here (too large).</h5>"); } } else sb.append("<h5>Not yet computed.</h5>"); } sb.append("<h3>" + "Progress" + "</h3>"); sb.append("<h4>" + "Epochs: " + String.format("%.3f", epoch_counter) + "</h4>"); String training = "Number of training set samples for scoring: " + (fulltrain ? "all " + model_info().data_info()._adaptedFrame.numRows() : score_train); if (score_train > 0) { if (score_train < 1000 && model_info().data_info()._adaptedFrame.numRows() >= 1000) training += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)"; if (score_train > 100000) training += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)"; } DocGen.HTML.section(sb, training); if (error.validation) { String validation = "Number of validation set samples for scoring: " + (fullvalid ? "all " + model_info().get_params().validation.numRows() : score_valid); if (score_valid > 0) { if (score_valid < 1000 && model_info().get_params().validation.numRows() >= 1000) validation += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)"; if (score_valid > 100000) validation += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)"; } DocGen.HTML.section(sb, validation); } // String training = "Number of training set samples for scoring: " + error.score_training; if (error.validation) { // String validation = "Number of validation set samples for scoring: " + error.score_validation; } sb.append("<table class='table table-striped table-bordered table-condensed'>"); sb.append("<tr>"); sb.append("<th>Training Time</th>"); sb.append("<th>Training Epochs</th>"); sb.append("<th>Training Samples</th>"); if (isClassifier()) { // sb.append("<th>Training MCE</th>"); sb.append("<th>Training Error</th>"); } else { sb.append("<th>Training MSE</th>"); } if (error.validation) { if (isClassifier()) { // sb.append("<th>Validation MCE</th>"); sb.append("<th>Validation Error</th>"); } else { sb.append("<th>Validation MSE</th>"); } } sb.append("</tr>"); for( int i = errors.length - 1; i >= 0; i-- ) { final Errors e = errors[i]; sb.append("<tr>"); sb.append("<td>" + PrettyPrint.msecs(e.training_time_ms, true) + "</td>"); sb.append("<td>" + String.format("%g", e.epoch_counter) + "</td>"); sb.append("<td>" + String.format("%,d", e.training_samples) + "</td>"); if (isClassifier()) { // sb.append("<td>" + String.format(cross_entropy_format, e.train_mce) + "</td>"); sb.append("<td>" + formatPct(e.train_err) + "</td>"); } else { sb.append("<td>" + String.format(mse_format, e.train_mse) + "</td>"); } if(e.validation) { if (isClassifier()) { // sb.append("<td>" + String.format(cross_entropy_format, e.valid_mce) + "</td>"); sb.append("<td>" + formatPct(e.valid_err) + "</td>"); } else { sb.append("<td>" + String.format(mse_format, e.valid_mse) + "</td>"); } } sb.append("</tr>"); } sb.append("</table>"); return true; }
diff --git a/org.touge.restclient/src/org/touge/restclient/ReSTClient.java b/org.touge.restclient/src/org/touge/restclient/ReSTClient.java index 9770a68..38a5127 100644 --- a/org.touge.restclient/src/org/touge/restclient/ReSTClient.java +++ b/org.touge.restclient/src/org/touge/restclient/ReSTClient.java @@ -1,1396 +1,1396 @@ /* * This file is in the public domain, furnished "as is", without technical * support, and with no warranty, express or implied, as to its usefulness for * any purpose. */ package org.touge.restclient; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; /** * A client library for accessing resources via HTTP. * * @author kgilmer * */ public class ReSTClient { private static final String HEADER_CONTENT_TYPE = "Content-Type"; private static final String APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; private static final int COPY_BUFFER_SIZE = 1024 * 4; private static final int RANDOM_CHAR_COUNT = 15; private static final String HEADER_TYPE = HEADER_CONTENT_TYPE; private static final String HEADER_PARA = "Content-Disposition: form-data"; private static final String MULTIPART_FORM_DATA_CONTENT_TYPE = "multipart/form-data"; private static final String FILE_NAME = "filename"; private static final String LINE_ENDING = "\r\n"; private static final String BOUNDARY = "boundary="; private static final String PARA_NAME = "name"; private static final Map<Integer, String> HTTP_RESPONSE_TEXT = createResponseMap(); /** * HTTP methods supported by REST client. * */ public enum HttpMethod { GET, POST, PUT, DELETE, HEAD } /** * implement to provide an HttpURLConnection w/ some properties pre-set see * BasicAuthenticationConnectionProvider for an example. * * This is passed into HttpRequest on creation to provide it w/ the connection * * @author bballantine * */ public interface ConnectionProvider { /** * @param urlStr url that is used to source the connection * @return an appropriate instance of HttpURLConnection * @throws IOException on I/O error. */ HttpURLConnection getConnection(String urlStr) throws IOException; } /** * Implementors can configure the http connection before every call is made. * Useful for setting headers that always need to be present in every WS * call to a given server. * */ public interface ConnectionInitializer { /** * @param connection * HttpURLConnection */ void initialize(HttpURLConnection connection); } /** * Utility interface for building URLs from String segments. */ public interface URLBuilder extends Cloneable { /** * Append a segment to the URL. Will handle leading and trailing slashes, and schemes. * * @param segment to be appended * @return instance of builder */ URLBuilder append(String ... segment); /** * @param value if true, scheme is set to https, otherwise http. * @return instance of builder */ URLBuilder setHttps(boolean value); /** * @return URL as a String with scheme */ String toString(); /** * @return A new instance of URLBuilder with same path and scheme as parent. */ URLBuilder copy(); /** * @param segments new segment to append to new copy of URLBuilder * @return A new instance of URLBuilder with same path and scheme as parent, with segment appended. */ URLBuilder copy(String ... segments); } /** * * * @param <T> */ public interface ResponseDeserializer<T> { /** * Deserialize the input. * @param input input stream of response * @param responseCode HTTP response from server * @param headers HTTP response headers * @return deserialized representation of response * @throws IOException on I/O error */ T deserialize(InputStream input, int responseCode, Map<String, List<String>> headers) throws IOException; } /** * A HTTPResponseDeserializer that returns the entire response as a String. */ public static final ResponseDeserializer<String> STRING_DESERIALIZER = new ResponseDeserializer<String>() { @Override public String deserialize(InputStream input, int responseCode, Map<String, List<String>> headers) throws IOException { if (input != null) return new String(readStream(input)); return null; } }; /** * A HTTPResponseDeserializer that returns true if the response from the server was not an error. */ public static final ResponseDeserializer<Integer> HTTP_CODE_DESERIALIZER = new ResponseDeserializer<Integer>() { @Override public Integer deserialize(InputStream input, int responseCode, Map<String, List<String>> headers) throws IOException { return responseCode; } }; /** * A HTTPResponseDeserializer that simply returns the internal inputstream. * Useful for clients that wish to handle the response input stream manually. */ public static final ResponseDeserializer<InputStream> INPUTSTREAM_DESERIALIZER = new ResponseDeserializer<InputStream>() { @Override public InputStream deserialize(InputStream input, int responseCode, Map<String, List<String>> headers) throws IOException { return input; } }; /** * */ public static final ErrorHandler THROW_ALL_ERRORS = new ErrorHandler() { @Override public void handleError(int code) throws IOException { if (code > 0) throw new IOException("HTTP Error " + code + " was returned from the server: " + HTTP_RESPONSE_TEXT.get(code)); else throw new IOException("A non-HTTP error was returned from the server."); } }; /** * */ public static final ErrorHandler THROW_5XX_ERRORS = new ErrorHandler() { @Override public void handleError(int code) throws IOException { if (code > 499 && code < 600) throw new IOException("HTTP Error " + code + " was returned from the server: " + HTTP_RESPONSE_TEXT.get(code)); } }; /** * The response from the server for a given request. * * @param <T> */ public interface Response<T> { /** * Cancel the request. * * @param mayInterruptIfRunning * @return */ public abstract boolean cancel(boolean mayInterruptIfRunning); /** * @return true if the request has been canceled */ public abstract boolean isCancelled(); /** * @return true if the request has been completed */ public abstract boolean isDone(); /** * @return the content (body) of the response. * * @throws IOException */ public abstract T getContent() throws IOException; /** * @return The HttpURLConnection associated with the request. */ HttpURLConnection getConnection(); /** * @return The HTTP method that was used in the call. */ HttpMethod getRequestMethod(); /** * @return The URL that was used in the call. */ String getRequestUrl(); /** * @return The HTTP Response code from the server. * @throws IOException on I/O error. */ int getCode() throws IOException; /** * @return true if error code or an exception is raised, false otherwise. */ boolean isError(); } /** * The ErrorHander does something based on an HTTP or I/O error. * */ public interface ErrorHandler { /** * @param code the HTTP code of the error * @throws IOException on I/O error */ void handleError(int code) throws IOException; } /** * Used to specify a file to upload in a multipart POST. * */ public static class FormFile extends File { private static final long serialVersionUID = 2957338960806476533L; private final String mimeType; /** * @param pathname */ public FormFile(String pathname, String mimeType) { super(pathname); this.mimeType = mimeType; } /** * @return Mime type of file. */ public String getMimeType() { return mimeType; } } /** * Used to specify a file to upload in a multipart POST. * */ public static class FormInputStream extends InputStream { private static final long serialVersionUID = 2957338960806476533L; private final String mimeType; private final InputStream parent; private final String name; /** * @param parent Input stream of file * @param name name of file * @param mimeType mimetype for content of file */ public FormInputStream(InputStream parent, String name, String mimeType) { this.parent = parent; this.name = name; this.mimeType = mimeType; } /** * @return Mime type of file. */ public String getMimeType() { return mimeType; } @Override public int read() throws IOException { return parent.read(); } @Override public int read(byte[] b) throws IOException { return parent.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return parent.read(b, off, len); } /** * @return name of content */ public String getName() { return name; } } private static Random RNG; private ConnectionProvider connectionProvider; private List<ConnectionInitializer> connectionInitializers; private ErrorHandler errorHandler; private OutputStream debugStream; private StringBuilder debugBuffer; /** * Default constructor. */ public ReSTClient() { this.connectionProvider = new DefaultConnectionProvider(); this.connectionInitializers = new ArrayList<ConnectionInitializer>(); this.errorHandler = null; } /** * @param connectionProvider ConnectionProvider */ public ReSTClient(ConnectionProvider connectionProvider) { this.connectionProvider = connectionProvider; this.connectionInitializers = new ArrayList<ConnectionInitializer>(); this.errorHandler = null; } /** * @param initializer ConnectionInitializer */ public ReSTClient(ConnectionInitializer initializer) { this(); connectionInitializers.add(initializer); } /** * @param connectionProvider ConnectionProvider * @param initializer ConnectionInitializer */ public ReSTClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer) { this(connectionProvider); connectionInitializers.add(initializer); } /** * @param initializer ConnectionInitializer * @param deserializer ResponseDeserializer<T> */ public ReSTClient(ConnectionInitializer initializer, ResponseDeserializer<?> deserializer) { this(initializer); } /** * @param connectionProvider ConnectionProvider * @param initializer ConnectionInitializer * @param deserializer ResponseDeserializer<T> */ public ReSTClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer, ResponseDeserializer<?> deserializer) { this(connectionProvider, initializer); } /** * @param connectionProvider ConnectionProvider * @param initializer ConnectionInitializer * @param deserializer ResponseDeserializer<T> * @param errorHandler ErrorHandler */ public ReSTClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer, ResponseDeserializer<?> deserializer, ErrorHandler errorHandler) { this.connectionProvider = connectionProvider; this.connectionInitializers = new ArrayList<ConnectionInitializer>(); this.errorHandler = errorHandler; connectionInitializers.add(initializer); } /** * @param connectionProvider ConnectionProvider * @param initializer ConnectionInitializer * @param deserializer ResponseDeserializer<T> * @param errorHandler ErrorHandler * @param debugStream OutputStream to pass debug messages to. If null, no debug output. */ public ReSTClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer, ResponseDeserializer<?> deserializer, ErrorHandler errorHandler, OutputStream debugStream) { this.connectionProvider = connectionProvider; this.connectionInitializers = new ArrayList<ConnectionInitializer>(); this.errorHandler = errorHandler; this.debugStream = debugStream; connectionInitializers.add(initializer); } // Public methods /** * @return ErrorHandler */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * Sets an error handler for the client. If no error handler is set, HTTP (application level) errors will be ignored * by the client. * * Creating a custom ErrorHandler let's the client handle specific errors from the server in an application specific way. * * See also: THROW_ALL_ERRORS, THROW_5XX_ERRORS * * @param handler ErrorHandler */ public void setErrorHandler(ErrorHandler handler) { this.errorHandler = handler; } /** * Sets a debug OutputStream for the client. If null is passed, no debug output * will be generated. * * @param debugStream OutputStream */ public void setDebugStream(OutputStream debugStream) { this.debugStream = debugStream; } /** * @param provider ConnectionProvider */ public void setConnectionProvider(ConnectionProvider provider) { this.connectionProvider = provider; } /** * @return ConnectionProvider */ public ConnectionProvider getConnectionProvider() { return connectionProvider; } /** * @param initializer */ public void addConnectionInitializer(ConnectionInitializer initializer) { if (!connectionInitializers.contains(initializer)) connectionInitializers.add(initializer); } /** * @param initializer ConnectionInitializer * @return ConnectionInitializer */ public boolean removeConnectionInitializer(ConnectionInitializer initializer) { return connectionInitializers.remove(initializer); } /** * This is the primary call in RestClient. All other HTTP method calls call this method with some specific parameters. * For flexibility this method is exposed to clients but should not be used in a majority of cases. See callGet(), * callPost() etc. for the simplest usage. This call is asynchronous, the Response works like a Future. * * This method handles errors based on how the client is configured. If no Deserializer or ErrorHander is specified * the response content will produce null. The response class will contain the HTTP error information. * * @param method HTTP method. Cannot be null. * @param url url of server. Cannot be null. * @param deserializer class to deserialize the response body. If null then response is deserialized to a String. * @param content Optional content to pass to server, can be null. * @param headers HTTP headers that should be appended to the call. These are in addition to any headers set * in any ConnectionInitializers associated with client. * @param <T> type to deserialize to * @return deserialized response * @throws IOException on I/O error */ public <T> Response<T> call(final HttpMethod method, final String url, final ResponseDeserializer<T> deserializer, InputStream content, Map<String, String> headers) throws IOException { validateArguments(method, url); String httpUrl = url; if (!url.toLowerCase().startsWith("http://")) httpUrl = "http://" + url; if (debugStream != null) debugStart(httpUrl); final HttpURLConnection connection = connectionProvider.getConnection(httpUrl); connection.setRequestMethod(method.toString()); if (debugStream != null) debugMid(method.toString()); for (ConnectionInitializer initializer : connectionInitializers) initializer.initialize(connection); if (headers != null && headers.size() > 0) for (Map.Entry<String, String> entry : headers.entrySet()) connection.addRequestProperty(entry.getKey(), entry.getValue()); ByteArrayOutputStream baos; switch(method) { case GET: connection.setDoInput(true); connection.setDoOutput(false); break; case POST: connection.setDoOutput(true); baos = new ByteArrayOutputStream(); copy(content, baos); writeRequestBody(connection, baos.toByteArray()); baos.close(); if (debugStream != null) debugMid(new String(baos.toByteArray())); break; case PUT: connection.setDoOutput(true); baos = new ByteArrayOutputStream(); copy(content, baos); writeRequestBody(connection, baos.toByteArray()); baos.close(); if (debugStream != null) debugMid(new String(baos.toByteArray())); break; case DELETE: connection.setDoInput(true); break; case HEAD: connection.setDoInput(true); connection.setDoOutput(false); break; default: throw new RuntimeException("Unhandled HTTP method."); } if (debugStream != null) debugEnd(); return new Response<T>() { private boolean done; private boolean cancelled; @Override public int getCode() throws IOException { return connection.getResponseCode(); } @Override public String getRequestUrl() { return url; } @Override public HttpMethod getRequestMethod() { return method; } @Override public HttpURLConnection getConnection() { return connection; } @Override public boolean isError() { int code; try { code = getCode(); return code >= HttpURLConnection.HTTP_BAD_REQUEST && code < HttpURLConnection.HTTP_VERSION; } catch (IOException e) { return true; } } @Override public boolean cancel(boolean flag) { connection.disconnect(); cancelled = true; return cancelled; } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isDone() { return done; } @Override public T getContent() throws IOException { if (isError()) { if (errorHandler != null) errorHandler.handleError(getCode()); if (deserializer != null) - return (T) deserializer.deserialize(null, connection.getResponseCode(), + return (T) deserializer.deserialize(connection.getErrorStream(), connection.getResponseCode(), connection.getHeaderFields()); return null; } if (deserializer == null) { // If no deserializer is specified, use String. T response = (T) ReSTClient.STRING_DESERIALIZER.deserialize(connection.getInputStream(), 0, null); done = true; return (T) response; } T response = (T) deserializer.deserialize(connection.getInputStream(), connection.getResponseCode(), connection.getHeaderFields()); done = true; return response; } }; } private void debugStart(String httpUrl) { debugBuffer = new StringBuilder(); debugBuffer.append(this.getClass().getSimpleName()); debugBuffer.append(' '); debugBuffer.append(System.currentTimeMillis()); debugBuffer.append(' '); debugBuffer.append(httpUrl); debugBuffer.append(' '); } private void debugMid(String element) { debugBuffer.append(element); debugBuffer.append(' '); } private void debugEnd() { debugBuffer.append('\n'); try { debugStream.write(debugBuffer.toString().getBytes()); debugStream.flush(); } catch (IOException e) { } } /** * Execute GET method and return body as a string. This call blocks * until the response content is deserialized into a String. * * @param url of server. If not String, toString() will be called. * @return body as a String * @throws IOException on I/O error */ public String callGet(Object url) throws IOException { return callGetContent(url.toString(), STRING_DESERIALIZER); } /** * Execute GET method and return body deserizalized. This call * blocks until the response body content is deserialized. * * @param url of server. If not String, toString() will be called. * @param deserializer ResponseDeserializer * @return T deserialized object * @throws IOException on I/O error */ public <T> T callGetContent(Object url, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.GET, url.toString(), deserializer, null, null).getContent(); } /** * Execute GET method and deserialize response. * * @param url of server If not String, toString() will be called. * @param deserializer class that can deserialize content into desired type. * @return type specified by deserializer * @throws IOException on I/O error */ public <T> Response<T> callGet(Object url, Map<String, String> headers, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.GET, url.toString(), deserializer, null, headers); } /** * Execute GET method and deserialize response. * * @param url of server. If not String, toString() will be called. * @param deserializer class that can deserialize content into desired type. * @return type specified by deserializer * @throws IOException on I/O error */ public <T> Response<T> callGet(Object url, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.GET, url.toString(), deserializer, null, null); } /** * Send a POST to the server. * * @param url url of server. If not String, toString() will be called. * @param body body of post as an input stream * @return a response to the request * @throws IOException on I/O error */ public Response<Integer> callPost(Object url, InputStream body) throws IOException { return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER, body, null); } /** * Send a POST to the server. * * @param url url of server. If not String, toString() will be called. * @param body body of post as a String * @return a response to the request * @throws IOException on I/O error */ public Response<Integer> callPost(Object url, String body) throws IOException { return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER, new ByteArrayInputStream(body.getBytes()), null); } /** * Send a POST to the server. * * @param url url of server * @param formData Form data as strings. * @return a response from the POST * @throws IOException on I/O error */ public Response<Integer> callPost(Object url, Map<String, String> formData) throws IOException { return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER, new ByteArrayInputStream(propertyString(formData).getBytes()), toMap(HEADER_CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)); } /** * Send a POST to the server. * * @param url url of server * @param body body of post as an input stream * @return a response to the request * @throws IOException on I/O error */ public <T> Response<T> callPost(Object url, InputStream body, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.POST, url.toString(), deserializer, body, null); } /** * Send a POST to the server. * * @param url url of server. If not String, toString() will be called. * @param formData Form data as strings. * @return a response from the POST * @throws IOException on I/O error */ public <T> Response<T> callPost(Object url, Map<String, String> formData, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.POST, url.toString(), deserializer, new ByteArrayInputStream(propertyString(formData).getBytes()), toMap(HEADER_CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)); } /** * Send a multipart POST to the server. Convenience method for post(url, createMultipartPostBody(content)). * * @param url url of server. If not String, toString() will be called. * @param content See createMultipartPostBody() for details on this parameter. * @return a response from the POST * @throws IOException on I/O error */ public Response<Integer> callPostMultipart(Object url, Map<String, Object> content) throws IOException { String boundary = createMultipartBoundary(); String contentType = MULTIPART_FORM_DATA_CONTENT_TYPE + "; " + BOUNDARY + boundary; return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER, createMultipartPostBody(boundary, content), toMap(HEADER_CONTENT_TYPE, contentType)); } /** * Send a multipart POST to the server. Convenience method for post(url, createMultipartPostBody(content)). * * @param url url of server. If not String, toString() will be called. * @param content See createMultipartPostBody() for details on this parameter. * @param deserializer class that can deserialize content into desired type. * @param <T> Type to be deserialized to. * @return a response from the POST * @throws IOException on I/O error */ public <T> Response<T> callPostMultipart(Object url, Map<String, Object> content, ResponseDeserializer<T> deserializer) throws IOException { String boundary = createMultipartBoundary(); String contentType = MULTIPART_FORM_DATA_CONTENT_TYPE + "; " + BOUNDARY + boundary; return call(HttpMethod.POST, url.toString(), deserializer, createMultipartPostBody(boundary, content), toMap(HEADER_CONTENT_TYPE, contentType)); } /** * Call PUT method on a server. * * @param url url of server * @param content See createMultipartPostBody() for details on this parameter. * @return a response from the POST * @throws IOException on I/O error */ public Response<Integer> callPut(Object url, InputStream content) throws IOException { return call(HttpMethod.PUT, url.toString(), HTTP_CODE_DESERIALIZER, content, null); } /** * Send a POST to the server. * * @param url url of server * @param formData Form data as strings. * @return a response from the POST * @throws IOException on I/O error */ public Response<Integer> callPut(Object url, Map<String, String> formData) throws IOException { return call(HttpMethod.PUT, url.toString(), HTTP_CODE_DESERIALIZER, new ByteArrayInputStream(propertyString(formData).getBytes()), toMap(HEADER_CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)); } /** * Call PUT method on a server. * * @param url url of server * @param content See createMultipartPostBody() for details on this parameter. * @return a response from the POST * @throws IOException on I/O error */ public <T> Response<T> callPut(Object url, InputStream content, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.PUT, url.toString(), deserializer, content, null); } /** * Send a POST to the server. * * @param url url of server * @param formData Form data as strings. * @return a response from the POST * @throws IOException on I/O error */ public <T> Response<T> callPut(Object url, Map<String, String> formData, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.PUT, url.toString(), deserializer, new ByteArrayInputStream(propertyString(formData).getBytes()), toMap(HEADER_CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)); } /** * Call DELETE method on a server. * * @param url of server. If not String, toString() will be called. * @return HTTP response from server * @throws IOException on I/O error */ public Response<Integer> callDelete(Object url) throws IOException { return call(HttpMethod.DELETE, url.toString(), HTTP_CODE_DESERIALIZER, null, null); } /** * Call DELETE method on a server. * * @param url of server. If not String, toString() will be called. * @return HTTP response from server * @throws IOException on I/O error */ public <T> Response<T> callDelete(Object url, ResponseDeserializer<T> deserializer) throws IOException { return call(HttpMethod.DELETE, url.toString(), deserializer, null, null); } /** * Call HEAD method on a server. * * @param url of server. If not String, toString() will be called. * @return HTTP Response from server * @throws IOException on I/O error */ public Response<Integer> callHead(Object url) throws IOException { return call(HttpMethod.HEAD, url.toString(), HTTP_CODE_DESERIALIZER, null, null); } // Public static methods /** * Create a buffer for a multi-part POST body, and return an input stream to the buffer. * * @param content A map of <String, Object> The values can either be of type String, RestClient.FormInputStream, or * type RestClient.FormFile. Other types will cause an IllegalArgumentException. * @return an input stream of buffer of POST body. * @throws IOException on I/O error. */ public static InputStream createMultipartPostBody(String boundary, Map<String, Object> content) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] header = getPartHeader(boundary); for (Map.Entry<String, Object> entry : content.entrySet()) { baos.write(header); baos.write(entry.getKey().getBytes()); baos.write('"'); if (entry.getValue() instanceof String) { baos.write(LINE_ENDING.getBytes()); baos.write(LINE_ENDING.getBytes()); baos.write(((String) entry.getValue()).getBytes()); } else if (entry.getValue() instanceof FormFile) { FormFile ffile = (FormFile) entry.getValue(); baos.write("; ".getBytes()); baos.write(FILE_NAME.getBytes()); baos.write("=\"".getBytes()); baos.write(ffile.getName().getBytes()); baos.write('"'); baos.write(LINE_ENDING.getBytes()); baos.write(HEADER_TYPE.getBytes()); baos.write(": ".getBytes()); baos.write(ffile.getMimeType().getBytes()); baos.write(';'); baos.write(LINE_ENDING.getBytes()); baos.write(LINE_ENDING.getBytes()); baos.write(readStream(new FileInputStream(ffile))); } else if (entry.getValue() instanceof FormInputStream) { FormInputStream ffile = (FormInputStream) entry.getValue(); baos.write("; ".getBytes()); baos.write(FILE_NAME.getBytes()); baos.write("=\"".getBytes()); baos.write(ffile.getName().getBytes()); baos.write('"'); baos.write(LINE_ENDING.getBytes()); baos.write(HEADER_TYPE.getBytes()); baos.write(": ".getBytes()); baos.write(ffile.getMimeType().getBytes()); baos.write(';'); baos.write(LINE_ENDING.getBytes()); baos.write(LINE_ENDING.getBytes()); baos.write(readStream(ffile)); } else if (entry.getValue() == null) { throw new IllegalArgumentException("Content value is null."); } else { throw new IllegalArgumentException("Unhandled type: " + entry.getValue().getClass().getName()); } baos.write(LINE_ENDING.getBytes()); } return new ByteArrayInputStream(baos.toByteArray()); } /** * Get the general response text associated with an HTTP Response code. * * @param httpResponseCode HTTP code, ex 404 * @return Short description of response or null if invalid or unknown code. */ public static String getHttpResponseText(int httpResponseCode) { return HTTP_RESPONSE_TEXT.get(httpResponseCode); } /** * Build a URL with the URLBuilder utility interface. This interface * will clean extra/missing path segment terminators and handle schemes. * * @param segment set of segments that compose the url. * @return an instance of URLBuilder with complete url. */ public URLBuilder buildURL(String ... segment) { URLBuilderImpl builder = new URLBuilderImpl(); if (segment != null) if (segment.length == 0) return builder; else if (segment.length == 1) return builder.append(segment[0]); else for (String seg : segment) builder.append(seg); return builder; } /** * @param boundary String that represents form part boundary. * @return byte array of String of part header. */ private static byte[] getPartHeader(String boundary) { StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(boundary); sb.append(LINE_ENDING); sb.append(HEADER_PARA); sb.append("; "); sb.append(PARA_NAME); sb.append("=\""); return sb.toString().getBytes(); } /** * Turns a map into a key=value property string. * * @param props * Map of <String, String> properties * @return A querystring as String * @throws IOException * on string encoding error */ public static String propertyString(Map<String, String> props) throws IOException { StringBuilder sb = new StringBuilder(); for (Iterator<String> i = props.keySet().iterator(); i.hasNext();) { String key = i.next(); sb.append(URLEncoder.encode(key, "UTF-8")); sb.append("="); sb.append(URLEncoder.encode((String) props.get(key), "UTF-8")); if (i.hasNext()) { sb.append("&"); } } return sb.toString(); } /** * Given a variable number of <String, String> pairs, construct a Map and * return it with values loaded. * * @param elements * name1, value1, name2, value2... * @return a Map and return it with values loaded. */ public static Map<String, String> toMap(String... elements) { if (elements.length % 2 != 0) { throw new IllegalStateException("Input parameters must be even."); } Iterator<String> i = Arrays.asList(elements).iterator(); Map<String, String> m = new HashMap<String, String>(); while (i.hasNext()) { m.put(i.next().toString(), i.next()); } return m; } // Private methods /** * Create an array of bytesfrom the complete contents of an InputStream. * * @param in * InputStream to turn into a byte array * @return byte array (byte[]) w/ contents of input stream, or null if inputstream is null. * @throws IOException * on I/O error */ public static byte[] readStream(InputStream in) throws IOException { if (in == null) return null; ByteArrayOutputStream os = new ByteArrayOutputStream(); int read = 0; byte[] buff = new byte[COPY_BUFFER_SIZE]; while ((read = in.read(buff)) > 0) { os.write(buff, 0, read); } os.close(); return os.toByteArray(); } /** * Create multipart form boundary. * * @return boiundry as a String */ private static String createMultipartBoundary() { if (RNG == null) RNG = new Random(); StringBuilder buf = new StringBuilder(42); buf.append("---------------------------"); for (int i = 0; i < RANDOM_CHAR_COUNT; i++) { if (RNG.nextBoolean()) buf.append((char) (RNG.nextInt(25) + 65)); else buf.append((char) (RNG.nextInt(25) + 98)); } return buf.toString(); } /** * Create a byte array from the contents of an input stream. * * @param inputStream * InputStream to read from * @param outputStream * OutputStream to write to * @return number of bytes copied * @throws IOException * on I/O error */ private static long copy(InputStream inputStream, OutputStream outputStream) throws IOException { int read = 0; long size = 0; byte[] buff = new byte[COPY_BUFFER_SIZE]; while ((read = inputStream.read(buff)) > 0) { outputStream.write(buff, 0, read); size += read; } outputStream.flush(); return size; } /** * Throws an IllegalArgumentException if any input parameters are null. * * @param args list of parameters. */ private static void validateArguments(Object ... args) { for (int i = 0; i < args.length; ++i) if (args[i] == null) throw new IllegalArgumentException("An input parameter is null."); } /** * The default connection provider returns a HttpUrlConnection. */ private class DefaultConnectionProvider implements ConnectionProvider { /* (non-Javadoc) * @see com.buglabs.util.http.RestClient.ConnectionProvider#getConnection(java.lang.String) */ public HttpURLConnection getConnection(String urlStr) throws IOException { URL url = new URL(urlStr); return (HttpURLConnection) url.openConnection(); } } /** * Write the content to the request body. * @param connection associated with request * @param content content of request. If null, no body is sent and HTTP header Content-Length is set to zero. * @throws IOException on I/O error. */ private void writeRequestBody(HttpURLConnection connection, byte[] content) throws IOException { if (content != null) { connection.setRequestProperty("Content-Length", Long.toString(content.length)); OutputStream outputStream = connection.getOutputStream(); outputStream.write(content); outputStream.close(); } else { connection.setRequestProperty("Content-Length", Long.toString(0)); } } /** * URLBuilder Implementation for safely composing URLs. */ private final class URLBuilderImpl implements URLBuilder { private final List<String> segments; private boolean httpsScheme; /** * */ public URLBuilderImpl() { segments = new ArrayList<String>(); httpsScheme = false; } /** * @param segments list of in-order segments that are used to build the url. * @param httpsScheme true if HTTPS should be used, false otherwise. */ private URLBuilderImpl(List<String> segments, boolean httpsScheme) { this.segments = segments; this.httpsScheme = httpsScheme; } @Override public URLBuilder append(String ... sgmnts) { validateArguments((Object []) sgmnts); if (sgmnts.length == 1) appendSingle(sgmnts[0]); else for (String segment : sgmnts) { appendSingle(segment); } return this; } /** * Append a single segment. * @param segment segment to append. * @return instance of URLBuilder with the new segment attached. */ private URLBuilder appendSingle(String segment) { segment = segment.trim(); if (segment.length() == 0) return this; else if (segment.indexOf('/', 1) > -1) { for (String nseg : segment.split("/")) this.append(nseg); } else if (segment.length() > 0) { if (segment.toUpperCase().startsWith("HTTP:")) return this; else if (segment.toUpperCase().startsWith("HTTPS:")) { httpsScheme = true; return this; } segments.add(stripIllegalChars(segment)); } return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (httpsScheme) sb.append("https://"); else sb.append("http://"); for (Iterator<String> i = segments.iterator(); i.hasNext();) { sb.append(i.next()); if (i.hasNext()) sb.append('/'); } return sb.toString(); } /** * Remove characters that should be removed from a segment before appending. * @param segment input segment * @return segment string without invalid characters. */ private String stripIllegalChars(String segment) { return segment.replaceAll("/", ""); } @Override public URLBuilder setHttps(boolean value) { httpsScheme = value; return this; } @Override protected Object clone() throws CloneNotSupportedException { return new URLBuilderImpl(new ArrayList<String>(segments), httpsScheme); } @Override public URLBuilder copy() { try { return (URLBuilder) this.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("Invalid state", e); } } @Override public URLBuilder copy(String ... segments) { validateArguments((Object []) segments); return this.copy().append(segments); } } /** * Create map of known HTTP response codes and their text labels. * * @return a Map<Integer, String> of responses */ private static Map<Integer, String> createResponseMap() { Map<Integer, String> responses = new HashMap<Integer, String>(); //Responses is a map, with error code as key, and a 2 dimensional String array with //header and HTML error response, segmented where a user error-defined can be specified. responses.put(Integer.valueOf(100), "Continue"); responses.put(Integer.valueOf(101), "Switching Protocols"); responses.put(Integer.valueOf(200), "OK"); responses.put(Integer.valueOf(201), "Created"); responses.put(Integer.valueOf(202), "Accepted"); responses.put(Integer.valueOf(203), "Non-Authoritative Information"); responses.put(Integer.valueOf(204), "No Content"); responses.put(Integer.valueOf(205), "Reset Content"); responses.put(Integer.valueOf(206), "Partial Content"); //TODO: Add all 3xx codes responses.put(Integer.valueOf(300), "Multiple Choices"); responses.put(Integer.valueOf(301), "Moved Permanently"); responses.put(Integer.valueOf(302), "Found"); responses.put(Integer.valueOf(307), "Temporary Redirect"); responses.put(Integer.valueOf(400), "Bad Request - HTTP 1.1 requests must include the Host: header."); responses.put(Integer.valueOf(401), "Unauthorized"); responses.put(Integer.valueOf(402), "Payment Required"); responses.put(Integer.valueOf(403), "Forbidden"); responses.put(Integer.valueOf(404), "Not Found"); responses.put(Integer.valueOf(405), "Method not Allowed"); responses.put(Integer.valueOf(406), "Not Acceptable"); responses.put(Integer.valueOf(407), "Proxy Authentication Required"); responses.put(Integer.valueOf(408), "Request Timeout"); responses.put(Integer.valueOf(409), "Conflict"); responses.put(Integer.valueOf(410), "Gone"); responses.put(Integer.valueOf(411), "Length Required"); responses.put(Integer.valueOf(412), "Precondition Failed"); responses.put(Integer.valueOf(413), "Request Entity too Large"); responses.put(Integer.valueOf(414), "Request-URI too Long"); responses.put(Integer.valueOf(415), "Unsupported Media Type"); responses.put(Integer.valueOf(416), "Requested Range not Satisfiable"); responses.put(Integer.valueOf(417), "Expectation Failed"); responses.put(Integer.valueOf(500), "Internal Server Error"); responses.put(Integer.valueOf(501), "Not Implemented"); responses.put(Integer.valueOf(502), "Bad Gateway"); responses.put(Integer.valueOf(503), "Service Unavailable"); responses.put(Integer.valueOf(504), "Gateway Timeout"); responses.put(Integer.valueOf(505), "HTTP Version not Supported"); return responses; } }
true
true
public <T> Response<T> call(final HttpMethod method, final String url, final ResponseDeserializer<T> deserializer, InputStream content, Map<String, String> headers) throws IOException { validateArguments(method, url); String httpUrl = url; if (!url.toLowerCase().startsWith("http://")) httpUrl = "http://" + url; if (debugStream != null) debugStart(httpUrl); final HttpURLConnection connection = connectionProvider.getConnection(httpUrl); connection.setRequestMethod(method.toString()); if (debugStream != null) debugMid(method.toString()); for (ConnectionInitializer initializer : connectionInitializers) initializer.initialize(connection); if (headers != null && headers.size() > 0) for (Map.Entry<String, String> entry : headers.entrySet()) connection.addRequestProperty(entry.getKey(), entry.getValue()); ByteArrayOutputStream baos; switch(method) { case GET: connection.setDoInput(true); connection.setDoOutput(false); break; case POST: connection.setDoOutput(true); baos = new ByteArrayOutputStream(); copy(content, baos); writeRequestBody(connection, baos.toByteArray()); baos.close(); if (debugStream != null) debugMid(new String(baos.toByteArray())); break; case PUT: connection.setDoOutput(true); baos = new ByteArrayOutputStream(); copy(content, baos); writeRequestBody(connection, baos.toByteArray()); baos.close(); if (debugStream != null) debugMid(new String(baos.toByteArray())); break; case DELETE: connection.setDoInput(true); break; case HEAD: connection.setDoInput(true); connection.setDoOutput(false); break; default: throw new RuntimeException("Unhandled HTTP method."); } if (debugStream != null) debugEnd(); return new Response<T>() { private boolean done; private boolean cancelled; @Override public int getCode() throws IOException { return connection.getResponseCode(); } @Override public String getRequestUrl() { return url; } @Override public HttpMethod getRequestMethod() { return method; } @Override public HttpURLConnection getConnection() { return connection; } @Override public boolean isError() { int code; try { code = getCode(); return code >= HttpURLConnection.HTTP_BAD_REQUEST && code < HttpURLConnection.HTTP_VERSION; } catch (IOException e) { return true; } } @Override public boolean cancel(boolean flag) { connection.disconnect(); cancelled = true; return cancelled; } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isDone() { return done; } @Override public T getContent() throws IOException { if (isError()) { if (errorHandler != null) errorHandler.handleError(getCode()); if (deserializer != null) return (T) deserializer.deserialize(null, connection.getResponseCode(), connection.getHeaderFields()); return null; } if (deserializer == null) { // If no deserializer is specified, use String. T response = (T) ReSTClient.STRING_DESERIALIZER.deserialize(connection.getInputStream(), 0, null); done = true; return (T) response; } T response = (T) deserializer.deserialize(connection.getInputStream(), connection.getResponseCode(), connection.getHeaderFields()); done = true; return response; } }; }
public <T> Response<T> call(final HttpMethod method, final String url, final ResponseDeserializer<T> deserializer, InputStream content, Map<String, String> headers) throws IOException { validateArguments(method, url); String httpUrl = url; if (!url.toLowerCase().startsWith("http://")) httpUrl = "http://" + url; if (debugStream != null) debugStart(httpUrl); final HttpURLConnection connection = connectionProvider.getConnection(httpUrl); connection.setRequestMethod(method.toString()); if (debugStream != null) debugMid(method.toString()); for (ConnectionInitializer initializer : connectionInitializers) initializer.initialize(connection); if (headers != null && headers.size() > 0) for (Map.Entry<String, String> entry : headers.entrySet()) connection.addRequestProperty(entry.getKey(), entry.getValue()); ByteArrayOutputStream baos; switch(method) { case GET: connection.setDoInput(true); connection.setDoOutput(false); break; case POST: connection.setDoOutput(true); baos = new ByteArrayOutputStream(); copy(content, baos); writeRequestBody(connection, baos.toByteArray()); baos.close(); if (debugStream != null) debugMid(new String(baos.toByteArray())); break; case PUT: connection.setDoOutput(true); baos = new ByteArrayOutputStream(); copy(content, baos); writeRequestBody(connection, baos.toByteArray()); baos.close(); if (debugStream != null) debugMid(new String(baos.toByteArray())); break; case DELETE: connection.setDoInput(true); break; case HEAD: connection.setDoInput(true); connection.setDoOutput(false); break; default: throw new RuntimeException("Unhandled HTTP method."); } if (debugStream != null) debugEnd(); return new Response<T>() { private boolean done; private boolean cancelled; @Override public int getCode() throws IOException { return connection.getResponseCode(); } @Override public String getRequestUrl() { return url; } @Override public HttpMethod getRequestMethod() { return method; } @Override public HttpURLConnection getConnection() { return connection; } @Override public boolean isError() { int code; try { code = getCode(); return code >= HttpURLConnection.HTTP_BAD_REQUEST && code < HttpURLConnection.HTTP_VERSION; } catch (IOException e) { return true; } } @Override public boolean cancel(boolean flag) { connection.disconnect(); cancelled = true; return cancelled; } @Override public boolean isCancelled() { return cancelled; } @Override public boolean isDone() { return done; } @Override public T getContent() throws IOException { if (isError()) { if (errorHandler != null) errorHandler.handleError(getCode()); if (deserializer != null) return (T) deserializer.deserialize(connection.getErrorStream(), connection.getResponseCode(), connection.getHeaderFields()); return null; } if (deserializer == null) { // If no deserializer is specified, use String. T response = (T) ReSTClient.STRING_DESERIALIZER.deserialize(connection.getInputStream(), 0, null); done = true; return (T) response; } T response = (T) deserializer.deserialize(connection.getInputStream(), connection.getResponseCode(), connection.getHeaderFields()); done = true; return response; } }; }
diff --git a/src/src/main/java/net/sprauer/sitzplaner/EA/operations/OperationGreedy.java b/src/src/main/java/net/sprauer/sitzplaner/EA/operations/OperationGreedy.java index 2900e69..fdb9064 100644 --- a/src/src/main/java/net/sprauer/sitzplaner/EA/operations/OperationGreedy.java +++ b/src/src/main/java/net/sprauer/sitzplaner/EA/operations/OperationGreedy.java @@ -1,65 +1,67 @@ package net.sprauer.sitzplaner.EA.operations; import java.awt.Point; import java.util.Collections; import java.util.Comparator; import java.util.Vector; import net.sprauer.sitzplaner.EA.Chromosome; import net.sprauer.sitzplaner.EA.EAOperation; import net.sprauer.sitzplaner.model.DataBase; import net.sprauer.sitzplaner.view.ClassRoom; import net.sprauer.sitzplaner.view.helper.Parameter; public class OperationGreedy extends EAOperation { private final Vector<Integer> studentsByPriority = new Vector<Integer>(); private final Vector<Point> lockedPositions = new Vector<Point>(); @Override public void invoke(Chromosome gene) throws Exception { fillAndSortStudents(gene); int x = 0; int y = Parameter.numRows - 1; while (!studentsByPriority.isEmpty()) { int student = getNextStudentByPriority(); final Point newPos = new Point(x, y); if (!positionIsAlreadyUsed(newPos)) { gene.setPositionOf(student, newPos); + } else { + studentsByPriority.insertElementAt(student, 0); } x += 1; if (x >= ClassRoom.instance().getDimensions().getWidth()) { x = 0; y -= 1; } } } private boolean positionIsAlreadyUsed(Point newPos) { return lockedPositions.contains(newPos); } private void fillAndSortStudents(Chromosome gene) { studentsByPriority.clear(); for (int i = 0; i < DataBase.instance().getSize(); i++) { if (DataBase.instance().getStudent(i).isLocked()) { gene.setPositionOf(i, DataBase.instance().getStudent(i).getLockPosition()); lockedPositions.add(DataBase.instance().getStudent(i).getLockPosition()); } else { studentsByPriority.add(i); } } Collections.sort(studentsByPriority, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return DataBase.instance().getPriority(o2) - DataBase.instance().getPriority(o1); } }); } private int getNextStudentByPriority() { return studentsByPriority.remove(0); } }
true
true
public void invoke(Chromosome gene) throws Exception { fillAndSortStudents(gene); int x = 0; int y = Parameter.numRows - 1; while (!studentsByPriority.isEmpty()) { int student = getNextStudentByPriority(); final Point newPos = new Point(x, y); if (!positionIsAlreadyUsed(newPos)) { gene.setPositionOf(student, newPos); } x += 1; if (x >= ClassRoom.instance().getDimensions().getWidth()) { x = 0; y -= 1; } } }
public void invoke(Chromosome gene) throws Exception { fillAndSortStudents(gene); int x = 0; int y = Parameter.numRows - 1; while (!studentsByPriority.isEmpty()) { int student = getNextStudentByPriority(); final Point newPos = new Point(x, y); if (!positionIsAlreadyUsed(newPos)) { gene.setPositionOf(student, newPos); } else { studentsByPriority.insertElementAt(student, 0); } x += 1; if (x >= ClassRoom.instance().getDimensions().getWidth()) { x = 0; y -= 1; } } }
diff --git a/src/test/java/org/elasticsearch/test/integration/update/UpdateTests.java b/src/test/java/org/elasticsearch/test/integration/update/UpdateTests.java index 0cf7821acd7..18844b6b87b 100644 --- a/src/test/java/org/elasticsearch/test/integration/update/UpdateTests.java +++ b/src/test/java/org/elasticsearch/test/integration/update/UpdateTests.java @@ -1,330 +1,330 @@ /* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.integration.update; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.index.engine.DocumentMissingException; import org.elasticsearch.test.integration.AbstractNodesTests; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class UpdateTests extends AbstractNodesTests { private Client client; @BeforeClass public void startNodes() throws Exception { startNode("node1", nodeSettings()); startNode("node2", nodeSettings()); client = getClient(); } protected void createIndex() throws Exception { try { client.admin().indices().prepareDelete("test").execute().actionGet(); } catch (Exception e) { // ignore } logger.info("--> creating index test"); client.admin().indices().prepareCreate("test") .addMapping("type1", XContentFactory.jsonBuilder() .startObject() .startObject("type1") .startObject("_timestamp").field("enabled", true).field("store", "yes").endObject() .startObject("_ttl").field("enabled", true).field("store", "yes").endObject() .endObject() .endObject()) .execute().actionGet(); } protected Settings nodeSettings() { return ImmutableSettings.Builder.EMPTY_SETTINGS; } protected String getConcreteIndexName() { return "test"; } @AfterClass public void closeNodes() { client.close(); closeAllNodes(); } protected Client getClient() { return client("node1"); } @Test public void testUpdateRequest() throws Exception { UpdateRequest request = new UpdateRequest("test", "type", "1"); // simple script request.source(XContentFactory.jsonBuilder().startObject() .field("script", "script1") .endObject()); assertThat(request.script(), equalTo("script1")); // script with params request = new UpdateRequest("test", "type", "1"); request.source(XContentFactory.jsonBuilder().startObject() .field("script", "script1") .startObject("params").field("param1", "value1").endObject() .endObject()); assertThat(request.script(), equalTo("script1")); assertThat(request.scriptParams().get("param1").toString(), equalTo("value1")); request = new UpdateRequest("test", "type", "1"); request.source(XContentFactory.jsonBuilder().startObject() .startObject("params").field("param1", "value1").endObject() .field("script", "script1") .endObject()); assertThat(request.script(), equalTo("script1")); assertThat(request.scriptParams().get("param1").toString(), equalTo("value1")); // script with params and upsert request = new UpdateRequest("test", "type", "1"); request.source(XContentFactory.jsonBuilder().startObject() .startObject("params").field("param1", "value1").endObject() .field("script", "script1") .startObject("upsert").field("field1", "value1").startObject("compound").field("field2", "value2").endObject().endObject() .endObject()); assertThat(request.script(), equalTo("script1")); assertThat(request.scriptParams().get("param1").toString(), equalTo("value1")); Map<String, Object> upsertDoc = XContentHelper.convertToMap(request.upsertRequest().source(), true).v2(); assertThat(upsertDoc.get("field1").toString(), equalTo("value1")); assertThat(((Map) upsertDoc.get("compound")).get("field2").toString(), equalTo("value2")); request = new UpdateRequest("test", "type", "1"); request.source(XContentFactory.jsonBuilder().startObject() .startObject("upsert").field("field1", "value1").startObject("compound").field("field2", "value2").endObject().endObject() .startObject("params").field("param1", "value1").endObject() .field("script", "script1") .endObject()); assertThat(request.script(), equalTo("script1")); assertThat(request.scriptParams().get("param1").toString(), equalTo("value1")); upsertDoc = XContentHelper.convertToMap(request.upsertRequest().source(), true).v2(); assertThat(upsertDoc.get("field1").toString(), equalTo("value1")); assertThat(((Map) upsertDoc.get("compound")).get("field2").toString(), equalTo("value2")); request = new UpdateRequest("test", "type", "1"); request.source(XContentFactory.jsonBuilder().startObject() .startObject("params").field("param1", "value1").endObject() .startObject("upsert").field("field1", "value1").startObject("compound").field("field2", "value2").endObject().endObject() .field("script", "script1") .endObject()); assertThat(request.script(), equalTo("script1")); assertThat(request.scriptParams().get("param1").toString(), equalTo("value1")); upsertDoc = XContentHelper.convertToMap(request.upsertRequest().source(), true).v2(); assertThat(upsertDoc.get("field1").toString(), equalTo("value1")); assertThat(((Map) upsertDoc.get("compound")).get("field2").toString(), equalTo("value2")); // script with doc request = new UpdateRequest("test", "type", "1"); request.source(XContentFactory.jsonBuilder().startObject() .startObject("doc").field("field1", "value1").startObject("compound").field("field2", "value2").endObject().endObject() .endObject()); Map<String, Object> doc = request.doc().sourceAsMap(); assertThat(doc.get("field1").toString(), equalTo("value1")); assertThat(((Map) doc.get("compound")).get("field2").toString(), equalTo("value2")); } @Test public void testUpsert() throws Exception { createIndex(); ClusterHealthResponse clusterHealth = client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); client.prepareUpdate("test", "type1", "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("field", 1).endObject()) .setScript("ctx._source.field += 1") .execute().actionGet(); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("1")); } client.prepareUpdate("test", "type1", "1") .setUpsert(XContentFactory.jsonBuilder().startObject().field("field", 1).endObject()) .setScript("ctx._source.field += 1") .execute().actionGet(); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("2")); } } @Test public void testUpdate() throws Exception { createIndex(); ClusterHealthResponse clusterHealth = client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); try { client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field++").execute().actionGet(); assert false; } catch (DocumentMissingException e) { // all is well } client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); UpdateResponse updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").execute().actionGet(); assertThat(updateResponse.version(), equalTo(2L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("2")); } updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += count").addScriptParam("count", 3).execute().actionGet(); assertThat(updateResponse.version(), equalTo(3L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("5")); } // check noop updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx.op = 'none'").execute().actionGet(); assertThat(updateResponse.version(), equalTo(3L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("5")); } // check delete updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx.op = 'delete'").execute().actionGet(); assertThat(updateResponse.version(), equalTo(4L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.exists(), equalTo(false)); } // check percolation client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); logger.info("--> register a query"); client.prepareIndex("_percolator", "test", "1") .setSource(jsonBuilder().startObject() .field("query", termQuery("field", 2)) .endObject()) .setRefresh(true) .execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").setPercolate("*").execute().actionGet(); assertThat(updateResponse.matches().size(), equalTo(1)); // check TTL is kept after an update without TTL client.prepareIndex("test", "type1", "2").setSource("field", 1).setTTL(86400000L).setRefresh(true).execute().actionGet(); GetResponse getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); long ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); client.prepareUpdate("test", "type1", "2").setScript("ctx._source.field += 1").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); // check TTL update client.prepareUpdate("test", "type1", "2").setScript("ctx._ttl = 3600000").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); - assertThat(ttl, lessThan(3600000L)); + assertThat(ttl, lessThanOrEqualTo(3600000L)); // check timestamp update client.prepareIndex("test", "type1", "3").setSource("field", 1).setRefresh(true).execute().actionGet(); client.prepareUpdate("test", "type1", "3").setScript("ctx._timestamp = \"2009-11-15T14:12:12\"").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "3").setFields("_timestamp").execute().actionGet(); long timestamp = ((Number) getResponse.field("_timestamp").value()).longValue(); assertThat(timestamp, equalTo(1258294332000L)); // check fields parameter client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").setFields("_source", "field").execute().actionGet(); assertThat(updateResponse.getResult(), notNullValue()); assertThat(updateResponse.getResult().sourceRef(), notNullValue()); assertThat(updateResponse.getResult().field("field").value(), notNullValue()); // check updates without script // add new field client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("field2", 2).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("1")); assertThat(getResponse.sourceAsMap().get("field2").toString(), equalTo("2")); } // change existing field updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("field", 3).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("3")); assertThat(getResponse.sourceAsMap().get("field2").toString(), equalTo("2")); } // recursive map Map<String, Object> testMap = new HashMap<String, Object>(); Map<String, Object> testMap2 = new HashMap<String, Object>(); Map<String, Object> testMap3 = new HashMap<String, Object>(); testMap3.put("commonkey", testMap); testMap3.put("map3", 5); testMap2.put("map2", 6); testMap.put("commonkey", testMap2); testMap.put("map1", 8); client.prepareIndex("test", "type1", "1").setSource("map", testMap).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("map", testMap3).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); Map map1 = (Map) getResponse.sourceAsMap().get("map"); assertThat(map1.size(), equalTo(3)); assertThat(map1.containsKey("map1"), equalTo(true)); assertThat(map1.containsKey("map3"), equalTo(true)); assertThat(map1.containsKey("commonkey"), equalTo(true)); Map map2 = (Map) map1.get("commonkey"); assertThat(map2.size(), equalTo(3)); assertThat(map2.containsKey("map1"), equalTo(true)); assertThat(map2.containsKey("map2"), equalTo(true)); assertThat(map2.containsKey("commonkey"), equalTo(true)); } } }
true
true
public void testUpdate() throws Exception { createIndex(); ClusterHealthResponse clusterHealth = client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); try { client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field++").execute().actionGet(); assert false; } catch (DocumentMissingException e) { // all is well } client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); UpdateResponse updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").execute().actionGet(); assertThat(updateResponse.version(), equalTo(2L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("2")); } updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += count").addScriptParam("count", 3).execute().actionGet(); assertThat(updateResponse.version(), equalTo(3L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("5")); } // check noop updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx.op = 'none'").execute().actionGet(); assertThat(updateResponse.version(), equalTo(3L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("5")); } // check delete updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx.op = 'delete'").execute().actionGet(); assertThat(updateResponse.version(), equalTo(4L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.exists(), equalTo(false)); } // check percolation client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); logger.info("--> register a query"); client.prepareIndex("_percolator", "test", "1") .setSource(jsonBuilder().startObject() .field("query", termQuery("field", 2)) .endObject()) .setRefresh(true) .execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").setPercolate("*").execute().actionGet(); assertThat(updateResponse.matches().size(), equalTo(1)); // check TTL is kept after an update without TTL client.prepareIndex("test", "type1", "2").setSource("field", 1).setTTL(86400000L).setRefresh(true).execute().actionGet(); GetResponse getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); long ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); client.prepareUpdate("test", "type1", "2").setScript("ctx._source.field += 1").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); // check TTL update client.prepareUpdate("test", "type1", "2").setScript("ctx._ttl = 3600000").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); assertThat(ttl, lessThan(3600000L)); // check timestamp update client.prepareIndex("test", "type1", "3").setSource("field", 1).setRefresh(true).execute().actionGet(); client.prepareUpdate("test", "type1", "3").setScript("ctx._timestamp = \"2009-11-15T14:12:12\"").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "3").setFields("_timestamp").execute().actionGet(); long timestamp = ((Number) getResponse.field("_timestamp").value()).longValue(); assertThat(timestamp, equalTo(1258294332000L)); // check fields parameter client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").setFields("_source", "field").execute().actionGet(); assertThat(updateResponse.getResult(), notNullValue()); assertThat(updateResponse.getResult().sourceRef(), notNullValue()); assertThat(updateResponse.getResult().field("field").value(), notNullValue()); // check updates without script // add new field client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("field2", 2).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("1")); assertThat(getResponse.sourceAsMap().get("field2").toString(), equalTo("2")); } // change existing field updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("field", 3).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("3")); assertThat(getResponse.sourceAsMap().get("field2").toString(), equalTo("2")); } // recursive map Map<String, Object> testMap = new HashMap<String, Object>(); Map<String, Object> testMap2 = new HashMap<String, Object>(); Map<String, Object> testMap3 = new HashMap<String, Object>(); testMap3.put("commonkey", testMap); testMap3.put("map3", 5); testMap2.put("map2", 6); testMap.put("commonkey", testMap2); testMap.put("map1", 8); client.prepareIndex("test", "type1", "1").setSource("map", testMap).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("map", testMap3).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); Map map1 = (Map) getResponse.sourceAsMap().get("map"); assertThat(map1.size(), equalTo(3)); assertThat(map1.containsKey("map1"), equalTo(true)); assertThat(map1.containsKey("map3"), equalTo(true)); assertThat(map1.containsKey("commonkey"), equalTo(true)); Map map2 = (Map) map1.get("commonkey"); assertThat(map2.size(), equalTo(3)); assertThat(map2.containsKey("map1"), equalTo(true)); assertThat(map2.containsKey("map2"), equalTo(true)); assertThat(map2.containsKey("commonkey"), equalTo(true)); } }
public void testUpdate() throws Exception { createIndex(); ClusterHealthResponse clusterHealth = client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); assertThat(clusterHealth.timedOut(), equalTo(false)); assertThat(clusterHealth.status(), equalTo(ClusterHealthStatus.GREEN)); try { client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field++").execute().actionGet(); assert false; } catch (DocumentMissingException e) { // all is well } client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); UpdateResponse updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").execute().actionGet(); assertThat(updateResponse.version(), equalTo(2L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("2")); } updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += count").addScriptParam("count", 3).execute().actionGet(); assertThat(updateResponse.version(), equalTo(3L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("5")); } // check noop updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx.op = 'none'").execute().actionGet(); assertThat(updateResponse.version(), equalTo(3L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("5")); } // check delete updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx.op = 'delete'").execute().actionGet(); assertThat(updateResponse.version(), equalTo(4L)); for (int i = 0; i < 5; i++) { GetResponse getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.exists(), equalTo(false)); } // check percolation client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); logger.info("--> register a query"); client.prepareIndex("_percolator", "test", "1") .setSource(jsonBuilder().startObject() .field("query", termQuery("field", 2)) .endObject()) .setRefresh(true) .execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").setPercolate("*").execute().actionGet(); assertThat(updateResponse.matches().size(), equalTo(1)); // check TTL is kept after an update without TTL client.prepareIndex("test", "type1", "2").setSource("field", 1).setTTL(86400000L).setRefresh(true).execute().actionGet(); GetResponse getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); long ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); client.prepareUpdate("test", "type1", "2").setScript("ctx._source.field += 1").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); // check TTL update client.prepareUpdate("test", "type1", "2").setScript("ctx._ttl = 3600000").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "2").setFields("_ttl").execute().actionGet(); ttl = ((Number) getResponse.field("_ttl").value()).longValue(); assertThat(ttl, greaterThan(0L)); assertThat(ttl, lessThanOrEqualTo(3600000L)); // check timestamp update client.prepareIndex("test", "type1", "3").setSource("field", 1).setRefresh(true).execute().actionGet(); client.prepareUpdate("test", "type1", "3").setScript("ctx._timestamp = \"2009-11-15T14:12:12\"").execute().actionGet(); getResponse = client.prepareGet("test", "type1", "3").setFields("_timestamp").execute().actionGet(); long timestamp = ((Number) getResponse.field("_timestamp").value()).longValue(); assertThat(timestamp, equalTo(1258294332000L)); // check fields parameter client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setScript("ctx._source.field += 1").setFields("_source", "field").execute().actionGet(); assertThat(updateResponse.getResult(), notNullValue()); assertThat(updateResponse.getResult().sourceRef(), notNullValue()); assertThat(updateResponse.getResult().field("field").value(), notNullValue()); // check updates without script // add new field client.prepareIndex("test", "type1", "1").setSource("field", 1).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("field2", 2).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("1")); assertThat(getResponse.sourceAsMap().get("field2").toString(), equalTo("2")); } // change existing field updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("field", 3).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); assertThat(getResponse.sourceAsMap().get("field").toString(), equalTo("3")); assertThat(getResponse.sourceAsMap().get("field2").toString(), equalTo("2")); } // recursive map Map<String, Object> testMap = new HashMap<String, Object>(); Map<String, Object> testMap2 = new HashMap<String, Object>(); Map<String, Object> testMap3 = new HashMap<String, Object>(); testMap3.put("commonkey", testMap); testMap3.put("map3", 5); testMap2.put("map2", 6); testMap.put("commonkey", testMap2); testMap.put("map1", 8); client.prepareIndex("test", "type1", "1").setSource("map", testMap).execute().actionGet(); updateResponse = client.prepareUpdate("test", "type1", "1").setDoc(XContentFactory.jsonBuilder().startObject().field("map", testMap3).endObject()).execute().actionGet(); for (int i = 0; i < 5; i++) { getResponse = client.prepareGet("test", "type1", "1").execute().actionGet(); Map map1 = (Map) getResponse.sourceAsMap().get("map"); assertThat(map1.size(), equalTo(3)); assertThat(map1.containsKey("map1"), equalTo(true)); assertThat(map1.containsKey("map3"), equalTo(true)); assertThat(map1.containsKey("commonkey"), equalTo(true)); Map map2 = (Map) map1.get("commonkey"); assertThat(map2.size(), equalTo(3)); assertThat(map2.containsKey("map1"), equalTo(true)); assertThat(map2.containsKey("map2"), equalTo(true)); assertThat(map2.containsKey("commonkey"), equalTo(true)); } }
diff --git a/src/java/mc/alk/arena/util/SignUtil.java b/src/java/mc/alk/arena/util/SignUtil.java index e7b5b59..a1bf83b 100644 --- a/src/java/mc/alk/arena/util/SignUtil.java +++ b/src/java/mc/alk/arena/util/SignUtil.java @@ -1,84 +1,84 @@ package mc.alk.arena.util; import mc.alk.arena.Defaults; import mc.alk.arena.controllers.ArenaClassController; import mc.alk.arena.controllers.ParamController; import mc.alk.arena.objects.ArenaClass; import mc.alk.arena.objects.MatchParams; import mc.alk.arena.objects.signs.ArenaCommandSign; import mc.alk.arena.objects.signs.ArenaCommandSign.ARENA_COMMAND; import mc.alk.arena.objects.signs.ArenaStatusSign; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.Sign; import java.util.Collection; public class SignUtil { public static ArenaCommandSign getArenaCommandSign(Sign sign, String[] lines) { if (lines.length < 2) return null; String param = MessageUtil.decolorChat(lines[0]).replaceAll("[\\[\\"+Defaults.SIGN_PREFIX+"\\]]","").trim().toLowerCase(); MatchParams mp = ParamController.getMatchParamCopy(param); if (mp == null){ Collection<MatchParams> params = ParamController.getAllParams(); for (MatchParams p: params){ if (p.getName().toLowerCase().startsWith(param) || p.getCommand().toLowerCase().startsWith(param) || p.getSignDisplayName()!=null && - MessageUtil.decolorChat(p.getSignDisplayName()).equalsIgnoreCase(param)){ + MessageUtil.decolorChat(p.getSignDisplayName().replaceAll("[\\[\\"+Defaults.SIGN_PREFIX+"\\]]","").trim()).equalsIgnoreCase(param)){ mp = p; break; } } if (mp == null){ return null;} } param = MessageUtil.decolorChat(lines[1]).toUpperCase().trim(); ARENA_COMMAND cmd; try { cmd = ARENA_COMMAND.valueOf(param); } catch (Exception e){ return null; } String op1 = MessageUtil.decolorChat(lines[2]); String op2 = MessageUtil.decolorChat(lines[3]); ArenaCommandSign acs = new ArenaCommandSign(sign.getLocation(), mp, cmd, op1, op2); return acs; } public static ArenaClass getArenaClassSign(String[] lines) { ArenaClass ac = ArenaClassController.getClass( MessageUtil.decolorChat(lines[0]).replaceAll("[\\[\\"+Defaults.SIGN_PREFIX+"\\]]", "")); return ac; } public static ArenaStatusSign getArenaStatusSign(String[] lines) { if (lines.length < 2) return null; String param = MessageUtil.decolorChat(lines[0]).replaceAll("\\"+Defaults.SIGN_PREFIX, "").trim(); MatchParams mp = ParamController.getMatchParamCopy(param); if (mp == null) return null; if (lines[1].contains("status")) return new ArenaStatusSign(mp); return null; } public static Sign getSign(World w, int x, int y, int z) { Block b = w.getBlockAt(x, y, z); Material t = b.getType(); return t == Material.SIGN || t == Material.SIGN_POST || t==Material.WALL_SIGN ? (Sign)b.getState(): null; } public static Sign getSign(Location l) { if (l == null) return null; Material t = l.getBlock().getType(); return t == Material.SIGN || t == Material.SIGN_POST || t==Material.WALL_SIGN ? (Sign)l.getBlock().getState(): null; } }
true
true
public static ArenaCommandSign getArenaCommandSign(Sign sign, String[] lines) { if (lines.length < 2) return null; String param = MessageUtil.decolorChat(lines[0]).replaceAll("[\\[\\"+Defaults.SIGN_PREFIX+"\\]]","").trim().toLowerCase(); MatchParams mp = ParamController.getMatchParamCopy(param); if (mp == null){ Collection<MatchParams> params = ParamController.getAllParams(); for (MatchParams p: params){ if (p.getName().toLowerCase().startsWith(param) || p.getCommand().toLowerCase().startsWith(param) || p.getSignDisplayName()!=null && MessageUtil.decolorChat(p.getSignDisplayName()).equalsIgnoreCase(param)){ mp = p; break; } } if (mp == null){ return null;} } param = MessageUtil.decolorChat(lines[1]).toUpperCase().trim(); ARENA_COMMAND cmd; try { cmd = ARENA_COMMAND.valueOf(param); } catch (Exception e){ return null; } String op1 = MessageUtil.decolorChat(lines[2]); String op2 = MessageUtil.decolorChat(lines[3]); ArenaCommandSign acs = new ArenaCommandSign(sign.getLocation(), mp, cmd, op1, op2); return acs; }
public static ArenaCommandSign getArenaCommandSign(Sign sign, String[] lines) { if (lines.length < 2) return null; String param = MessageUtil.decolorChat(lines[0]).replaceAll("[\\[\\"+Defaults.SIGN_PREFIX+"\\]]","").trim().toLowerCase(); MatchParams mp = ParamController.getMatchParamCopy(param); if (mp == null){ Collection<MatchParams> params = ParamController.getAllParams(); for (MatchParams p: params){ if (p.getName().toLowerCase().startsWith(param) || p.getCommand().toLowerCase().startsWith(param) || p.getSignDisplayName()!=null && MessageUtil.decolorChat(p.getSignDisplayName().replaceAll("[\\[\\"+Defaults.SIGN_PREFIX+"\\]]","").trim()).equalsIgnoreCase(param)){ mp = p; break; } } if (mp == null){ return null;} } param = MessageUtil.decolorChat(lines[1]).toUpperCase().trim(); ARENA_COMMAND cmd; try { cmd = ARENA_COMMAND.valueOf(param); } catch (Exception e){ return null; } String op1 = MessageUtil.decolorChat(lines[2]); String op2 = MessageUtil.decolorChat(lines[3]); ArenaCommandSign acs = new ArenaCommandSign(sign.getLocation(), mp, cmd, op1, op2); return acs; }
diff --git a/src/eu/bryants/anthony/toylanguage/compiler/Checker.java b/src/eu/bryants/anthony/toylanguage/compiler/Checker.java index 4c7d94f..7f4d627 100644 --- a/src/eu/bryants/anthony/toylanguage/compiler/Checker.java +++ b/src/eu/bryants/anthony/toylanguage/compiler/Checker.java @@ -1,61 +1,61 @@ package eu.bryants.anthony.toylanguage.compiler; import eu.bryants.anthony.toylanguage.ast.Block; import eu.bryants.anthony.toylanguage.ast.CompilationUnit; import eu.bryants.anthony.toylanguage.ast.Function; import eu.bryants.anthony.toylanguage.ast.ReturnStatement; import eu.bryants.anthony.toylanguage.ast.Statement; /* * Created on 6 Apr 2012 */ /** * @author Anthony Bryant */ public class Checker { /** * Checks that the control flow of the specified compilation unit is well defined. * @param compilationUnit - the CompilationUnit to check * @throws ConceptualException - if any control flow related errors are detected */ public static void checkControlFlow(CompilationUnit compilationUnit) throws ConceptualException { for (Function f : compilationUnit.getFunctions()) { boolean returned = checkControlFlow(f.getBlock()); if (!returned) { throw new ConceptualException("Function does not return a value", f.getLexicalPhrase()); } } } /** * Checks that the control flow of the specified block is well defined. * @param block - the block to check * @return true if the block returns from its enclosing function, false if control flow continues after it * @throws ConceptualException - if any unreachable code is detected */ private static boolean checkControlFlow(Block block) throws ConceptualException { boolean returned = false; for (Statement s : block.getStatements()) { if (returned) { throw new ConceptualException("Unreachable code", s.getLexicalPhrase()); } if (s instanceof ReturnStatement) { returned = true; } else if (s instanceof Block) { - returned = checkControlFlow(block); + returned = checkControlFlow((Block) s); } } return returned; } }
true
true
private static boolean checkControlFlow(Block block) throws ConceptualException { boolean returned = false; for (Statement s : block.getStatements()) { if (returned) { throw new ConceptualException("Unreachable code", s.getLexicalPhrase()); } if (s instanceof ReturnStatement) { returned = true; } else if (s instanceof Block) { returned = checkControlFlow(block); } } return returned; }
private static boolean checkControlFlow(Block block) throws ConceptualException { boolean returned = false; for (Statement s : block.getStatements()) { if (returned) { throw new ConceptualException("Unreachable code", s.getLexicalPhrase()); } if (s instanceof ReturnStatement) { returned = true; } else if (s instanceof Block) { returned = checkControlFlow((Block) s); } } return returned; }
diff --git a/JavaSource/org/unitime/timetable/model/Meeting.java b/JavaSource/org/unitime/timetable/model/Meeting.java index 878168db..5ab0580d 100644 --- a/JavaSource/org/unitime/timetable/model/Meeting.java +++ b/JavaSource/org/unitime/timetable/model/Meeting.java @@ -1,260 +1,263 @@ /* * UniTime 3.1 (University Course Timetabling & Student Sectioning Application) * Copyright (C) 2008, UniTime LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.unitime.timetable.model; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.unitime.timetable.model.base.BaseMeeting; import org.unitime.timetable.model.dao.LocationDAO; import org.unitime.timetable.model.dao.MeetingDAO; import org.unitime.timetable.model.dao.RoomDAO; import org.unitime.timetable.util.Constants; public class Meeting extends BaseMeeting implements Comparable<Meeting> { private static final long serialVersionUID = 1L; private Location location = null; /*[CONSTRUCTOR MARKER BEGIN]*/ public Meeting () { super(); } /** * Constructor for primary key */ public Meeting (java.lang.Long uniqueId) { super(uniqueId); } /** * Constructor for required fields */ public Meeting ( java.lang.Long uniqueId, org.unitime.timetable.model.Event event, java.util.Date meetingDate, java.lang.Integer startPeriod, java.lang.Integer stopPeriod, java.lang.Boolean classCanOverride) { super ( uniqueId, event, meetingDate, startPeriod, stopPeriod, classCanOverride); } /*[CONSTRUCTOR MARKER END]*/ @Override public Object clone() { Meeting newMeeting = new Meeting(); newMeeting.setClassCanOverride(isClassCanOverride()); newMeeting.setLocationPermanentId(getLocationPermanentId()); newMeeting.setMeetingDate(getMeetingDate()); newMeeting.setStartOffset(getStartOffset()); newMeeting.setStartPeriod(getStartPeriod()); newMeeting.setStopOffset(getStopOffset()); newMeeting.setStopPeriod(getStopPeriod()); return(newMeeting); } public int compareTo(Meeting other) { int cmp = getMeetingDate().compareTo(other.getMeetingDate()); if (cmp!=0) return cmp; cmp = getStartPeriod().compareTo(other.getStartPeriod()); if (cmp!=0) return cmp; cmp = getRoomLabel().compareTo(other.getRoomLabel()); if (cmp!=0) return cmp; return getUniqueId().compareTo(other.getUniqueId()); } public Location getLocation(){ if (location != null){ return(location); } if(getLocationPermanentId() == null){ return(null); } if (getMeetingDate() == null){ return(null); } - Session session = getEvent().getSession(); + Session session = null; + if (getEvent() != null){ + session = getEvent().getSession(); + } if (session!=null) { location = (Location)RoomDAO.getInstance().getSession().createQuery( "select r from Room r where r.permanentId = :permId and r.session.uniqueId=:sessionId") .setLong("sessionId", session.getUniqueId()) .setLong("permId", getLocationPermanentId()) .setCacheable(true) .uniqueResult(); if (location==null) location = (Location)RoomDAO.getInstance().getSession().createQuery( "select r from NonUniversityLocation r where r.permanentId = :permId and r.session.uniqueId=:sessionId") .setLong("sessionId", session.getUniqueId()) .setLong("permId", getLocationPermanentId()) .setCacheable(true) .uniqueResult(); return location; } long distance = -1; List locations = LocationDAO.getInstance().getSession().createQuery( "from Location where permanentId = :permId"). setLong("permId", getLocationPermanentId()). setCacheable(true).list(); if (!locations.isEmpty()) { for (Iterator it = locations.iterator(); it.hasNext(); ) { Location loc = (Location)it.next(); long dist = loc.getSession().getDistance(getMeetingDate()); if (location==null || distance>dist) { location = loc; distance = dist; } } } return(location); } public List<Meeting> getTimeRoomOverlaps(){ if (getLocationPermanentId()==null) return new ArrayList<Meeting>(); return (MeetingDAO.getInstance()).getSession().createQuery( "from Meeting m where m.meetingDate=:meetingDate and m.startPeriod < :stopPeriod and m.stopPeriod > :startPeriod and " + "m.locationPermanentId = :locPermId and m.uniqueId != :uniqueId") .setDate("meetingDate", getMeetingDate()) .setInteger("stopPeriod", getStopPeriod()) .setInteger("startPeriod", getStartPeriod()) .setLong("locPermId", getLocationPermanentId()) .setLong("uniqueId", this.getUniqueId()) .list(); } public List<Meeting> getApprovedTimeRoomOverlaps(){ if (getLocationPermanentId()==null) return new ArrayList<Meeting>(); return (MeetingDAO.getInstance()).getSession().createQuery( "from Meeting m where m.meetingDate=:meetingDate and m.startPeriod < :stopPeriod and m.stopPeriod > :startPeriod and " + "m.locationPermanentId = :locPermId and m.uniqueId != :uniqueId and m.approvedDate != null") .setDate("meetingDate", getMeetingDate()) .setInteger("stopPeriod", getStopPeriod()) .setInteger("startPeriod", getStartPeriod()) .setLong("locPermId", getLocationPermanentId()) .setLong("uniqueId", this.getUniqueId()) .list(); } public static List<Meeting> findOverlaps(Date meetingDate, int startPeriod, int stopPeriod, Long locationPermId){ return (MeetingDAO.getInstance()).getSession().createQuery( "from Meeting m where m.meetingDate=:meetingDate and m.startPeriod < :stopPeriod and m.stopPeriod > :startPeriod and " + "m.locationPermanentId = :locPermId") .setDate("meetingDate", meetingDate) .setInteger("stopPeriod", stopPeriod) .setInteger("startPeriod", startPeriod) .setLong("locPermId", locationPermId) .list(); } public boolean hasTimeRoomOverlaps(){ return ((Number)MeetingDAO.getInstance().getSession().createQuery( "select count(m) from Meeting m where m.meetingDate=:meetingDate and m.startPeriod < :stopPeriod and m.stopPeriod > :startPeriod and " + "m.locationPermanentId = :locPermId and m.uniqueId != :uniqueId") .setDate("meetingDate", getMeetingDate()) .setInteger("stopPeriod", getStopPeriod()) .setInteger("startPeriod", getStartPeriod()) .setLong("locPermId", getLocationPermanentId()) .setLong("uniqueId", this.getUniqueId()) .uniqueResult()).longValue()>0; } public String toString() { return (DateFormat.getDateInstance(DateFormat.SHORT).format(getMeetingDate())+" "+ (isAllDay()?"All Day":startTime()+" - "+stopTime())+ (getLocation()==null?"":", "+getLocation().getLabel())); } public String getTimeLabel() { return dateStr() + " " + startTime() + " - " + stopTime(); } public String getRoomLabel() { return getLocation() == null?"":getLocation().getLabel(); } private String periodToTime(Integer slot, Integer offset){ if (slot==null) return(""); int min = slot.intValue()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN; if (offset!=null) min += offset; return Constants.toTime(min); } public String startTime(){ return(periodToTime(getStartPeriod(), getStartOffset())); } public String stopTime(){ return(periodToTime(getStopPeriod(), getStopOffset())); } public String dateStr() { return new SimpleDateFormat("EEE MM/dd").format(getMeetingDate()); } public Date getStartTime() { Calendar c = Calendar.getInstance(Locale.US); c.setTime(getMeetingDate()); int min = (getStartPeriod().intValue()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN)+(getStartOffset()==null?0:getStartOffset()); c.set(Calendar.HOUR, min/60); c.set(Calendar.MINUTE, min%60); return c.getTime(); } public Date getStopTime() { Calendar c = Calendar.getInstance(Locale.US); c.setTime(getMeetingDate()); int min = (getStopPeriod().intValue()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN)+(getStopOffset()==null?0:getStopOffset()); c.set(Calendar.HOUR, min/60); c.set(Calendar.MINUTE, min%60); return c.getTime(); } public int getDayOfWeek() { Calendar c = Calendar.getInstance(Locale.US); c.setTime(getMeetingDate()); return c.get(Calendar.DAY_OF_WEEK); } public boolean isApproved() { return getApprovedDate()!=null; } public boolean overlaps(Meeting meeting) { if (getMeetingDate().getTime()!=meeting.getMeetingDate().getTime()) return false; return getStartPeriod()<meeting.getStopPeriod() && meeting.getStartPeriod()<getStopPeriod(); } public boolean isAllDay() { return getStartPeriod()==0 && getStopPeriod()==Constants.SLOTS_PER_DAY; } }
true
true
public Location getLocation(){ if (location != null){ return(location); } if(getLocationPermanentId() == null){ return(null); } if (getMeetingDate() == null){ return(null); } Session session = getEvent().getSession(); if (session!=null) { location = (Location)RoomDAO.getInstance().getSession().createQuery( "select r from Room r where r.permanentId = :permId and r.session.uniqueId=:sessionId") .setLong("sessionId", session.getUniqueId()) .setLong("permId", getLocationPermanentId()) .setCacheable(true) .uniqueResult(); if (location==null) location = (Location)RoomDAO.getInstance().getSession().createQuery( "select r from NonUniversityLocation r where r.permanentId = :permId and r.session.uniqueId=:sessionId") .setLong("sessionId", session.getUniqueId()) .setLong("permId", getLocationPermanentId()) .setCacheable(true) .uniqueResult(); return location; } long distance = -1; List locations = LocationDAO.getInstance().getSession().createQuery( "from Location where permanentId = :permId"). setLong("permId", getLocationPermanentId()). setCacheable(true).list(); if (!locations.isEmpty()) { for (Iterator it = locations.iterator(); it.hasNext(); ) { Location loc = (Location)it.next(); long dist = loc.getSession().getDistance(getMeetingDate()); if (location==null || distance>dist) { location = loc; distance = dist; } } } return(location); }
public Location getLocation(){ if (location != null){ return(location); } if(getLocationPermanentId() == null){ return(null); } if (getMeetingDate() == null){ return(null); } Session session = null; if (getEvent() != null){ session = getEvent().getSession(); } if (session!=null) { location = (Location)RoomDAO.getInstance().getSession().createQuery( "select r from Room r where r.permanentId = :permId and r.session.uniqueId=:sessionId") .setLong("sessionId", session.getUniqueId()) .setLong("permId", getLocationPermanentId()) .setCacheable(true) .uniqueResult(); if (location==null) location = (Location)RoomDAO.getInstance().getSession().createQuery( "select r from NonUniversityLocation r where r.permanentId = :permId and r.session.uniqueId=:sessionId") .setLong("sessionId", session.getUniqueId()) .setLong("permId", getLocationPermanentId()) .setCacheable(true) .uniqueResult(); return location; } long distance = -1; List locations = LocationDAO.getInstance().getSession().createQuery( "from Location where permanentId = :permId"). setLong("permId", getLocationPermanentId()). setCacheable(true).list(); if (!locations.isEmpty()) { for (Iterator it = locations.iterator(); it.hasNext(); ) { Location loc = (Location)it.next(); long dist = loc.getSession().getDistance(getMeetingDate()); if (location==null || distance>dist) { location = loc; distance = dist; } } } return(location); }
diff --git a/Badds/src/de/danielsenff/badds/actions/BasicAction.java b/Badds/src/de/danielsenff/badds/actions/BasicAction.java index 95fb168..9969867 100644 --- a/Badds/src/de/danielsenff/badds/actions/BasicAction.java +++ b/Badds/src/de/danielsenff/badds/actions/BasicAction.java @@ -1,51 +1,51 @@ package de.danielsenff.badds.actions; import java.util.ResourceBundle; import javax.swing.AbstractAction; import javax.swing.KeyStroke; import de.danielsenff.badds.controller.Application; import de.danielsenff.badds.util.OS; import de.danielsenff.badds.util.ResourceLoader; abstract public class BasicAction extends AbstractAction { ResourceBundle bundle = Application.getBundle(); Application controller; /** * @param controller */ public BasicAction(final Application controller) { this(controller, true); } public BasicAction(final Application controller, final boolean hasBundle) { this.controller = controller; if (hasBundle){ String name = getClass().getName(); putValue(NAME, bundle.getString(name+".name")); String string = bundle.getString(name+".description"); putValue(SHORT_DESCRIPTION, string); String hotkey; if (OS.isMacOS()) { hotkey = bundle.getString(name+".hotkey_osx"); } else { hotkey = bundle.getString(name+".hotkey"); } putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(hotkey)); - if(!bundle.getString(name+".icon").equals("null")){ + if(!bundle.getString(name+".icon").equals("")){ putValue(SMALL_ICON, ResourceLoader.getResourceIcon(bundle.getString(name+".icon"))); } // putValue(MNEMONIC_KEY, new Integer('S')); } } }
true
true
public BasicAction(final Application controller, final boolean hasBundle) { this.controller = controller; if (hasBundle){ String name = getClass().getName(); putValue(NAME, bundle.getString(name+".name")); String string = bundle.getString(name+".description"); putValue(SHORT_DESCRIPTION, string); String hotkey; if (OS.isMacOS()) { hotkey = bundle.getString(name+".hotkey_osx"); } else { hotkey = bundle.getString(name+".hotkey"); } putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(hotkey)); if(!bundle.getString(name+".icon").equals("null")){ putValue(SMALL_ICON, ResourceLoader.getResourceIcon(bundle.getString(name+".icon"))); } // putValue(MNEMONIC_KEY, new Integer('S')); } }
public BasicAction(final Application controller, final boolean hasBundle) { this.controller = controller; if (hasBundle){ String name = getClass().getName(); putValue(NAME, bundle.getString(name+".name")); String string = bundle.getString(name+".description"); putValue(SHORT_DESCRIPTION, string); String hotkey; if (OS.isMacOS()) { hotkey = bundle.getString(name+".hotkey_osx"); } else { hotkey = bundle.getString(name+".hotkey"); } putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(hotkey)); if(!bundle.getString(name+".icon").equals("")){ putValue(SMALL_ICON, ResourceLoader.getResourceIcon(bundle.getString(name+".icon"))); } // putValue(MNEMONIC_KEY, new Integer('S')); } }
diff --git a/src/com/fsck/k9/mail/transport/SmtpTransport.java b/src/com/fsck/k9/mail/transport/SmtpTransport.java index 29d8c18..4a60c6c 100644 --- a/src/com/fsck/k9/mail/transport/SmtpTransport.java +++ b/src/com/fsck/k9/mail/transport/SmtpTransport.java @@ -1,613 +1,615 @@ package com.fsck.k9.mail.transport; import android.util.Log; import com.fsck.k9.K9; import com.fsck.k9.mail.*; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.filter.Base64; import com.fsck.k9.mail.filter.EOLConvertingOutputStream; import com.fsck.k9.mail.filter.LineWrapOutputStream; import com.fsck.k9.mail.filter.PeekableInputStream; import com.fsck.k9.mail.filter.SmtpDataStuffing; import com.fsck.k9.mail.store.TrustManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManager; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.*; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import org.apache.commons.codec.binary.Hex; import java.util.ArrayList; import java.util.List; public class SmtpTransport extends Transport { public static final int CONNECTION_SECURITY_NONE = 0; public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1; public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2; public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3; public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4; String mHost; int mPort; String mUsername; String mPassword; String mAuthType; int mConnectionSecurity; boolean mSecure; Socket mSocket; PeekableInputStream mIn; OutputStream mOut; private boolean m8bitEncodingAllowed; /** * smtp://user:password@server:port CONNECTION_SECURITY_NONE * smtp+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL * smtp+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED * smtp+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED * smtp+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL * * @param _uri */ public SmtpTransport(String _uri) throws MessagingException { URI uri; try { uri = new URI(_uri); } catch (URISyntaxException use) { throw new MessagingException("Invalid SmtpTransport URI", use); } String scheme = uri.getScheme(); if (scheme.equals("smtp")) { mConnectionSecurity = CONNECTION_SECURITY_NONE; mPort = 25; } else if (scheme.equals("smtp+tls")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; mPort = 25; } else if (scheme.equals("smtp+tls+")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; mPort = 25; } else if (scheme.equals("smtp+ssl+")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; mPort = 465; } else if (scheme.equals("smtp+ssl")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; mPort = 465; } else { throw new MessagingException("Unsupported protocol"); } mHost = uri.getHost(); if (uri.getPort() != -1) { mPort = uri.getPort(); } if (uri.getUserInfo() != null) { try { String[] userInfoParts = uri.getUserInfo().split(":"); mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8"); if (userInfoParts.length > 1) { mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8"); } if (userInfoParts.length > 2) { mAuthType = userInfoParts[2]; } } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc); } } } @Override public void open() throws MessagingException { try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mSecure = true; } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } // RFC 1047 mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); // Eat the banner executeSimpleCommand(null); InetAddress localAddress = mSocket.getLocalAddress(); String localHost = localAddress.getHostName(); + String ipAddr = localAddress.getHostAddress(); - if (localHost.equals(localAddress.getHostAddress())) + if (localHost.equals(ipAddr) || localHost.contains("_")) { - // We don't have a FQDN, so use IP address. + // We don't have a FQDN or the hostname contains invalid + // characters (see issue 2143), so use IP address. if (localAddress instanceof Inet6Address) { - localHost = "[IPV6:" + localHost + "]"; + localHost = "[IPV6:" + ipAddr + "]"; } else { - localHost = "[" + localHost + "]"; + localHost = "[" + ipAddr + "]"; } } List<String> results = executeSimpleCommand("EHLO " + localHost); m8bitEncodingAllowed = results.contains("8BITMIME"); /* * TODO may need to add code to fall back to HELO I switched it from * using HELO on non STARTTLS connections because of AOL's mail * server. It won't let you use AUTH without EHLO. * We should really be paying more attention to the capabilities * and only attempting auth if it's available, and warning the user * if not. */ if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { if (results.contains("STARTTLS")) { executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, true); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); mSecure = true; /* * Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically, * Exim. */ results = executeSimpleCommand("EHLO " + localHost); } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } /* * result contains the results of the EHLO in concatenated form */ boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; for (String result : results) { if (result.matches(".*AUTH.*LOGIN.*$") == true) { authLoginSupported = true; } if (result.matches(".*AUTH.*PLAIN.*$") == true) { authPlainSupported = true; } if (result.matches(".*AUTH.*CRAM-MD5.*$") == true && mAuthType != null && mAuthType.equals("CRAM_MD5")) { authCramMD5Supported = true; } } if (mUsername != null && mUsername.length() > 0 && mPassword != null && mPassword.length() > 0) { if (authCramMD5Supported) { saslAuthCramMD5(mUsername, mPassword); } else if (authPlainSupported) { saslAuthPlain(mUsername, mPassword); } else if (authLoginSupported) { saslAuthLogin(mUsername, mPassword); } else { throw new MessagingException("No valid authentication mechanism found."); } } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to SMTP server.", ioe); } } @Override public void sendMessage(Message message) throws MessagingException { close(); open(); if (m8bitEncodingAllowed) { message.setEncoding("8bit"); } Address[] from = message.getFrom(); boolean possibleSend = false; try { //TODO: Add BODY=8BITMIME parameter if appropriate? executeSimpleCommand("MAIL FROM: " + "<" + from[0].getAddress() + ">"); for (Address address : message.getRecipients(RecipientType.TO)) { executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">"); } for (Address address : message.getRecipients(RecipientType.CC)) { executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">"); } for (Address address : message.getRecipients(RecipientType.BCC)) { executeSimpleCommand("RCPT TO: " + "<" + address.getAddress() + ">"); } message.setRecipients(RecipientType.BCC, null); executeSimpleCommand("DATA"); EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream( new SmtpDataStuffing( new LineWrapOutputStream( new BufferedOutputStream(mOut, 1024), 1000))); message.writeTo(msgOut); // We use BufferedOutputStream. So make sure to call flush() ! msgOut.flush(); possibleSend = true; // After the "\r\n." is attempted, we may have sent the message executeSimpleCommand("\r\n."); } catch (Exception e) { MessagingException me = new MessagingException("Unable to send message", e); me.setPermanentFailure(possibleSend); throw me; } finally { close(); } } @Override public void close() { try { executeSimpleCommand("QUIT"); } catch (Exception e) { } try { mIn.close(); } catch (Exception e) { } try { mOut.close(); } catch (Exception e) { } try { mSocket.close(); } catch (Exception e) { } mIn = null; mOut = null; mSocket = null; } private String readLine() throws IOException { StringBuffer sb = new StringBuffer(); int d; while ((d = mIn.read()) != -1) { if (((char)d) == '\r') { continue; } else if (((char)d) == '\n') { break; } else { sb.append((char)d); } } String ret = sb.toString(); if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) Log.d(K9.LOG_TAG, "SMTP <<< " + ret); return ret; } private void writeLine(String s, boolean sensitive) throws IOException { if (K9.DEBUG && K9.DEBUG_PROTOCOL_SMTP) { final String commandToLog; if (sensitive && !K9.DEBUG_SENSITIVE) { commandToLog = "SMTP >>> *sensitive*"; } else { commandToLog = "SMTP >>> " + s; } Log.d(K9.LOG_TAG, commandToLog); } /* * Note: We can use the string length to compute the buffer size since * only ASCII characters are allowed in SMTP commands i.e. this string * will never contain multi-byte characters. */ int len = s.length(); byte[] data = new byte[len + 2]; s.getBytes(0, len, data, 0); data[len+0] = '\r'; data[len+1] = '\n'; /* * Important: Send command + CRLF using just one write() call. Using * multiple calls will likely result in multiple TCP packets and some * SMTP servers misbehave if CR and LF arrive in separate pakets. * See issue 799. */ mOut.write(data); mOut.flush(); } private void checkLine(String line) throws MessagingException { if (line.length() < 1) { throw new MessagingException("SMTP response is 0 length"); } char c = line.charAt(0); if ((c == '4') || (c == '5')) { throw new MessagingException(line); } } private List<String> executeSimpleCommand(String command) throws IOException, MessagingException { return executeSimpleCommand(command, false); } private List<String> executeSimpleCommand(String command, boolean sensitive) throws IOException, MessagingException { List<String> results = new ArrayList<String>(); if (command != null) { writeLine(command, sensitive); } boolean cont = false; do { String line = readLine(); checkLine(line); if (line.length() > 4) { results.add(line.substring(4)); if (line.charAt(3) == '-') { cont = true; } else { cont = false; } } } while (cont); return results; } // C: AUTH LOGIN // S: 334 VXNlcm5hbWU6 // C: d2VsZG9u // S: 334 UGFzc3dvcmQ6 // C: dzNsZDBu // S: 235 2.0.0 OK Authenticated // // Lines 2-5 of the conversation contain base64-encoded information. The same conversation, with base64 strings decoded, reads: // // // C: AUTH LOGIN // S: 334 Username: // C: weldon // S: 334 Password: // C: w3ld0n // S: 235 2.0.0 OK Authenticated private void saslAuthLogin(String username, String password) throws MessagingException, AuthenticationFailedException, IOException { try { executeSimpleCommand("AUTH LOGIN"); executeSimpleCommand(new String(Base64.encodeBase64(username.getBytes())), true); executeSimpleCommand(new String(Base64.encodeBase64(password.getBytes())), true); } catch (MessagingException me) { if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') { throw new AuthenticationFailedException("AUTH LOGIN failed (" + me.getMessage() + ")"); } throw me; } } private void saslAuthPlain(String username, String password) throws MessagingException, AuthenticationFailedException, IOException { byte[] data = ("\000" + username + "\000" + password).getBytes(); data = new Base64().encode(data); try { executeSimpleCommand("AUTH PLAIN " + new String(data), true); } catch (MessagingException me) { if (me.getMessage().length() > 1 && me.getMessage().charAt(1) == '3') { throw new AuthenticationFailedException("AUTH PLAIN failed (" + me.getMessage() + ")"); } throw me; } } private void saslAuthCramMD5(String username, String password) throws MessagingException, AuthenticationFailedException, IOException { List<String> respList = executeSimpleCommand("AUTH CRAM-MD5"); if (respList.size() != 1) throw new AuthenticationFailedException("Unable to negotiate CRAM-MD5"); String b64Nonce = respList.get(0); byte[] nonce = Base64.decodeBase64(b64Nonce.getBytes("US-ASCII")); byte[] ipad = new byte[64]; byte[] opad = new byte[64]; byte[] secretBytes = password.getBytes("US-ASCII"); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { throw new AuthenticationFailedException("MD5 Not Available."); } if (secretBytes.length > 64) { secretBytes = md.digest(secretBytes); } System.arraycopy(secretBytes, 0, ipad, 0, secretBytes.length); System.arraycopy(secretBytes, 0, opad, 0, secretBytes.length); for (int i = 0; i < ipad.length; i++) ipad[i] ^= 0x36; for (int i = 0; i < opad.length; i++) opad[i] ^= 0x5c; md.update(ipad); byte[] firstPass = md.digest(nonce); md.update(opad); byte[] result = md.digest(firstPass); String plainCRAM = username + " " + new String(Hex.encodeHex(result)); byte[] b64CRAM = Base64.encodeBase64(plainCRAM.getBytes("US-ASCII")); String b64CRAMString = new String(b64CRAM, "US-ASCII"); try { executeSimpleCommand(b64CRAMString, true); } catch (MessagingException me) { throw new AuthenticationFailedException("Unable to negotiate MD5 CRAM"); } } }
false
true
public void open() throws MessagingException { try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mSecure = true; } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } // RFC 1047 mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); // Eat the banner executeSimpleCommand(null); InetAddress localAddress = mSocket.getLocalAddress(); String localHost = localAddress.getHostName(); if (localHost.equals(localAddress.getHostAddress())) { // We don't have a FQDN, so use IP address. if (localAddress instanceof Inet6Address) { localHost = "[IPV6:" + localHost + "]"; } else { localHost = "[" + localHost + "]"; } } List<String> results = executeSimpleCommand("EHLO " + localHost); m8bitEncodingAllowed = results.contains("8BITMIME"); /* * TODO may need to add code to fall back to HELO I switched it from * using HELO on non STARTTLS connections because of AOL's mail * server. It won't let you use AUTH without EHLO. * We should really be paying more attention to the capabilities * and only attempting auth if it's available, and warning the user * if not. */ if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { if (results.contains("STARTTLS")) { executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, true); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); mSecure = true; /* * Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically, * Exim. */ results = executeSimpleCommand("EHLO " + localHost); } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } /* * result contains the results of the EHLO in concatenated form */ boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; for (String result : results) { if (result.matches(".*AUTH.*LOGIN.*$") == true) { authLoginSupported = true; } if (result.matches(".*AUTH.*PLAIN.*$") == true) { authPlainSupported = true; } if (result.matches(".*AUTH.*CRAM-MD5.*$") == true && mAuthType != null && mAuthType.equals("CRAM_MD5")) { authCramMD5Supported = true; } } if (mUsername != null && mUsername.length() > 0 && mPassword != null && mPassword.length() > 0) { if (authCramMD5Supported) { saslAuthCramMD5(mUsername, mPassword); } else if (authPlainSupported) { saslAuthPlain(mUsername, mPassword); } else if (authLoginSupported) { saslAuthLogin(mUsername, mPassword); } else { throw new MessagingException("No valid authentication mechanism found."); } } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
public void open() throws MessagingException { try { SocketAddress socketAddress = new InetSocketAddress(mHost, mPort); if (mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); mSecure = true; } else { mSocket = new Socket(); mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); } // RFC 1047 mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); // Eat the banner executeSimpleCommand(null); InetAddress localAddress = mSocket.getLocalAddress(); String localHost = localAddress.getHostName(); String ipAddr = localAddress.getHostAddress(); if (localHost.equals(ipAddr) || localHost.contains("_")) { // We don't have a FQDN or the hostname contains invalid // characters (see issue 2143), so use IP address. if (localAddress instanceof Inet6Address) { localHost = "[IPV6:" + ipAddr + "]"; } else { localHost = "[" + ipAddr + "]"; } } List<String> results = executeSimpleCommand("EHLO " + localHost); m8bitEncodingAllowed = results.contains("8BITMIME"); /* * TODO may need to add code to fall back to HELO I switched it from * using HELO on non STARTTLS connections because of AOL's mail * server. It won't let you use AUTH without EHLO. * We should really be paying more attention to the capabilities * and only attempting auth if it's available, and warning the user * if not. */ if (mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { if (results.contains("STARTTLS")) { executeSimpleCommand("STARTTLS"); SSLContext sslContext = SSLContext.getInstance("TLS"); boolean secure = mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED; sslContext.init(null, new TrustManager[] { TrustManagerFactory.get(mHost, secure) }, new SecureRandom()); mSocket = sslContext.getSocketFactory().createSocket(mSocket, mHost, mPort, true); mIn = new PeekableInputStream(new BufferedInputStream(mSocket.getInputStream(), 1024)); mOut = mSocket.getOutputStream(); mSecure = true; /* * Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically, * Exim. */ results = executeSimpleCommand("EHLO " + localHost); } else if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED) { throw new MessagingException("TLS not supported but required"); } } /* * result contains the results of the EHLO in concatenated form */ boolean authLoginSupported = false; boolean authPlainSupported = false; boolean authCramMD5Supported = false; for (String result : results) { if (result.matches(".*AUTH.*LOGIN.*$") == true) { authLoginSupported = true; } if (result.matches(".*AUTH.*PLAIN.*$") == true) { authPlainSupported = true; } if (result.matches(".*AUTH.*CRAM-MD5.*$") == true && mAuthType != null && mAuthType.equals("CRAM_MD5")) { authCramMD5Supported = true; } } if (mUsername != null && mUsername.length() > 0 && mPassword != null && mPassword.length() > 0) { if (authCramMD5Supported) { saslAuthCramMD5(mUsername, mPassword); } else if (authPlainSupported) { saslAuthPlain(mUsername, mPassword); } else if (authLoginSupported) { saslAuthLogin(mUsername, mPassword); } else { throw new MessagingException("No valid authentication mechanism found."); } } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } catch (GeneralSecurityException gse) { throw new MessagingException( "Unable to open connection to SMTP server due to security error.", gse); } catch (IOException ioe) { throw new MessagingException("Unable to open connection to SMTP server.", ioe); } }
diff --git a/opal-shell/src/main/java/org/obiba/opal/shell/service/impl/quartz/QuartzCommandSchedulerServiceImpl.java b/opal-shell/src/main/java/org/obiba/opal/shell/service/impl/quartz/QuartzCommandSchedulerServiceImpl.java index 57e13a800..a79f0e785 100644 --- a/opal-shell/src/main/java/org/obiba/opal/shell/service/impl/quartz/QuartzCommandSchedulerServiceImpl.java +++ b/opal-shell/src/main/java/org/obiba/opal/shell/service/impl/quartz/QuartzCommandSchedulerServiceImpl.java @@ -1,112 +1,112 @@ /******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * 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.obiba.opal.shell.service.impl.quartz; import java.util.List; import org.apache.shiro.SecurityUtils; import org.obiba.opal.shell.commands.Command; import org.obiba.opal.shell.service.CommandSchedulerService; import org.obiba.opal.shell.service.CommandSchedulerServiceException; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Quartz-based implementation of {@link CommandSchedulerService}. */ @Component public class QuartzCommandSchedulerServiceImpl implements CommandSchedulerService { private static final Logger log = LoggerFactory.getLogger(QuartzCommandSchedulerServiceImpl.class); private final Scheduler scheduler; @Autowired public QuartzCommandSchedulerServiceImpl(Scheduler scheduler) { this.scheduler = scheduler; } @Override public void addCommand(String name, String group, Command<?> command) { try { JobDetail jobDetail = JobBuilder.newJob(QuartzCommandJob.class) // .withIdentity(name, group) // .storeDurably(true) // OPAL-917 .usingJobData("command", command.toString()) // - .usingJobData("subject", SecurityUtils.getSubject().getPrincipals().toString()) // .build(); + jobDetail.getJobDataMap().put("subject", SecurityUtils.getSubject().getPrincipals()); log.debug("Add job {}", jobDetail); scheduler.addJob(jobDetail, true); } catch(SchedulerException ex) { throw new CommandSchedulerServiceException(ex); } } @Override public void deleteCommand(String name, String group) { try { JobKey jobKey = new JobKey(name, group); log.debug("Delete job {}", jobKey); scheduler.deleteJob(jobKey); } catch(SchedulerException ex) { throw new CommandSchedulerServiceException(ex); } } @Override public void scheduleCommand(String name, String group, String cronExpression) { try { Trigger trigger = TriggerBuilder.newTrigger() // .withIdentity(name + "-trigger", group) // .forJob(name, group) // .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)) // .build(); log.debug("Schedule job {} ({}): {}", trigger.getKey(), cronExpression, trigger); scheduler.scheduleJob(trigger); } catch(SchedulerException ex) { throw new CommandSchedulerServiceException(ex); } } @Override public void unscheduleCommand(String name, String group) { try { for(Trigger trigger : scheduler.getTriggersOfJob(new JobKey(name, group))) { log.debug("Unschedule job {}", trigger); scheduler.unscheduleJob(trigger.getKey()); } } catch(SchedulerException ex) { throw new CommandSchedulerServiceException(ex); } } @Override public String getCommandSchedule(String name, String group) { try { List<? extends Trigger> triggers = scheduler.getTriggersOfJob(new JobKey(name, group)); return triggers != null && !triggers.isEmpty() && triggers.get(0) instanceof CronTrigger // ? ((CronTrigger) triggers.get(0)).getCronExpression() // : null; } catch(SchedulerException ex) { throw new CommandSchedulerServiceException(ex); } } }
false
true
public void addCommand(String name, String group, Command<?> command) { try { JobDetail jobDetail = JobBuilder.newJob(QuartzCommandJob.class) // .withIdentity(name, group) // .storeDurably(true) // OPAL-917 .usingJobData("command", command.toString()) // .usingJobData("subject", SecurityUtils.getSubject().getPrincipals().toString()) // .build(); log.debug("Add job {}", jobDetail); scheduler.addJob(jobDetail, true); } catch(SchedulerException ex) { throw new CommandSchedulerServiceException(ex); } }
public void addCommand(String name, String group, Command<?> command) { try { JobDetail jobDetail = JobBuilder.newJob(QuartzCommandJob.class) // .withIdentity(name, group) // .storeDurably(true) // OPAL-917 .usingJobData("command", command.toString()) // .build(); jobDetail.getJobDataMap().put("subject", SecurityUtils.getSubject().getPrincipals()); log.debug("Add job {}", jobDetail); scheduler.addJob(jobDetail, true); } catch(SchedulerException ex) { throw new CommandSchedulerServiceException(ex); } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/TaskSelectionDialogWithRandom.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/TaskSelectionDialogWithRandom.java index 4c854c771..6041ba5de 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/TaskSelectionDialogWithRandom.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/TaskSelectionDialogWithRandom.java @@ -1,117 +1,120 @@ /******************************************************************************* * Copyright (c) 2004, 2009 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.actions; import java.util.HashSet; import java.util.Random; import java.util.Set; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.mylyn.internal.tasks.core.TaskActivityManager; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.ITask.PriorityLevel; import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; /** * @author Jakub Jurkiewicz * @author Mik Kersten */ public class TaskSelectionDialogWithRandom extends TaskSelectionDialog { private static final int RANDOM_ID = IDialogConstants.CLIENT_ID + 1; private Button randomTaskButton; private boolean activateTask = false; public TaskSelectionDialogWithRandom(Shell parent) { super(parent); } @Override protected void createAdditionalButtons(Composite parent) { randomTaskButton = createButton(parent, RANDOM_ID, Messages.TaskSelectionDialog_Random_Task, false); randomTaskButton.setToolTipText(Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Tooltip); randomTaskButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent se) { try { Set<ITask> selectedTasks = new HashSet<ITask>(); Set<ITask> allScheduled = ((TaskActivityManager) TasksUi.getTaskActivityManager()).getAllScheduledTasks(); if (!allScheduled.isEmpty()) { selectedTasks.addAll(allScheduled); - } else { + // XXX bug 280939 make sure all scheduled tasks actually exist + selectedTasks.retainAll(TasksUiPlugin.getTaskList().getAllTasks()); + } + if (selectedTasks.isEmpty()) { selectedTasks.addAll(TasksUiPlugin.getTaskList().getAllTasks()); } Set<ITask> potentialTasks = new HashSet<ITask>(); addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P5); addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P4); if (potentialTasks.isEmpty()) { addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P3); } if (potentialTasks.isEmpty()) { addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P2); } int randomTaskIndex = new Random().nextInt(potentialTasks.size()); ITask randomTask = potentialTasks.toArray(new ITask[potentialTasks.size()])[randomTaskIndex]; if (activateTask) { TasksUi.getTaskActivityManager().activateTask(randomTask); } TasksUiInternal.refreshAndOpenTaskListElement(randomTask); close(); } catch (Exception e) { MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Error_Title, Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Error); } } private void addLowEnergyTasks(Set<ITask> selectedTasks, Set<ITask> potentialTasks, PriorityLevel priorityLevel) { for (ITask task : selectedTasks) { if (task.getSynchronizationState().isSynchronized() && !task.isCompleted()) { if (priorityLevel.toString().equals(task.getPriority())) { potentialTasks.add(task); } } } } }); } public boolean isActivateTask() { return activateTask; } public void setActivateTask(boolean activateTask) { this.activateTask = activateTask; } }
true
true
protected void createAdditionalButtons(Composite parent) { randomTaskButton = createButton(parent, RANDOM_ID, Messages.TaskSelectionDialog_Random_Task, false); randomTaskButton.setToolTipText(Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Tooltip); randomTaskButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent se) { try { Set<ITask> selectedTasks = new HashSet<ITask>(); Set<ITask> allScheduled = ((TaskActivityManager) TasksUi.getTaskActivityManager()).getAllScheduledTasks(); if (!allScheduled.isEmpty()) { selectedTasks.addAll(allScheduled); } else { selectedTasks.addAll(TasksUiPlugin.getTaskList().getAllTasks()); } Set<ITask> potentialTasks = new HashSet<ITask>(); addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P5); addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P4); if (potentialTasks.isEmpty()) { addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P3); } if (potentialTasks.isEmpty()) { addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P2); } int randomTaskIndex = new Random().nextInt(potentialTasks.size()); ITask randomTask = potentialTasks.toArray(new ITask[potentialTasks.size()])[randomTaskIndex]; if (activateTask) { TasksUi.getTaskActivityManager().activateTask(randomTask); } TasksUiInternal.refreshAndOpenTaskListElement(randomTask); close(); } catch (Exception e) { MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Error_Title, Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Error); } } private void addLowEnergyTasks(Set<ITask> selectedTasks, Set<ITask> potentialTasks, PriorityLevel priorityLevel) { for (ITask task : selectedTasks) { if (task.getSynchronizationState().isSynchronized() && !task.isCompleted()) { if (priorityLevel.toString().equals(task.getPriority())) { potentialTasks.add(task); } } } } }); }
protected void createAdditionalButtons(Composite parent) { randomTaskButton = createButton(parent, RANDOM_ID, Messages.TaskSelectionDialog_Random_Task, false); randomTaskButton.setToolTipText(Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Tooltip); randomTaskButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent se) { try { Set<ITask> selectedTasks = new HashSet<ITask>(); Set<ITask> allScheduled = ((TaskActivityManager) TasksUi.getTaskActivityManager()).getAllScheduledTasks(); if (!allScheduled.isEmpty()) { selectedTasks.addAll(allScheduled); // XXX bug 280939 make sure all scheduled tasks actually exist selectedTasks.retainAll(TasksUiPlugin.getTaskList().getAllTasks()); } if (selectedTasks.isEmpty()) { selectedTasks.addAll(TasksUiPlugin.getTaskList().getAllTasks()); } Set<ITask> potentialTasks = new HashSet<ITask>(); addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P5); addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P4); if (potentialTasks.isEmpty()) { addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P3); } if (potentialTasks.isEmpty()) { addLowEnergyTasks(selectedTasks, potentialTasks, PriorityLevel.P2); } int randomTaskIndex = new Random().nextInt(potentialTasks.size()); ITask randomTask = potentialTasks.toArray(new ITask[potentialTasks.size()])[randomTaskIndex]; if (activateTask) { TasksUi.getTaskActivityManager().activateTask(randomTask); } TasksUiInternal.refreshAndOpenTaskListElement(randomTask); close(); } catch (Exception e) { MessageDialog.openInformation(Display.getDefault().getActiveShell(), Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Error_Title, Messages.TaskSelectionDialogWithRandom_Feeling_Lazy_Error); } } private void addLowEnergyTasks(Set<ITask> selectedTasks, Set<ITask> potentialTasks, PriorityLevel priorityLevel) { for (ITask task : selectedTasks) { if (task.getSynchronizationState().isSynchronized() && !task.isCompleted()) { if (priorityLevel.toString().equals(task.getPriority())) { potentialTasks.add(task); } } } } }); }
diff --git a/EffectGainHealth/src/main/java/multitallented/plugins/herostronghold/effects/EffectGainHealth.java b/EffectGainHealth/src/main/java/multitallented/plugins/herostronghold/effects/EffectGainHealth.java index 447b534..9f92f55 100644 --- a/EffectGainHealth/src/main/java/multitallented/plugins/herostronghold/effects/EffectGainHealth.java +++ b/EffectGainHealth/src/main/java/multitallented/plugins/herostronghold/effects/EffectGainHealth.java @@ -1,95 +1,95 @@ package main.java.multitallented.plugins.herostronghold.effects; import com.herocraftonline.dev.heroes.Heroes; import com.herocraftonline.dev.heroes.hero.Hero; import main.java.multitallented.plugins.herostronghold.Effect; import main.java.multitallented.plugins.herostronghold.HeroStronghold; import main.java.multitallented.plugins.herostronghold.PlayerInRegionEvent; import main.java.multitallented.plugins.herostronghold.Region; import main.java.multitallented.plugins.herostronghold.RegionManager; import main.java.multitallented.plugins.herostronghold.RegionType; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.CustomEventListener; import org.bukkit.event.Event; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Type; /** * * @author Multitallented */ public class EffectGainHealth extends Effect { public final HeroStronghold aPlugin; public EffectGainHealth(HeroStronghold plugin) { super(plugin); this.aPlugin = plugin; registerEvent(Type.CUSTOM_EVENT, new IntruderListener(this), Priority.Highest); } @Override public void init(HeroStronghold plugin) { super.init(plugin); } public class IntruderListener extends CustomEventListener { private final EffectGainHealth effect; public IntruderListener(EffectGainHealth effect) { this.effect = effect; } @Override public void onCustomEvent(Event event) { if (!(event instanceof PlayerInRegionEvent)) return; PlayerInRegionEvent pIREvent = (PlayerInRegionEvent) event; Player player = pIREvent.getPlayer(); Hero hero = null; Heroes heroes = effect.aPlugin.getHeroes(); if (heroes != null) hero = heroes.getHeroManager().getHero(player); if (hero == null) { if (player.getHealth() == 20) return; } else if (hero.getHealth() == hero.getMaxHealth()) return; //Check if the region has the shoot arrow effect and return arrow velocity int addHealth = effect.regionHasEffect(pIREvent.getEffects(), "gainhealth"); if (addHealth == 0) return; Location l = pIREvent.getRegionLocation(); RegionManager rm = effect.getPlugin().getRegionManager(); Region r = rm.getRegion(l); RegionType rt = rm.getRegionType(r.getType()); //Check if the player owns or is a member of the region if (!effect.isOwnerOfRegion(player, l) && !effect.isMemberOfRegion(player, l) && hero == null) { return; - } else if (!rt.containsFriendlyClass(hero.getHeroClass().getName())) { + } else if (hero != null && !rt.containsFriendlyClass(hero.getHeroClass().getName())) { return; } //Check to see if the HeroStronghold has enough reagents if (!effect.hasReagents(l)) return; //Run upkeep but don't need to know if upkeep occured effect.forceUpkeep(l); //grant the player food if (hero == null) { if (player.getHealth() + addHealth <= 20) { player.setHealth(player.getHealth() + addHealth); } else { player.setHealth(20); } } else if (hero.getHealth() + addHealth <= hero.getMaxHealth()) { hero.setHealth(hero.getHealth() + addHealth); } else { hero.setHealth(hero.getMaxHealth()); } } } }
true
true
public void onCustomEvent(Event event) { if (!(event instanceof PlayerInRegionEvent)) return; PlayerInRegionEvent pIREvent = (PlayerInRegionEvent) event; Player player = pIREvent.getPlayer(); Hero hero = null; Heroes heroes = effect.aPlugin.getHeroes(); if (heroes != null) hero = heroes.getHeroManager().getHero(player); if (hero == null) { if (player.getHealth() == 20) return; } else if (hero.getHealth() == hero.getMaxHealth()) return; //Check if the region has the shoot arrow effect and return arrow velocity int addHealth = effect.regionHasEffect(pIREvent.getEffects(), "gainhealth"); if (addHealth == 0) return; Location l = pIREvent.getRegionLocation(); RegionManager rm = effect.getPlugin().getRegionManager(); Region r = rm.getRegion(l); RegionType rt = rm.getRegionType(r.getType()); //Check if the player owns or is a member of the region if (!effect.isOwnerOfRegion(player, l) && !effect.isMemberOfRegion(player, l) && hero == null) { return; } else if (!rt.containsFriendlyClass(hero.getHeroClass().getName())) { return; } //Check to see if the HeroStronghold has enough reagents if (!effect.hasReagents(l)) return; //Run upkeep but don't need to know if upkeep occured effect.forceUpkeep(l); //grant the player food if (hero == null) { if (player.getHealth() + addHealth <= 20) { player.setHealth(player.getHealth() + addHealth); } else { player.setHealth(20); } } else if (hero.getHealth() + addHealth <= hero.getMaxHealth()) { hero.setHealth(hero.getHealth() + addHealth); } else { hero.setHealth(hero.getMaxHealth()); } }
public void onCustomEvent(Event event) { if (!(event instanceof PlayerInRegionEvent)) return; PlayerInRegionEvent pIREvent = (PlayerInRegionEvent) event; Player player = pIREvent.getPlayer(); Hero hero = null; Heroes heroes = effect.aPlugin.getHeroes(); if (heroes != null) hero = heroes.getHeroManager().getHero(player); if (hero == null) { if (player.getHealth() == 20) return; } else if (hero.getHealth() == hero.getMaxHealth()) return; //Check if the region has the shoot arrow effect and return arrow velocity int addHealth = effect.regionHasEffect(pIREvent.getEffects(), "gainhealth"); if (addHealth == 0) return; Location l = pIREvent.getRegionLocation(); RegionManager rm = effect.getPlugin().getRegionManager(); Region r = rm.getRegion(l); RegionType rt = rm.getRegionType(r.getType()); //Check if the player owns or is a member of the region if (!effect.isOwnerOfRegion(player, l) && !effect.isMemberOfRegion(player, l) && hero == null) { return; } else if (hero != null && !rt.containsFriendlyClass(hero.getHeroClass().getName())) { return; } //Check to see if the HeroStronghold has enough reagents if (!effect.hasReagents(l)) return; //Run upkeep but don't need to know if upkeep occured effect.forceUpkeep(l); //grant the player food if (hero == null) { if (player.getHealth() + addHealth <= 20) { player.setHealth(player.getHealth() + addHealth); } else { player.setHealth(20); } } else if (hero.getHealth() + addHealth <= hero.getMaxHealth()) { hero.setHealth(hero.getHealth() + addHealth); } else { hero.setHealth(hero.getMaxHealth()); } }
diff --git a/src/groovy/org/pillarone/riskanalytics/application/Main.java b/src/groovy/org/pillarone/riskanalytics/application/Main.java index b99be6ac..da270c59 100644 --- a/src/groovy/org/pillarone/riskanalytics/application/Main.java +++ b/src/groovy/org/pillarone/riskanalytics/application/Main.java @@ -1,71 +1,74 @@ package org.pillarone.riskanalytics.application; import grails.util.GrailsUtil; import groovy.lang.ExpandoMetaClass; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.commons.BootstrapArtefactHandler; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsBootstrapClass; import org.codehaus.groovy.grails.commons.GrailsClass; import org.pillarone.riskanalytics.application.initialization.DatabaseManagingSessionStateListener; import org.pillarone.riskanalytics.application.initialization.IExternalDatabaseSupport; import org.pillarone.riskanalytics.application.initialization.StandaloneConfigLoader; import org.pillarone.riskanalytics.application.ui.P1RATStandaloneLauncher; import org.springframework.context.ApplicationContext; /** * Starting point of the standalone application. * Initializes log4j and starts grails, then executes all BootStraps and starts the UI. */ public class Main { private static Log LOG = LogFactory.getLog(Main.class); public static void main(String args[]) { launchApplication(null); } public static void launchApplication(IExternalDatabaseSupport databaseSupport) { try { String environment = System.getProperty("grails.env"); if (environment == null) { environment = "development"; System.setProperty("grails.env", environment); } StandaloneConfigLoader.loadLog4JConfig(environment); LOG.info("Starting RiskAnalytics with environment " + environment); if(databaseSupport != null) { LOG.info("Starting external database for environment " + environment); databaseSupport.startDatabase(); } LOG.info("Loading grails.."); ExpandoMetaClass.enableGlobally(); ApplicationContext ctx = GrailsUtil.bootstrapGrailsFromClassPath(); GrailsApplication app = (GrailsApplication) ctx.getBean(GrailsApplication.APPLICATION_ID); LOG.info("Executing bootstraps.."); GrailsClass[] bootstraps = app.getArtefacts(BootstrapArtefactHandler.TYPE); for (GrailsClass bootstrap : bootstraps) { final GrailsBootstrapClass bootstrapClass = (GrailsBootstrapClass) bootstrap; //Quartz bootstrap needs a servlet context if (!bootstrapClass.getClazz().getSimpleName().startsWith("Quartz")) { bootstrapClass.callInit(null); } } LOG.info("Loading user interface.."); if (databaseSupport == null) { P1RATStandaloneLauncher.start(); } else { P1RATStandaloneLauncher.start(new DatabaseManagingSessionStateListener(databaseSupport)); } } catch (Exception e) { LOG.fatal("Startup failed", e); + if (databaseSupport != null) { + databaseSupport.stopDatabase(); + } } } }
true
true
public static void launchApplication(IExternalDatabaseSupport databaseSupport) { try { String environment = System.getProperty("grails.env"); if (environment == null) { environment = "development"; System.setProperty("grails.env", environment); } StandaloneConfigLoader.loadLog4JConfig(environment); LOG.info("Starting RiskAnalytics with environment " + environment); if(databaseSupport != null) { LOG.info("Starting external database for environment " + environment); databaseSupport.startDatabase(); } LOG.info("Loading grails.."); ExpandoMetaClass.enableGlobally(); ApplicationContext ctx = GrailsUtil.bootstrapGrailsFromClassPath(); GrailsApplication app = (GrailsApplication) ctx.getBean(GrailsApplication.APPLICATION_ID); LOG.info("Executing bootstraps.."); GrailsClass[] bootstraps = app.getArtefacts(BootstrapArtefactHandler.TYPE); for (GrailsClass bootstrap : bootstraps) { final GrailsBootstrapClass bootstrapClass = (GrailsBootstrapClass) bootstrap; //Quartz bootstrap needs a servlet context if (!bootstrapClass.getClazz().getSimpleName().startsWith("Quartz")) { bootstrapClass.callInit(null); } } LOG.info("Loading user interface.."); if (databaseSupport == null) { P1RATStandaloneLauncher.start(); } else { P1RATStandaloneLauncher.start(new DatabaseManagingSessionStateListener(databaseSupport)); } } catch (Exception e) { LOG.fatal("Startup failed", e); } }
public static void launchApplication(IExternalDatabaseSupport databaseSupport) { try { String environment = System.getProperty("grails.env"); if (environment == null) { environment = "development"; System.setProperty("grails.env", environment); } StandaloneConfigLoader.loadLog4JConfig(environment); LOG.info("Starting RiskAnalytics with environment " + environment); if(databaseSupport != null) { LOG.info("Starting external database for environment " + environment); databaseSupport.startDatabase(); } LOG.info("Loading grails.."); ExpandoMetaClass.enableGlobally(); ApplicationContext ctx = GrailsUtil.bootstrapGrailsFromClassPath(); GrailsApplication app = (GrailsApplication) ctx.getBean(GrailsApplication.APPLICATION_ID); LOG.info("Executing bootstraps.."); GrailsClass[] bootstraps = app.getArtefacts(BootstrapArtefactHandler.TYPE); for (GrailsClass bootstrap : bootstraps) { final GrailsBootstrapClass bootstrapClass = (GrailsBootstrapClass) bootstrap; //Quartz bootstrap needs a servlet context if (!bootstrapClass.getClazz().getSimpleName().startsWith("Quartz")) { bootstrapClass.callInit(null); } } LOG.info("Loading user interface.."); if (databaseSupport == null) { P1RATStandaloneLauncher.start(); } else { P1RATStandaloneLauncher.start(new DatabaseManagingSessionStateListener(databaseSupport)); } } catch (Exception e) { LOG.fatal("Startup failed", e); if (databaseSupport != null) { databaseSupport.stopDatabase(); } } }
diff --git a/src/org/flowvisor/message/FVPortMod.java b/src/org/flowvisor/message/FVPortMod.java index d6ff01a..bfcd85f 100644 --- a/src/org/flowvisor/message/FVPortMod.java +++ b/src/org/flowvisor/message/FVPortMod.java @@ -1,50 +1,50 @@ package org.flowvisor.message; import org.flowvisor.classifier.FVClassifier; import org.flowvisor.log.FVLog; import org.flowvisor.log.LogLevel; import org.flowvisor.slicer.FVSlicer; import org.openflow.protocol.OFPhysicalPort; import org.openflow.protocol.OFPortMod; import org.openflow.protocol.OFError.OFPortModFailedCode; public class FVPortMod extends OFPortMod implements Classifiable, Slicable { /** * Send to all slices with this port * * FIXME: decide if port_mod's can come *up* from switch? */ @Override public void classifyFromSwitch(FVClassifier fvClassifier) { FVLog.log(LogLevel.DEBUG, fvClassifier, "recv from switch: " + this); for (FVSlicer fvSlicer : fvClassifier.getSlicers()) if (fvSlicer.portInSlice(this.portNumber)) fvSlicer.sendMsg(this, fvClassifier); } /** * First, check to see if this port is available in this slice Second, check * to see if they're changing the FLOOD bit FIXME: prevent slices from * administratrively bringing down a port! */ @Override public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) { // First, check if this port is in the slice if (!fvSlicer.portInSlice(this.portNumber)) { fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg( OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier); return; } // Second, update the port's flood state boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber); FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " + ((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.getValue()) == 0)); fvSlicer.setFloodPortStatus(this.portNumber, (this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD - .ordinal()) == 0); + .getValue()) == 0); if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber)) FVLog.log(LogLevel.CRIT, fvSlicer, "FIXME: need to implement FLOODING port changes"); } }
true
true
public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) { // First, check if this port is in the slice if (!fvSlicer.portInSlice(this.portNumber)) { fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg( OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier); return; } // Second, update the port's flood state boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber); FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " + ((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.getValue()) == 0)); fvSlicer.setFloodPortStatus(this.portNumber, (this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD .ordinal()) == 0); if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber)) FVLog.log(LogLevel.CRIT, fvSlicer, "FIXME: need to implement FLOODING port changes"); }
public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) { // First, check if this port is in the slice if (!fvSlicer.portInSlice(this.portNumber)) { fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg( OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier); return; } // Second, update the port's flood state boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber); FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " + ((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.getValue()) == 0)); fvSlicer.setFloodPortStatus(this.portNumber, (this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD .getValue()) == 0); if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber)) FVLog.log(LogLevel.CRIT, fvSlicer, "FIXME: need to implement FLOODING port changes"); }
diff --git a/src/grepJar/Main.java b/src/grepJar/Main.java index 3f85b1b..f6035ce 100644 --- a/src/grepJar/Main.java +++ b/src/grepJar/Main.java @@ -1,32 +1,32 @@ package grepJar; import java.io.File; import java.util.regex.Pattern; /** * Entry point for the utility * @author Luke Sandberg * Oct 28, 2010 */ public class Main { public static void main(String[] args) { if (args.length > 2 || args.length < 1) { System.out.println("Usage: java -jar jarFinder.jar <regex> [directory]\n\t[Directory] defaults to the Current Dir if not provided."); return; } Pattern pat = Pattern.compile(args[0], Pattern.CASE_INSENSITIVE); File dir = new File("."); if (args.length == 2) { - dir = new File(args[0]); + dir = new File(args[1]); } for (File jar : new JarFinder(dir)) { String sn; if ((sn = JarSearcher.search(jar, pat)) != null) { System.out.println(jar.getPath() + "\t" + sn); } } } }
true
true
public static void main(String[] args) { if (args.length > 2 || args.length < 1) { System.out.println("Usage: java -jar jarFinder.jar <regex> [directory]\n\t[Directory] defaults to the Current Dir if not provided."); return; } Pattern pat = Pattern.compile(args[0], Pattern.CASE_INSENSITIVE); File dir = new File("."); if (args.length == 2) { dir = new File(args[0]); } for (File jar : new JarFinder(dir)) { String sn; if ((sn = JarSearcher.search(jar, pat)) != null) { System.out.println(jar.getPath() + "\t" + sn); } } }
public static void main(String[] args) { if (args.length > 2 || args.length < 1) { System.out.println("Usage: java -jar jarFinder.jar <regex> [directory]\n\t[Directory] defaults to the Current Dir if not provided."); return; } Pattern pat = Pattern.compile(args[0], Pattern.CASE_INSENSITIVE); File dir = new File("."); if (args.length == 2) { dir = new File(args[1]); } for (File jar : new JarFinder(dir)) { String sn; if ((sn = JarSearcher.search(jar, pat)) != null) { System.out.println(jar.getPath() + "\t" + sn); } } }
diff --git a/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java b/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java index 12ff06012..81f0bb506 100644 --- a/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java +++ b/org.amanzi.awe.render.network/src/org/amanzi/awe/render/network/NetworkRenderer.java @@ -1,345 +1,348 @@ package org.amanzi.awe.render.network; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.io.IOException; import java.util.ArrayList; import net.refractions.udig.catalog.IGeoResource; import net.refractions.udig.project.ILayer; import net.refractions.udig.project.IStyleBlackboard; import net.refractions.udig.project.internal.render.impl.RendererImpl; import net.refractions.udig.project.render.RenderException; import org.amanzi.awe.catalog.neo.GeoNeo; import org.amanzi.awe.catalog.neo.GeoNeo.GeoNode; import org.amanzi.awe.neostyle.NeoStyle; import org.amanzi.awe.neostyle.NeoStyleContent; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.geotools.geometry.jts.JTS; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.neo4j.api.core.Direction; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Envelope; public class NetworkRenderer extends RendererImpl { private static final Color COLOR_SELECTED = Color.RED; private static final Color COLOR_LESS = Color.BLUE; private static final Color COLOR_MORE = Color.GREEN; private static final Color COLOR_SITE_SELECTED = Color.CYAN; private static final Color COLOR_SECTOR_SELECTED = Color.CYAN; private AffineTransform base_transform = null; // save original graphics transform for repeated re-use private Color drawColor = Color.DARK_GRAY; private Color siteColor = new Color(128, 128, 128,(int)(0.6*255.0)); private Color fillColor = new Color(255, 255, 128,(int)(0.6*255.0)); private MathTransform transform_d2w; private MathTransform transform_w2d; private Color labelColor; private void setCrsTransforms(CoordinateReferenceSystem dataCrs) throws FactoryException{ boolean lenient = true; // needs to be lenient to work on uDIG 1.1 (otherwise we get error: bursa wolf parameters required CoordinateReferenceSystem worldCrs = context.getCRS(); this.transform_d2w = CRS.findMathTransform(dataCrs, worldCrs, lenient); this.transform_w2d = CRS.findMathTransform(worldCrs, dataCrs, lenient); // could use transform_d2w.inverse() also } private Envelope getTransformedBounds() throws TransformException { ReferencedEnvelope bounds = getRenderBounds(); if (bounds == null) { bounds = this.context.getViewportModel().getBounds(); } Envelope bounds_transformed = null; if (bounds != null && transform_w2d != null) { bounds_transformed = JTS.transform(bounds, transform_w2d); } return bounds_transformed; } /** * This method is called to render what it can. It is passed a graphics context * with which it can draw. The class already contains a reference to a RenderContext * from which it can obtain the layer and the GeoResource to render. * @see net.refractions.udig.project.internal.render.impl.RendererImpl#render(java.awt.Graphics2D, org.eclipse.core.runtime.IProgressMonitor) */ @Override public void render( Graphics2D g, IProgressMonitor monitor ) throws RenderException { ILayer layer = getContext().getLayer(); // Are there any resources in the layer that respond to the GeoNeo class (should be the case if we found a Neo4J database with GeoNeo data) IGeoResource resource = layer.findGeoResource(GeoNeo.class); if(resource != null){ renderGeoNeo(g,resource,monitor); } } /** * This method is called to render data from the Neo4j 'GeoNeo' Geo-Resource. */ private void renderGeoNeo( Graphics2D g, IGeoResource neoGeoResource, IProgressMonitor monitor ) throws RenderException { if (monitor == null) monitor = new NullProgressMonitor(); monitor.beginTask("render network sites and sectors", IProgressMonitor.UNKNOWN); // TODO: Get size from info GeoNeo geoNeo = null; // Setup default drawing parameters and thresholds (to be modified by style if found) int drawSize=15; int transparency = (int)(0.6*255.0); int maxSitesLabel = 30; int maxSitesFull = 100; int maxSitesLite = 1000; boolean scaleSectors = true; IStyleBlackboard style = getContext().getLayer().getStyleBlackboard(); NeoStyle neostyle = (NeoStyle)style.get(NeoStyleContent.ID ); if (neostyle!=null){ - //siteColor=neostyle.getSiteFill(); - fillColor=neostyle.getFill(); - drawColor=neostyle.getLine(); - labelColor=neostyle.getLabel(); - drawSize = neostyle.getSymbolSize(); - transparency = (int)((double)neostyle.getSectorTransparency() / 100.0 * 255.0); - maxSitesLabel = neostyle.getLabeling(); - maxSitesFull = neostyle.getSmallSymb(); - maxSitesLite = neostyle.getSmallestSymb(); - scaleSectors = !neostyle.isFixSymbolSize(); - //TODO: get drawSite, transparency, maxSitesLabel, maxSitesFull, maxSitesLite and scaleSectors from style + try { + //siteColor=neostyle.getSiteFill(); + fillColor=neostyle.getFill(); + drawColor=neostyle.getLine(); + labelColor=neostyle.getLabel(); + drawSize = neostyle.getSymbolSize(); + transparency = (int)((double)neostyle.getSectorTransparency() / 100.0 * 255.0); + maxSitesLabel = neostyle.getLabeling(); + maxSitesFull = neostyle.getSmallSymb(); + maxSitesLite = neostyle.getSmallestSymb(); + scaleSectors = !neostyle.isFixSymbolSize(); + } catch (Exception e) { + //TODO: we can get here if an old style exists, and we have added new fields + } } siteColor = new Color(siteColor.getRed(), siteColor.getGreen(), siteColor.getBlue(), transparency); fillColor = new Color(fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue(), transparency); try { monitor.subTask("connecting"); geoNeo = neoGeoResource.resolve(GeoNeo.class, new SubProgressMonitor(monitor, 10)); String selectedProp = geoNeo.getPropertyName(); Double redMinValue = geoNeo.getPropertyValueMin(); Double redMaxValue = geoNeo.getPropertyValueMax(); Double lesMinValue = geoNeo.getMinPropertyValue(); Double moreMaxValue = geoNeo.getMaxPropertyValue(); setCrsTransforms(neoGeoResource.getInfo(null).getCRS()); Envelope bounds_transformed = getTransformedBounds(); Envelope data_bounds = geoNeo.getBounds(); boolean drawFull = true; boolean drawLite = true; boolean drawLabels = true; if (bounds_transformed == null) { drawFull = false; drawLite = false; drawLabels = false; }else if (data_bounds != null && data_bounds.getHeight()>0 && data_bounds.getWidth()>0) { double dataScaled = (bounds_transformed.getHeight() * bounds_transformed.getWidth()) / (data_bounds.getHeight() * data_bounds.getWidth()); double countScaled = dataScaled * geoNeo.getCount(); drawLabels = countScaled < maxSitesLabel; drawFull = countScaled < maxSitesFull; drawLite = countScaled < maxSitesLite; if (drawFull && scaleSectors) { drawSize *= Math.sqrt(maxSitesFull) / (3 * Math.sqrt(countScaled)); } } g.setColor(drawColor); int count = 0; monitor.subTask("drawing"); Coordinate world_location = new Coordinate(); // single object for re-use in transform below (minimize object creation) for(GeoNode node:geoNeo.getGeoNodes()) { Coordinate location = node.getCoordinate(); if (bounds_transformed != null && !bounds_transformed.contains(location)) { continue; // Don't draw points outside viewport } try { JTS.transform(location, world_location, transform_d2w); } catch (Exception e) { //JTS.transform(location, world_location, transform_w2d.inverse()); } java.awt.Point p = getContext().worldToPixel(world_location); Color borderColor = g.getColor(); if (geoNeo.getSelectedNodes().contains(node.getNode())) { borderColor = COLOR_SITE_SELECTED; } renderSite(g, p, borderColor, siteColor, drawSize, drawFull, drawLite); if (drawFull) { int countOmnis = 0; double[] label_position_angles = new double[] {0, 90}; try { int s = 0; for (Relationship relationship : node.getNode().getRelationships(Direction.OUTGOING)) { // for(Relationship // relationship:node.getNode().getRelationships(NetworkLoader.NetworkRelationshipTypes.CHILD, // Direction.OUTGOING)){ Node child = relationship.getEndNode(); if (child.hasProperty("type") && child.getProperty("type").toString().equals("sector")) { double azimuth = -0.0; double beamwidth = 360.0; Color colorToFill = fillColor; for (String key : child.getPropertyKeys()) { if (key.toLowerCase().contains("azimuth")) { Object value = child.getProperty(key); if (value instanceof Integer) { azimuth = (Integer)value; } else { try { azimuth = Integer.parseInt(value.toString()); } catch (Exception e) { } } } if (key.toLowerCase().contains("beamwidth")) { beamwidth = (Integer)child.getProperty(key); } else if (key.toLowerCase().startsWith("beam")) { Object value = child.getProperty(key); if (value instanceof Integer) { beamwidth = (Integer)value; } else { try { beamwidth = Integer.parseInt(value.toString()); } catch (Exception e) { } } } if (selectedProp != null && selectedProp.equals(key)) { double value = ((Number)child.getProperty(key)).doubleValue(); if (value < redMaxValue || value == redMinValue) { if (value >= redMinValue) { colorToFill = COLOR_SELECTED; } else if (value >= lesMinValue) { colorToFill = COLOR_LESS; } } else if (value < moreMaxValue) { colorToFill = COLOR_MORE; } } } if(azimuth == -0.0) continue; borderColor = drawColor; if (geoNeo.getSelectedNodes().contains(child)) { borderColor = COLOR_SECTOR_SELECTED; } renderSector(g, p, azimuth, beamwidth, colorToFill, borderColor, drawSize); if (s < label_position_angles.length) { label_position_angles[s] = azimuth; } // g.setColor(drawColor); // g.rotate(-Math.toRadians(beamwidth/2)); // g.drawString(sector.getString("name"),drawSize,0); if(beamwidth==360) countOmnis++; s++; } } } finally { if (base_transform != null) { // recover the normal transform g.setTransform(base_transform); g.setColor(drawColor); } } if (countOmnis>1) { System.err.println("Site "+node+" had "+countOmnis+" omni antennas"); } if (drawLabels) { double label_position_angle = Math.toRadians(-90 + (label_position_angles[0] + label_position_angles[1]) / 2.0); int label_x = 5 + (int)(10 * Math.cos(label_position_angle)); int label_y = (int)(10 * Math.sin(label_position_angle)); g.setColor(labelColor); g.drawString(node.toString(), p.x + label_x, p.y + label_y); } g.setTransform(base_transform); } monitor.worked(1); count++; if (monitor.isCanceled()) break; } } catch (TransformException e) { throw new RenderException(e); } catch (FactoryException e) { throw new RenderException(e); } catch (IOException e) { throw new RenderException(e); // rethrow any exceptions encountered } finally { // if (geoNeo != null) // geoNeo.close(); monitor.done(); } } /** * Render the sector symbols based on the point and azimuth. * We simply save the graphics transform, then modify the graphics * through the appropriate transformations (origin to site, and rotations * for drawing the lines and arcs). * @param g * @param p * @param azimuth */ private void renderSector(Graphics2D g, java.awt.Point p, double azimuth, double beamwidth, Color fillColor, Color borderColor, int drawSize) { Color oldColor = g.getColor(); if(base_transform==null) base_transform = g.getTransform(); if(beamwidth<10) beamwidth = 10; g.setTransform(base_transform); g.translate(p.x, p.y); if (beamwidth >= 360.0) { g.setColor(fillColor); g.fillOval(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize); g.setColor(borderColor); g.drawOval(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize); } else { g.rotate(Math.toRadians(-90 + azimuth - beamwidth / 2.0)); g.setColor(fillColor); g.fillArc(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize, 0, -(int)beamwidth); g.setColor(borderColor); g.drawArc(-drawSize, -drawSize, 2 * drawSize, 2 * drawSize, 0, -(int)beamwidth); g.drawLine(0, 0, drawSize, 0); g.rotate(Math.toRadians(beamwidth)); g.drawLine(0, 0, drawSize, 0); g.setColor(oldColor); } } /** * This one is very simple, just draw a circle at the site location. * * @param g * @param p * @param borderColor * @param drawSize */ private void renderSite(Graphics2D g, java.awt.Point p, Color borderColor, Color fillColor, int drawSize, boolean drawFull, boolean drawLite) { Color oldColor = g.getColor(); if (drawFull) { drawSize /= 4; if (drawSize < 2) drawSize = 2; g.setColor(fillColor); g.fillOval(p.x - drawSize, p.y - drawSize, 2 * drawSize, 2 * drawSize); g.setColor(borderColor); g.drawOval(p.x - drawSize, p.y - drawSize, 2 * drawSize, 2 * drawSize); } else if (drawLite) { g.setColor(borderColor); g.drawOval(p.x - 5, p.y - 5, 10, 10); } else { g.setColor(borderColor); g.drawRect(p.x - 1, p.y - 1, 3, 3); } g.setColor(oldColor); } @Override public void render( IProgressMonitor monitor ) throws RenderException { Graphics2D g = getContext().getImage().createGraphics(); render(g, monitor); } }
true
true
private void renderGeoNeo( Graphics2D g, IGeoResource neoGeoResource, IProgressMonitor monitor ) throws RenderException { if (monitor == null) monitor = new NullProgressMonitor(); monitor.beginTask("render network sites and sectors", IProgressMonitor.UNKNOWN); // TODO: Get size from info GeoNeo geoNeo = null; // Setup default drawing parameters and thresholds (to be modified by style if found) int drawSize=15; int transparency = (int)(0.6*255.0); int maxSitesLabel = 30; int maxSitesFull = 100; int maxSitesLite = 1000; boolean scaleSectors = true; IStyleBlackboard style = getContext().getLayer().getStyleBlackboard(); NeoStyle neostyle = (NeoStyle)style.get(NeoStyleContent.ID ); if (neostyle!=null){ //siteColor=neostyle.getSiteFill(); fillColor=neostyle.getFill(); drawColor=neostyle.getLine(); labelColor=neostyle.getLabel(); drawSize = neostyle.getSymbolSize(); transparency = (int)((double)neostyle.getSectorTransparency() / 100.0 * 255.0); maxSitesLabel = neostyle.getLabeling(); maxSitesFull = neostyle.getSmallSymb(); maxSitesLite = neostyle.getSmallestSymb(); scaleSectors = !neostyle.isFixSymbolSize(); //TODO: get drawSite, transparency, maxSitesLabel, maxSitesFull, maxSitesLite and scaleSectors from style } siteColor = new Color(siteColor.getRed(), siteColor.getGreen(), siteColor.getBlue(), transparency); fillColor = new Color(fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue(), transparency); try { monitor.subTask("connecting"); geoNeo = neoGeoResource.resolve(GeoNeo.class, new SubProgressMonitor(monitor, 10)); String selectedProp = geoNeo.getPropertyName(); Double redMinValue = geoNeo.getPropertyValueMin(); Double redMaxValue = geoNeo.getPropertyValueMax(); Double lesMinValue = geoNeo.getMinPropertyValue(); Double moreMaxValue = geoNeo.getMaxPropertyValue(); setCrsTransforms(neoGeoResource.getInfo(null).getCRS()); Envelope bounds_transformed = getTransformedBounds(); Envelope data_bounds = geoNeo.getBounds(); boolean drawFull = true; boolean drawLite = true; boolean drawLabels = true; if (bounds_transformed == null) { drawFull = false; drawLite = false; drawLabels = false; }else if (data_bounds != null && data_bounds.getHeight()>0 && data_bounds.getWidth()>0) { double dataScaled = (bounds_transformed.getHeight() * bounds_transformed.getWidth()) / (data_bounds.getHeight() * data_bounds.getWidth()); double countScaled = dataScaled * geoNeo.getCount(); drawLabels = countScaled < maxSitesLabel; drawFull = countScaled < maxSitesFull; drawLite = countScaled < maxSitesLite; if (drawFull && scaleSectors) { drawSize *= Math.sqrt(maxSitesFull) / (3 * Math.sqrt(countScaled)); } } g.setColor(drawColor); int count = 0; monitor.subTask("drawing"); Coordinate world_location = new Coordinate(); // single object for re-use in transform below (minimize object creation) for(GeoNode node:geoNeo.getGeoNodes()) { Coordinate location = node.getCoordinate(); if (bounds_transformed != null && !bounds_transformed.contains(location)) { continue; // Don't draw points outside viewport } try { JTS.transform(location, world_location, transform_d2w); } catch (Exception e) { //JTS.transform(location, world_location, transform_w2d.inverse()); } java.awt.Point p = getContext().worldToPixel(world_location); Color borderColor = g.getColor(); if (geoNeo.getSelectedNodes().contains(node.getNode())) { borderColor = COLOR_SITE_SELECTED; } renderSite(g, p, borderColor, siteColor, drawSize, drawFull, drawLite); if (drawFull) { int countOmnis = 0; double[] label_position_angles = new double[] {0, 90}; try { int s = 0; for (Relationship relationship : node.getNode().getRelationships(Direction.OUTGOING)) { // for(Relationship // relationship:node.getNode().getRelationships(NetworkLoader.NetworkRelationshipTypes.CHILD, // Direction.OUTGOING)){ Node child = relationship.getEndNode(); if (child.hasProperty("type") && child.getProperty("type").toString().equals("sector")) { double azimuth = -0.0; double beamwidth = 360.0; Color colorToFill = fillColor; for (String key : child.getPropertyKeys()) { if (key.toLowerCase().contains("azimuth")) { Object value = child.getProperty(key); if (value instanceof Integer) { azimuth = (Integer)value; } else { try { azimuth = Integer.parseInt(value.toString()); } catch (Exception e) { } } } if (key.toLowerCase().contains("beamwidth")) { beamwidth = (Integer)child.getProperty(key); } else if (key.toLowerCase().startsWith("beam")) { Object value = child.getProperty(key); if (value instanceof Integer) { beamwidth = (Integer)value; } else { try { beamwidth = Integer.parseInt(value.toString()); } catch (Exception e) { } } } if (selectedProp != null && selectedProp.equals(key)) { double value = ((Number)child.getProperty(key)).doubleValue(); if (value < redMaxValue || value == redMinValue) { if (value >= redMinValue) { colorToFill = COLOR_SELECTED; } else if (value >= lesMinValue) { colorToFill = COLOR_LESS; } } else if (value < moreMaxValue) { colorToFill = COLOR_MORE; } } } if(azimuth == -0.0) continue; borderColor = drawColor; if (geoNeo.getSelectedNodes().contains(child)) { borderColor = COLOR_SECTOR_SELECTED; } renderSector(g, p, azimuth, beamwidth, colorToFill, borderColor, drawSize); if (s < label_position_angles.length) { label_position_angles[s] = azimuth; } // g.setColor(drawColor); // g.rotate(-Math.toRadians(beamwidth/2)); // g.drawString(sector.getString("name"),drawSize,0); if(beamwidth==360) countOmnis++; s++; } } } finally { if (base_transform != null) { // recover the normal transform g.setTransform(base_transform); g.setColor(drawColor); } } if (countOmnis>1) { System.err.println("Site "+node+" had "+countOmnis+" omni antennas"); } if (drawLabels) { double label_position_angle = Math.toRadians(-90 + (label_position_angles[0] + label_position_angles[1]) / 2.0); int label_x = 5 + (int)(10 * Math.cos(label_position_angle)); int label_y = (int)(10 * Math.sin(label_position_angle)); g.setColor(labelColor); g.drawString(node.toString(), p.x + label_x, p.y + label_y); } g.setTransform(base_transform); } monitor.worked(1); count++; if (monitor.isCanceled()) break; } } catch (TransformException e) { throw new RenderException(e); } catch (FactoryException e) { throw new RenderException(e); } catch (IOException e) { throw new RenderException(e); // rethrow any exceptions encountered } finally { // if (geoNeo != null) // geoNeo.close(); monitor.done(); } }
private void renderGeoNeo( Graphics2D g, IGeoResource neoGeoResource, IProgressMonitor monitor ) throws RenderException { if (monitor == null) monitor = new NullProgressMonitor(); monitor.beginTask("render network sites and sectors", IProgressMonitor.UNKNOWN); // TODO: Get size from info GeoNeo geoNeo = null; // Setup default drawing parameters and thresholds (to be modified by style if found) int drawSize=15; int transparency = (int)(0.6*255.0); int maxSitesLabel = 30; int maxSitesFull = 100; int maxSitesLite = 1000; boolean scaleSectors = true; IStyleBlackboard style = getContext().getLayer().getStyleBlackboard(); NeoStyle neostyle = (NeoStyle)style.get(NeoStyleContent.ID ); if (neostyle!=null){ try { //siteColor=neostyle.getSiteFill(); fillColor=neostyle.getFill(); drawColor=neostyle.getLine(); labelColor=neostyle.getLabel(); drawSize = neostyle.getSymbolSize(); transparency = (int)((double)neostyle.getSectorTransparency() / 100.0 * 255.0); maxSitesLabel = neostyle.getLabeling(); maxSitesFull = neostyle.getSmallSymb(); maxSitesLite = neostyle.getSmallestSymb(); scaleSectors = !neostyle.isFixSymbolSize(); } catch (Exception e) { //TODO: we can get here if an old style exists, and we have added new fields } } siteColor = new Color(siteColor.getRed(), siteColor.getGreen(), siteColor.getBlue(), transparency); fillColor = new Color(fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue(), transparency); try { monitor.subTask("connecting"); geoNeo = neoGeoResource.resolve(GeoNeo.class, new SubProgressMonitor(monitor, 10)); String selectedProp = geoNeo.getPropertyName(); Double redMinValue = geoNeo.getPropertyValueMin(); Double redMaxValue = geoNeo.getPropertyValueMax(); Double lesMinValue = geoNeo.getMinPropertyValue(); Double moreMaxValue = geoNeo.getMaxPropertyValue(); setCrsTransforms(neoGeoResource.getInfo(null).getCRS()); Envelope bounds_transformed = getTransformedBounds(); Envelope data_bounds = geoNeo.getBounds(); boolean drawFull = true; boolean drawLite = true; boolean drawLabels = true; if (bounds_transformed == null) { drawFull = false; drawLite = false; drawLabels = false; }else if (data_bounds != null && data_bounds.getHeight()>0 && data_bounds.getWidth()>0) { double dataScaled = (bounds_transformed.getHeight() * bounds_transformed.getWidth()) / (data_bounds.getHeight() * data_bounds.getWidth()); double countScaled = dataScaled * geoNeo.getCount(); drawLabels = countScaled < maxSitesLabel; drawFull = countScaled < maxSitesFull; drawLite = countScaled < maxSitesLite; if (drawFull && scaleSectors) { drawSize *= Math.sqrt(maxSitesFull) / (3 * Math.sqrt(countScaled)); } } g.setColor(drawColor); int count = 0; monitor.subTask("drawing"); Coordinate world_location = new Coordinate(); // single object for re-use in transform below (minimize object creation) for(GeoNode node:geoNeo.getGeoNodes()) { Coordinate location = node.getCoordinate(); if (bounds_transformed != null && !bounds_transformed.contains(location)) { continue; // Don't draw points outside viewport } try { JTS.transform(location, world_location, transform_d2w); } catch (Exception e) { //JTS.transform(location, world_location, transform_w2d.inverse()); } java.awt.Point p = getContext().worldToPixel(world_location); Color borderColor = g.getColor(); if (geoNeo.getSelectedNodes().contains(node.getNode())) { borderColor = COLOR_SITE_SELECTED; } renderSite(g, p, borderColor, siteColor, drawSize, drawFull, drawLite); if (drawFull) { int countOmnis = 0; double[] label_position_angles = new double[] {0, 90}; try { int s = 0; for (Relationship relationship : node.getNode().getRelationships(Direction.OUTGOING)) { // for(Relationship // relationship:node.getNode().getRelationships(NetworkLoader.NetworkRelationshipTypes.CHILD, // Direction.OUTGOING)){ Node child = relationship.getEndNode(); if (child.hasProperty("type") && child.getProperty("type").toString().equals("sector")) { double azimuth = -0.0; double beamwidth = 360.0; Color colorToFill = fillColor; for (String key : child.getPropertyKeys()) { if (key.toLowerCase().contains("azimuth")) { Object value = child.getProperty(key); if (value instanceof Integer) { azimuth = (Integer)value; } else { try { azimuth = Integer.parseInt(value.toString()); } catch (Exception e) { } } } if (key.toLowerCase().contains("beamwidth")) { beamwidth = (Integer)child.getProperty(key); } else if (key.toLowerCase().startsWith("beam")) { Object value = child.getProperty(key); if (value instanceof Integer) { beamwidth = (Integer)value; } else { try { beamwidth = Integer.parseInt(value.toString()); } catch (Exception e) { } } } if (selectedProp != null && selectedProp.equals(key)) { double value = ((Number)child.getProperty(key)).doubleValue(); if (value < redMaxValue || value == redMinValue) { if (value >= redMinValue) { colorToFill = COLOR_SELECTED; } else if (value >= lesMinValue) { colorToFill = COLOR_LESS; } } else if (value < moreMaxValue) { colorToFill = COLOR_MORE; } } } if(azimuth == -0.0) continue; borderColor = drawColor; if (geoNeo.getSelectedNodes().contains(child)) { borderColor = COLOR_SECTOR_SELECTED; } renderSector(g, p, azimuth, beamwidth, colorToFill, borderColor, drawSize); if (s < label_position_angles.length) { label_position_angles[s] = azimuth; } // g.setColor(drawColor); // g.rotate(-Math.toRadians(beamwidth/2)); // g.drawString(sector.getString("name"),drawSize,0); if(beamwidth==360) countOmnis++; s++; } } } finally { if (base_transform != null) { // recover the normal transform g.setTransform(base_transform); g.setColor(drawColor); } } if (countOmnis>1) { System.err.println("Site "+node+" had "+countOmnis+" omni antennas"); } if (drawLabels) { double label_position_angle = Math.toRadians(-90 + (label_position_angles[0] + label_position_angles[1]) / 2.0); int label_x = 5 + (int)(10 * Math.cos(label_position_angle)); int label_y = (int)(10 * Math.sin(label_position_angle)); g.setColor(labelColor); g.drawString(node.toString(), p.x + label_x, p.y + label_y); } g.setTransform(base_transform); } monitor.worked(1); count++; if (monitor.isCanceled()) break; } } catch (TransformException e) { throw new RenderException(e); } catch (FactoryException e) { throw new RenderException(e); } catch (IOException e) { throw new RenderException(e); // rethrow any exceptions encountered } finally { // if (geoNeo != null) // geoNeo.close(); monitor.done(); } }
diff --git a/src/com/android/settings/DeviceAdminAdd.java b/src/com/android/settings/DeviceAdminAdd.java index 126af6bdb..26ad70c8d 100644 --- a/src/com/android/settings/DeviceAdminAdd.java +++ b/src/com/android/settings/DeviceAdminAdd.java @@ -1,260 +1,270 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.app.AlertDialog; import android.app.DeviceAdminReceiver; import android.app.DeviceAdminInfo; import android.app.DevicePolicyManager; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.os.RemoteCallback; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AppSecurityPermissions; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; public class DeviceAdminAdd extends Activity { static final String TAG = "DeviceAdminAdd"; static final int DIALOG_WARNING = 1; Handler mHandler; DevicePolicyManager mDPM; DeviceAdminInfo mDeviceAdmin; CharSequence mAddMsgText; TextView mTitle; ImageView mAdminIcon; TextView mAdminName; TextView mAdminDescription; TextView mAddMsg; TextView mAdminWarning; ViewGroup mAdminPolicies; Button mActionButton; View mSelectLayout; final ArrayList<View> mAddingPolicies = new ArrayList<View>(); final ArrayList<View> mActivePolicies = new ArrayList<View>(); boolean mAdding; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); mHandler = new Handler(getMainLooper()); mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName cn = (ComponentName)getIntent().getParcelableExtra( DevicePolicyManager.EXTRA_DEVICE_ADMIN); if (cn == null) { Log.w(TAG, "No component specified in " + getIntent().getAction()); finish(); return; } if (DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN.equals(getIntent().getAction())) { // If this was an add request, then just exit immediately if the // given component is already added. if (mDPM.isAdminActive(cn)) { setResult(Activity.RESULT_OK); finish(); return; } } ActivityInfo ai; try { ai = getPackageManager().getReceiverInfo(cn, PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } ResolveInfo ri = new ResolveInfo(); ri.activityInfo = ai; try { mDeviceAdmin= new DeviceAdminInfo(this, ri); } catch (XmlPullParserException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } catch (IOException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } mAddMsgText = getIntent().getCharSequenceExtra( DevicePolicyManager.EXTRA_ADD_EXPLANATION); setContentView(R.layout.device_admin_add); mTitle = (TextView)findViewById(R.id.title); mAdminIcon = (ImageView)findViewById(R.id.admin_icon); mAdminName = (TextView)findViewById(R.id.admin_name); mAdminDescription = (TextView)findViewById(R.id.admin_description); mAddMsg = (TextView)findViewById(R.id.add_msg); mAdminWarning = (TextView)findViewById(R.id.admin_warning); mAdminPolicies = (ViewGroup)findViewById(R.id.admin_policies); mActionButton = (Button)findViewById(R.id.action_button); mActionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mAdding) { - mDPM.setActiveAdmin(mDeviceAdmin.getComponent()); - setResult(Activity.RESULT_OK); + try { + mDPM.setActiveAdmin(mDeviceAdmin.getComponent()); + setResult(Activity.RESULT_OK); + } catch (RuntimeException e) { + // Something bad happened... could be that it was + // already set, though. + Log.w(TAG, "Exception trying to activate admin " + + mDeviceAdmin.getComponent(), e); + if (mDPM.isAdminActive(mDeviceAdmin.getComponent())) { + setResult(Activity.RESULT_OK); + } + } finish(); } else { mDPM.getRemoveWarning(mDeviceAdmin.getComponent(), new RemoteCallback(mHandler) { @Override protected void onResult(Bundle bundle) { CharSequence msg = bundle != null ? bundle.getCharSequence( DeviceAdminReceiver.EXTRA_DISABLE_WARNING) : null; if (msg == null) { mDPM.removeActiveAdmin(mDeviceAdmin.getComponent()); finish(); } else { Bundle args = new Bundle(); args.putCharSequence( DeviceAdminReceiver.EXTRA_DISABLE_WARNING, msg); showDialog(DIALOG_WARNING, args); } } }); } } }); } @Override protected void onResume() { super.onResume(); updateInterface(); } @Override protected Dialog onCreateDialog(int id, Bundle args) { switch (id) { case DIALOG_WARNING: { CharSequence msg = args.getCharSequence(DeviceAdminReceiver.EXTRA_DISABLE_WARNING); AlertDialog.Builder builder = new AlertDialog.Builder( DeviceAdminAdd.this); builder.setMessage(msg); builder.setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mDPM.removeActiveAdmin(mDeviceAdmin.getComponent()); finish(); } }); builder.setNegativeButton(R.string.dlg_cancel, null); return builder.create(); } default: return super.onCreateDialog(id, args); } } static void setViewVisibility(ArrayList<View> views, int visibility) { final int N = views.size(); for (int i=0; i<N; i++) { views.get(i).setVisibility(visibility); } } void updateInterface() { mAdminIcon.setImageDrawable(mDeviceAdmin.loadIcon(getPackageManager())); mAdminName.setText(mDeviceAdmin.loadLabel(getPackageManager())); try { mAdminDescription.setText( mDeviceAdmin.loadDescription(getPackageManager())); mAdminDescription.setVisibility(View.VISIBLE); } catch (Resources.NotFoundException e) { mAdminDescription.setVisibility(View.GONE); } if (mAddMsgText != null) { mAddMsg.setText(mAddMsgText); mAddMsg.setVisibility(View.VISIBLE); } else { mAddMsg.setVisibility(View.GONE); } if (mDPM.isAdminActive(mDeviceAdmin.getComponent())) { if (mActivePolicies.size() == 0) { ArrayList<DeviceAdminInfo.PolicyInfo> policies = mDeviceAdmin.getUsedPolicies(); for (int i=0; i<policies.size(); i++) { DeviceAdminInfo.PolicyInfo pi = policies.get(i); View view = AppSecurityPermissions.getPermissionItemView( this, getText(pi.label), "", true); mActivePolicies.add(view); mAdminPolicies.addView(view); } } setViewVisibility(mActivePolicies, View.VISIBLE); setViewVisibility(mAddingPolicies, View.GONE); mAdminWarning.setText(getString(R.string.device_admin_status, mDeviceAdmin.getActivityInfo().applicationInfo.loadLabel(getPackageManager()))); mTitle.setText(getText(R.string.active_device_admin_msg)); mActionButton.setText(getText(R.string.remove_device_admin)); mAdding = false; } else { if (mAddingPolicies.size() == 0) { ArrayList<DeviceAdminInfo.PolicyInfo> policies = mDeviceAdmin.getUsedPolicies(); for (int i=0; i<policies.size(); i++) { DeviceAdminInfo.PolicyInfo pi = policies.get(i); View view = AppSecurityPermissions.getPermissionItemView( this, getText(pi.label), getText(pi.description), true); mAddingPolicies.add(view); mAdminPolicies.addView(view); } } setViewVisibility(mAddingPolicies, View.VISIBLE); setViewVisibility(mActivePolicies, View.GONE); mAdminWarning.setText(getString(R.string.device_admin_warning, mDeviceAdmin.getActivityInfo().applicationInfo.loadLabel(getPackageManager()))); mTitle.setText(getText(R.string.add_device_admin_msg)); mActionButton.setText(getText(R.string.add_device_admin)); mAdding = true; } } }
true
true
protected void onCreate(Bundle icicle) { super.onCreate(icicle); mHandler = new Handler(getMainLooper()); mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName cn = (ComponentName)getIntent().getParcelableExtra( DevicePolicyManager.EXTRA_DEVICE_ADMIN); if (cn == null) { Log.w(TAG, "No component specified in " + getIntent().getAction()); finish(); return; } if (DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN.equals(getIntent().getAction())) { // If this was an add request, then just exit immediately if the // given component is already added. if (mDPM.isAdminActive(cn)) { setResult(Activity.RESULT_OK); finish(); return; } } ActivityInfo ai; try { ai = getPackageManager().getReceiverInfo(cn, PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } ResolveInfo ri = new ResolveInfo(); ri.activityInfo = ai; try { mDeviceAdmin= new DeviceAdminInfo(this, ri); } catch (XmlPullParserException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } catch (IOException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } mAddMsgText = getIntent().getCharSequenceExtra( DevicePolicyManager.EXTRA_ADD_EXPLANATION); setContentView(R.layout.device_admin_add); mTitle = (TextView)findViewById(R.id.title); mAdminIcon = (ImageView)findViewById(R.id.admin_icon); mAdminName = (TextView)findViewById(R.id.admin_name); mAdminDescription = (TextView)findViewById(R.id.admin_description); mAddMsg = (TextView)findViewById(R.id.add_msg); mAdminWarning = (TextView)findViewById(R.id.admin_warning); mAdminPolicies = (ViewGroup)findViewById(R.id.admin_policies); mActionButton = (Button)findViewById(R.id.action_button); mActionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mAdding) { mDPM.setActiveAdmin(mDeviceAdmin.getComponent()); setResult(Activity.RESULT_OK); finish(); } else { mDPM.getRemoveWarning(mDeviceAdmin.getComponent(), new RemoteCallback(mHandler) { @Override protected void onResult(Bundle bundle) { CharSequence msg = bundle != null ? bundle.getCharSequence( DeviceAdminReceiver.EXTRA_DISABLE_WARNING) : null; if (msg == null) { mDPM.removeActiveAdmin(mDeviceAdmin.getComponent()); finish(); } else { Bundle args = new Bundle(); args.putCharSequence( DeviceAdminReceiver.EXTRA_DISABLE_WARNING, msg); showDialog(DIALOG_WARNING, args); } } }); } } }); }
protected void onCreate(Bundle icicle) { super.onCreate(icicle); mHandler = new Handler(getMainLooper()); mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName cn = (ComponentName)getIntent().getParcelableExtra( DevicePolicyManager.EXTRA_DEVICE_ADMIN); if (cn == null) { Log.w(TAG, "No component specified in " + getIntent().getAction()); finish(); return; } if (DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN.equals(getIntent().getAction())) { // If this was an add request, then just exit immediately if the // given component is already added. if (mDPM.isAdminActive(cn)) { setResult(Activity.RESULT_OK); finish(); return; } } ActivityInfo ai; try { ai = getPackageManager().getReceiverInfo(cn, PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } ResolveInfo ri = new ResolveInfo(); ri.activityInfo = ai; try { mDeviceAdmin= new DeviceAdminInfo(this, ri); } catch (XmlPullParserException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } catch (IOException e) { Log.w(TAG, "Unable to retrieve device policy " + cn, e); finish(); return; } mAddMsgText = getIntent().getCharSequenceExtra( DevicePolicyManager.EXTRA_ADD_EXPLANATION); setContentView(R.layout.device_admin_add); mTitle = (TextView)findViewById(R.id.title); mAdminIcon = (ImageView)findViewById(R.id.admin_icon); mAdminName = (TextView)findViewById(R.id.admin_name); mAdminDescription = (TextView)findViewById(R.id.admin_description); mAddMsg = (TextView)findViewById(R.id.add_msg); mAdminWarning = (TextView)findViewById(R.id.admin_warning); mAdminPolicies = (ViewGroup)findViewById(R.id.admin_policies); mActionButton = (Button)findViewById(R.id.action_button); mActionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (mAdding) { try { mDPM.setActiveAdmin(mDeviceAdmin.getComponent()); setResult(Activity.RESULT_OK); } catch (RuntimeException e) { // Something bad happened... could be that it was // already set, though. Log.w(TAG, "Exception trying to activate admin " + mDeviceAdmin.getComponent(), e); if (mDPM.isAdminActive(mDeviceAdmin.getComponent())) { setResult(Activity.RESULT_OK); } } finish(); } else { mDPM.getRemoveWarning(mDeviceAdmin.getComponent(), new RemoteCallback(mHandler) { @Override protected void onResult(Bundle bundle) { CharSequence msg = bundle != null ? bundle.getCharSequence( DeviceAdminReceiver.EXTRA_DISABLE_WARNING) : null; if (msg == null) { mDPM.removeActiveAdmin(mDeviceAdmin.getComponent()); finish(); } else { Bundle args = new Bundle(); args.putCharSequence( DeviceAdminReceiver.EXTRA_DISABLE_WARNING, msg); showDialog(DIALOG_WARNING, args); } } }); } } }); }
diff --git a/src/Classes/TestMigratableProcess.java b/src/Classes/TestMigratableProcess.java index 7321189..e8a9dec 100644 --- a/src/Classes/TestMigratableProcess.java +++ b/src/Classes/TestMigratableProcess.java @@ -1,80 +1,80 @@ package Classes; import java.io.*; public class TestMigratableProcess implements MigratableProcess{ /** * */ private static final long serialVersionUID = 1241500530790605595L; private String inputFile; private String outputFile = "out.txt"; private volatile boolean suspending = false; private boolean finished = false; /* transactionalIO */ private TransactionalFileInputStream inStream; private TransactionalFileOutputStream outStream; private int i = 0; public TestMigratableProcess() { } public TestMigratableProcess(String[] args) { this.inputFile = args[0]; this.outputFile = args[1]; inStream = new TransactionalFileInputStream(inputFile); outStream = new TransactionalFileOutputStream(outputFile); } public String toString() { return ""; } public void run() { suspending = false; DataOutputStream out = null; out = new DataOutputStream(outStream); while(!suspending && !finished) { if (i > 100) { finished = true; break; } try { out.writeBytes("" + ++i + "\n"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(++i); try { Thread.sleep(600); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } + outStream.setMigrated(true); suspending = false; - inStream.setMigrated(true); } public void suspend() { suspending = true; while (suspending && !finished); } public boolean getFinished() { return this.finished; } }
false
true
public void run() { suspending = false; DataOutputStream out = null; out = new DataOutputStream(outStream); while(!suspending && !finished) { if (i > 100) { finished = true; break; } try { out.writeBytes("" + ++i + "\n"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(++i); try { Thread.sleep(600); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } suspending = false; inStream.setMigrated(true); }
public void run() { suspending = false; DataOutputStream out = null; out = new DataOutputStream(outStream); while(!suspending && !finished) { if (i > 100) { finished = true; break; } try { out.writeBytes("" + ++i + "\n"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println(++i); try { Thread.sleep(600); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } outStream.setMigrated(true); suspending = false; }
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java index ad896552c..405d8109e 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/Mpg123Test.java @@ -1,87 +1,87 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.AudioDevice; import com.badlogic.gdx.audio.io.Mpg123Decoder; import com.badlogic.gdx.audio.io.VorbisDecoder; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.tests.utils.GdxTest; /** * Demonstrates how to read and playback an OGG file with the {@link VorbisDecoder} found * in the gdx-audio extension. * @author mzechner * */ public class Mpg123Test extends GdxTest { /** the file to playback **/ private static final String FILE = "data/8.12.mp3"; /** a VorbisDecoder to read PCM data from the ogg file **/ Mpg123Decoder decoder; /** an AudioDevice for playing back the PCM data **/ AudioDevice device; @Override public void create () { // copy ogg file to SD card, can't playback from assets FileHandle externalFile = Gdx.files.external("tmp/test.mp3"); Gdx.files.internal(FILE).copyTo(externalFile); // Create the decoder and log some properties. Note that we need // an external or absolute file decoder = new Mpg123Decoder(externalFile); - Gdx.app.log("Vorbis", "channels: " + decoder.getChannels() + ", rate: " + decoder.getRate() + ", length: " + decoder.getLength()); + Gdx.app.log("Mp3", "channels: " + decoder.getChannels() + ", rate: " + decoder.getRate() + ", length: " + decoder.getLength()); // Create an audio device for playback device = Gdx.audio.newAudioDevice(decoder.getRate(), decoder.getChannels() == 1? true: false); // start a thread for playback Thread playbackThread = new Thread(new Runnable() { @Override public void run() { int readSamples = 0; // we need a short[] to pass the data to the AudioDevice short[] samples = new short[2048]; // read until we reach the end of the file while((readSamples = decoder.readSamples(samples, 0, samples.length)) > 0) { // write the samples to the AudioDevice device.writeSamples(samples, 0, readSamples); } } }); playbackThread.setDaemon(true); playbackThread.start(); } @Override public void dispose() { // we should synchronize with the thread here // left as an excercise to the reader :) device.dispose(); decoder.dispose(); // kill the file again Gdx.files.external("tmp/test.mp3").delete(); } @Override public boolean needsGL20 () { return false; } }
true
true
public void create () { // copy ogg file to SD card, can't playback from assets FileHandle externalFile = Gdx.files.external("tmp/test.mp3"); Gdx.files.internal(FILE).copyTo(externalFile); // Create the decoder and log some properties. Note that we need // an external or absolute file decoder = new Mpg123Decoder(externalFile); Gdx.app.log("Vorbis", "channels: " + decoder.getChannels() + ", rate: " + decoder.getRate() + ", length: " + decoder.getLength()); // Create an audio device for playback device = Gdx.audio.newAudioDevice(decoder.getRate(), decoder.getChannels() == 1? true: false); // start a thread for playback Thread playbackThread = new Thread(new Runnable() { @Override public void run() { int readSamples = 0; // we need a short[] to pass the data to the AudioDevice short[] samples = new short[2048]; // read until we reach the end of the file while((readSamples = decoder.readSamples(samples, 0, samples.length)) > 0) { // write the samples to the AudioDevice device.writeSamples(samples, 0, readSamples); } } }); playbackThread.setDaemon(true); playbackThread.start(); }
public void create () { // copy ogg file to SD card, can't playback from assets FileHandle externalFile = Gdx.files.external("tmp/test.mp3"); Gdx.files.internal(FILE).copyTo(externalFile); // Create the decoder and log some properties. Note that we need // an external or absolute file decoder = new Mpg123Decoder(externalFile); Gdx.app.log("Mp3", "channels: " + decoder.getChannels() + ", rate: " + decoder.getRate() + ", length: " + decoder.getLength()); // Create an audio device for playback device = Gdx.audio.newAudioDevice(decoder.getRate(), decoder.getChannels() == 1? true: false); // start a thread for playback Thread playbackThread = new Thread(new Runnable() { @Override public void run() { int readSamples = 0; // we need a short[] to pass the data to the AudioDevice short[] samples = new short[2048]; // read until we reach the end of the file while((readSamples = decoder.readSamples(samples, 0, samples.length)) > 0) { // write the samples to the AudioDevice device.writeSamples(samples, 0, readSamples); } } }); playbackThread.setDaemon(true); playbackThread.start(); }
diff --git a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildDefinitionAction.java b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildDefinitionAction.java index c2e368f6e..d8935ab1d 100644 --- a/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildDefinitionAction.java +++ b/continuum-webapp/src/main/java/org/apache/maven/continuum/web/action/BuildDefinitionAction.java @@ -1,395 +1,395 @@ package org.apache.maven.continuum.web.action; /* * Copyright 2005-2006 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. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.web.exception.ContinuumActionException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.List; /** * BuildDefinitionAction: * * @author Jesse McConnell <[email protected]> * @version $Id$ * @plexus.component role="com.opensymphony.xwork.Action" * role-hint="buildDefinition" */ public class BuildDefinitionAction extends ContinuumConfirmAction { private int buildDefinitionId; private int projectId; private int projectGroupId; private int scheduleId; private boolean defaultBuildDefinition; private boolean confirmed = false; private String executor; private String goals; private String arguments; private String buildFile; private boolean buildFresh; private Map schedules; private Map profiles; public void prepare() throws Exception { super.prepare(); if ( schedules == null ) { schedules = new HashMap(); Collection allSchedules = getContinuum().getSchedules(); for ( Iterator i = allSchedules.iterator(); i.hasNext(); ) { Schedule schedule = (Schedule) i.next(); schedules.put( new Integer( schedule.getId() ), schedule.getName() ); } } // todo: missing from continuum, investigate if ( profiles == null ) { profiles = new HashMap(); } } /** * if there is a build definition id set, then retrieve it..either way set us to up to work with build definition * * @return action result */ public String input() throws ContinuumException { if ( executor == null ) { if ( projectId != 0 ) { executor = getContinuum().getProject( projectId ).getExecutorId(); } else { List projects = getContinuum().getProjectGroup( projectGroupId ).getProjects(); if( projects.size() > 0 ) { Project project = (Project) projects.get( 0 ); executor = project.getExecutorId(); } } } if ( buildDefinitionId != 0 ) { BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); goals = buildDefinition.getGoals(); arguments = buildDefinition.getArguments(); buildFile = buildDefinition.getBuildFile(); buildFresh = buildDefinition.isBuildFresh(); scheduleId = buildDefinition.getSchedule().getId(); defaultBuildDefinition = buildDefinition.isDefaultForProject(); } - return INPUT; + return SUCCESS; } public String saveBuildDefinition() throws ContinuumException { if (projectId != 0) { return saveToProject(); } else { return saveToGroup(); } } public String saveToProject() throws ContinuumException { try { if ( buildDefinitionId == 0 ) { getContinuum().addBuildDefinitionToProject( projectId, getBuildDefinitionFromInput() ); } else { getContinuum().updateBuildDefinitionForProject( projectId, getBuildDefinitionFromInput() ); } } catch ( ContinuumActionException cae ) { addActionError( cae.getMessage() ); return INPUT; } return SUCCESS; } public String saveToGroup() throws ContinuumException { try { BuildDefinition newBuildDef = getBuildDefinitionFromInput(); if ( getContinuum().getBuildDefinitionsForProjectGroup( projectGroupId ).size() == 0 ) { newBuildDef.setDefaultForProject( true ); } if ( buildDefinitionId == 0 ) { getContinuum().addBuildDefinitionToProjectGroup( projectGroupId, newBuildDef ); } else { getContinuum().updateBuildDefinitionForProjectGroup( projectGroupId, newBuildDef ); } } catch ( ContinuumActionException cae ) { addActionError( cae.getMessage() ); return INPUT; } return "success_group"; } public String removeFromProject() throws ContinuumException { if ( confirmed ) { getContinuum().removeBuildDefinitionFromProject( projectId, buildDefinitionId ); return SUCCESS; } else { return CONFIRM; } } public String removeFromProjectGroup() throws ContinuumException { if ( confirmed ) { getContinuum().removeBuildDefinitionFromProjectGroup( projectGroupId, buildDefinitionId ); return SUCCESS; } else { return CONFIRM; } } private BuildDefinition getBuildDefinitionFromInput() throws ContinuumActionException { Schedule schedule; try { schedule = getContinuum().getSchedule( scheduleId ); } catch ( ContinuumException e ) { addActionError( "unable to get schedule" ); throw new ContinuumActionException( "unable to get schedule" ); } BuildDefinition buildDefinition = new BuildDefinition(); if ( buildDefinitionId != 0 ) { buildDefinition.setId( buildDefinitionId ); } buildDefinition.setGoals( goals ); buildDefinition.setArguments( arguments ); buildDefinition.setBuildFile( buildFile ); buildDefinition.setBuildFresh( buildFresh ); buildDefinition.setDefaultForProject( defaultBuildDefinition ); buildDefinition.setSchedule( schedule ); return buildDefinition; } public int getBuildDefinitionId() { return buildDefinitionId; } public void setBuildDefinitionId( int buildDefinitionId ) { this.buildDefinitionId = buildDefinitionId; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public int getScheduleId() { return scheduleId; } public void setScheduleId( int scheduleId ) { this.scheduleId = scheduleId; } public boolean isDefaultBuildDefinition() { return defaultBuildDefinition; } public void setDefaultBuildDefinition( boolean defaultBuildDefinition ) { this.defaultBuildDefinition = defaultBuildDefinition; } public boolean isConfirmed() { return confirmed; } public void setConfirmed( boolean confirmed ) { this.confirmed = confirmed; } public String getExecutor() { return executor; } public void setExecutor( String executor ) { this.executor = executor; } public String getGoals() { return goals; } public void setGoals( String goals ) { this.goals = goals; } public String getArguments() { return arguments; } public void setArguments( String arguments ) { this.arguments = arguments; } public String getBuildFile() { return buildFile; } public void setBuildFile( String buildFile ) { this.buildFile = buildFile; } public boolean isBuildFresh() { return buildFresh; } public void setBuildFresh( boolean buildFresh ) { this.buildFresh = buildFresh; } public Map getSchedules() { return schedules; } public void setSchedules( Map schedules ) { this.schedules = schedules; } public Map getProfiles() { return profiles; } public void setProfiles( Map profiles ) { this.profiles = profiles; } }
true
true
public String input() throws ContinuumException { if ( executor == null ) { if ( projectId != 0 ) { executor = getContinuum().getProject( projectId ).getExecutorId(); } else { List projects = getContinuum().getProjectGroup( projectGroupId ).getProjects(); if( projects.size() > 0 ) { Project project = (Project) projects.get( 0 ); executor = project.getExecutorId(); } } } if ( buildDefinitionId != 0 ) { BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); goals = buildDefinition.getGoals(); arguments = buildDefinition.getArguments(); buildFile = buildDefinition.getBuildFile(); buildFresh = buildDefinition.isBuildFresh(); scheduleId = buildDefinition.getSchedule().getId(); defaultBuildDefinition = buildDefinition.isDefaultForProject(); } return INPUT; }
public String input() throws ContinuumException { if ( executor == null ) { if ( projectId != 0 ) { executor = getContinuum().getProject( projectId ).getExecutorId(); } else { List projects = getContinuum().getProjectGroup( projectGroupId ).getProjects(); if( projects.size() > 0 ) { Project project = (Project) projects.get( 0 ); executor = project.getExecutorId(); } } } if ( buildDefinitionId != 0 ) { BuildDefinition buildDefinition = getContinuum().getBuildDefinition( buildDefinitionId ); goals = buildDefinition.getGoals(); arguments = buildDefinition.getArguments(); buildFile = buildDefinition.getBuildFile(); buildFresh = buildDefinition.isBuildFresh(); scheduleId = buildDefinition.getSchedule().getId(); defaultBuildDefinition = buildDefinition.isDefaultForProject(); } return SUCCESS; }
diff --git a/atlassian-plugins-webresource/src/main/java/com/atlassian/plugin/webresource/DefaultResourceBatchingConfiguration.java b/atlassian-plugins-webresource/src/main/java/com/atlassian/plugin/webresource/DefaultResourceBatchingConfiguration.java index 73308db4..ab2fa6a7 100644 --- a/atlassian-plugins-webresource/src/main/java/com/atlassian/plugin/webresource/DefaultResourceBatchingConfiguration.java +++ b/atlassian-plugins-webresource/src/main/java/com/atlassian/plugin/webresource/DefaultResourceBatchingConfiguration.java @@ -1,43 +1,43 @@ package com.atlassian.plugin.webresource; import com.atlassian.plugin.util.PluginUtils; import java.util.List; import java.util.Collections; /** * Default configuration for the plugin resource locator, for those applications that do not want to perform * any super-batching. */ public class DefaultResourceBatchingConfiguration implements ResourceBatchingConfiguration { public static final String PLUGIN_WEBRESOURCE_BATCHING_OFF = "plugin.webresource.batching.off"; public boolean isSuperBatchingEnabled() { return false; } public List<String> getSuperBatchModuleCompleteKeys() { return Collections.emptyList(); } public boolean isContextBatchingEnabled() { return false; } public boolean isPluginWebResourceBatchingEnabled() { final String explicitSetting = System.getProperty(PLUGIN_WEBRESOURCE_BATCHING_OFF); if (explicitSetting != null) { - return Boolean.parseBoolean(explicitSetting); + return !Boolean.parseBoolean(explicitSetting); } else { - return Boolean.parseBoolean(System.getProperty(PluginUtils.ATLASSIAN_DEV_MODE)); + return !Boolean.parseBoolean(System.getProperty(PluginUtils.ATLASSIAN_DEV_MODE)); } } }
false
true
public boolean isPluginWebResourceBatchingEnabled() { final String explicitSetting = System.getProperty(PLUGIN_WEBRESOURCE_BATCHING_OFF); if (explicitSetting != null) { return Boolean.parseBoolean(explicitSetting); } else { return Boolean.parseBoolean(System.getProperty(PluginUtils.ATLASSIAN_DEV_MODE)); } }
public boolean isPluginWebResourceBatchingEnabled() { final String explicitSetting = System.getProperty(PLUGIN_WEBRESOURCE_BATCHING_OFF); if (explicitSetting != null) { return !Boolean.parseBoolean(explicitSetting); } else { return !Boolean.parseBoolean(System.getProperty(PluginUtils.ATLASSIAN_DEV_MODE)); } }
diff --git a/main/src/com/google/refine/expr/HasFieldsListImpl.java b/main/src/com/google/refine/expr/HasFieldsListImpl.java index d7ee4a28..c09f0411 100644 --- a/main/src/com/google/refine/expr/HasFieldsListImpl.java +++ b/main/src/com/google/refine/expr/HasFieldsListImpl.java @@ -1,74 +1,76 @@ /* Copyright 2010, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.google.refine.expr; import java.util.ArrayList; import java.util.Properties; public class HasFieldsListImpl extends ArrayList<HasFields> implements HasFieldsList { private static final long serialVersionUID = -8635194387420305802L; public Object getField(String name, Properties bindings) { int c = size(); - if (c > 0 && get(0).fieldAlsoHasFields(name)) { + if (c > 0 && get(0) != null && get(0).fieldAlsoHasFields(name)) { HasFieldsListImpl l = new HasFieldsListImpl(); for (int i = 0; i < size(); i++) { - l.add(i, (HasFields) this.get(i).getField(name, bindings)); + HasFields o = this.get(i); + l.add(i, o == null ? null : (HasFields) o.getField(name, bindings)); } return l; } else { Object[] r = new Object[this.size()]; for (int i = 0; i < r.length; i++) { - r[i] = this.get(i).getField(name, bindings); + HasFields o = this.get(i); + r[i] = o == null ? null : o.getField(name, bindings); } return r; } } public int length() { return size(); } public boolean fieldAlsoHasFields(String name) { int c = size(); return (c > 0 && get(0).fieldAlsoHasFields(name)); } public HasFieldsList getSubList(int fromIndex, int toIndex) { HasFieldsListImpl subList = new HasFieldsListImpl(); subList.addAll(this.subList(fromIndex, toIndex)); return subList; } }
false
true
public Object getField(String name, Properties bindings) { int c = size(); if (c > 0 && get(0).fieldAlsoHasFields(name)) { HasFieldsListImpl l = new HasFieldsListImpl(); for (int i = 0; i < size(); i++) { l.add(i, (HasFields) this.get(i).getField(name, bindings)); } return l; } else { Object[] r = new Object[this.size()]; for (int i = 0; i < r.length; i++) { r[i] = this.get(i).getField(name, bindings); } return r; } }
public Object getField(String name, Properties bindings) { int c = size(); if (c > 0 && get(0) != null && get(0).fieldAlsoHasFields(name)) { HasFieldsListImpl l = new HasFieldsListImpl(); for (int i = 0; i < size(); i++) { HasFields o = this.get(i); l.add(i, o == null ? null : (HasFields) o.getField(name, bindings)); } return l; } else { Object[] r = new Object[this.size()]; for (int i = 0; i < r.length; i++) { HasFields o = this.get(i); r[i] = o == null ? null : o.getField(name, bindings); } return r; } }
diff --git a/src/main/java/de/kumpelblase2/remoteentities/EntityManager.java b/src/main/java/de/kumpelblase2/remoteentities/EntityManager.java index 4d28986..9e3d9d5 100644 --- a/src/main/java/de/kumpelblase2/remoteentities/EntityManager.java +++ b/src/main/java/de/kumpelblase2/remoteentities/EntityManager.java @@ -1,180 +1,180 @@ package de.kumpelblase2.remoteentities; import java.lang.reflect.Constructor; import java.util.*; import java.util.Map.Entry; import net.minecraft.server.EntityLiving; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.craftbukkit.entity.CraftLivingEntity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.plugin.Plugin; import de.kumpelblase2.remoteentities.api.*; import de.kumpelblase2.remoteentities.exceptions.NoNameException; public class EntityManager { private Map<Integer, RemoteEntity> m_entities; private final Plugin m_plugin; - public EntityManager(final Plugin inPlugin) + EntityManager(final Plugin inPlugin) { this.m_plugin = inPlugin; this.m_entities = new HashMap<Integer, RemoteEntity>(); Bukkit.getScheduler().scheduleSyncRepeatingTask(inPlugin, new Runnable() { @Override public void run() { Iterator<Entry<Integer, RemoteEntity>> it = m_entities.entrySet().iterator(); while(it.hasNext()) { Entry<Integer, RemoteEntity> entry = it.next(); entry.getValue().getHandle().y(); if(entry.getValue().getHandle().dead) { entry.getValue().despawn(); it.remove(); } } } }, 1L, 1L); } public Plugin getPlugin() { return this.m_plugin; } private Integer getNextFreeID() { Set<Integer> ids = this.m_entities.keySet(); Integer current = 0; while(ids.contains(current)) { current++; } return current; } public RemoteEntity createEntity(RemoteEntityType inType, Location inLocation) throws NoNameException { return this.createEntity(inType, inLocation, true); } public RemoteEntity createEntity(RemoteEntityType inType, Location inLocation, boolean inSetupGoals) throws NoNameException { if(inType.isNamed()) throw new NoNameException("Tried to spawn a named entity without name"); Integer id = this.getNextFreeID(); try { Constructor<? extends RemoteEntity> constructor = inType.getRemoteClass().getConstructor(int.class, EntityManager.class); RemoteEntity entity = constructor.newInstance(id, this); entity.spawn(inLocation); if(inSetupGoals) ((RemoteEntityHandle)entity.getHandle()).setupStandardGoals(); this.m_entities.put(id, entity); return entity; } catch(Exception e) { e.printStackTrace(); } return null; } public RemoteEntity createNamedEntity(RemoteEntityType inType, Location inLocation, String inName) { return this.createNamedEntity(inType, inLocation, inName, true); } public RemoteEntity createNamedEntity(RemoteEntityType inType, Location inLocation, String inName, boolean inSetupGoals) { Integer id = this.getNextFreeID(); try { Constructor<? extends RemoteEntity> constructor = inType.getRemoteClass().getConstructor(int.class, String.class, EntityManager.class); RemoteEntity entity = constructor.newInstance(id, inName, this); entity.spawn(inLocation); if(inSetupGoals) ((RemoteEntityHandle)entity.getHandle()).setupStandardGoals(); this.m_entities.put(id, entity); return entity; } catch(Exception e) { e.printStackTrace(); } return null; } public void removeEntity(int inID) { if(this.m_entities.containsKey((Integer)inID)) this.m_entities.get((Integer)inID).despawn(); this.m_entities.remove((Integer)inID); } public boolean isRemoteEntity(LivingEntity inEntity) { EntityLiving handle = ((CraftLivingEntity)inEntity).getHandle(); return handle instanceof RemoteEntityHandle; } public RemoteEntity getRemoteEntityFromEntity(LivingEntity inEntity) { if(!this.isRemoteEntity(inEntity)) return null; EntityLiving entityHandle = ((CraftLivingEntity)inEntity).getHandle(); return ((RemoteEntityHandle)entityHandle).getRemoteEntity(); } public RemoteEntity getRemoteEntityByID(int inID) { return this.m_entities.get((Integer)inID); } public void addRemoteEntity(int inID, RemoteEntity inEntity) { this.m_entities.put(inID, inEntity); } public RemoteEntity createRemoteEntityFromExisting(LivingEntity inEntity) //TODO copy more shit from entity { RemoteEntityType type = RemoteEntityType.getByEntityClass(((CraftLivingEntity)inEntity).getHandle().getClass()); Location originalSpot = inEntity.getLocation(); String name = (inEntity instanceof HumanEntity) ? ((HumanEntity)inEntity).getName() : null; inEntity.remove(); try { if(name == null) return this.createEntity(type, originalSpot); else return this.createNamedEntity(type, originalSpot, name); } catch(Exception e) { e.printStackTrace(); return null; } } public void despawnAll() { for(RemoteEntity entity : this.m_entities.values()) { entity.despawn(); } this.m_entities.clear(); } public List<RemoteEntity> getAllEntities() { return new ArrayList<RemoteEntity>(this.m_entities.values()); } }
true
true
public EntityManager(final Plugin inPlugin) { this.m_plugin = inPlugin; this.m_entities = new HashMap<Integer, RemoteEntity>(); Bukkit.getScheduler().scheduleSyncRepeatingTask(inPlugin, new Runnable() { @Override public void run() { Iterator<Entry<Integer, RemoteEntity>> it = m_entities.entrySet().iterator(); while(it.hasNext()) { Entry<Integer, RemoteEntity> entry = it.next(); entry.getValue().getHandle().y(); if(entry.getValue().getHandle().dead) { entry.getValue().despawn(); it.remove(); } } } }, 1L, 1L); }
EntityManager(final Plugin inPlugin) { this.m_plugin = inPlugin; this.m_entities = new HashMap<Integer, RemoteEntity>(); Bukkit.getScheduler().scheduleSyncRepeatingTask(inPlugin, new Runnable() { @Override public void run() { Iterator<Entry<Integer, RemoteEntity>> it = m_entities.entrySet().iterator(); while(it.hasNext()) { Entry<Integer, RemoteEntity> entry = it.next(); entry.getValue().getHandle().y(); if(entry.getValue().getHandle().dead) { entry.getValue().despawn(); it.remove(); } } } }, 1L, 1L); }
diff --git a/modules/cpr/src/main/java/org/atmosphere/websocket/protocol/SimpleHttpProtocol.java b/modules/cpr/src/main/java/org/atmosphere/websocket/protocol/SimpleHttpProtocol.java index 514842353..dad103a3c 100644 --- a/modules/cpr/src/main/java/org/atmosphere/websocket/protocol/SimpleHttpProtocol.java +++ b/modules/cpr/src/main/java/org/atmosphere/websocket/protocol/SimpleHttpProtocol.java @@ -1,159 +1,162 @@ /* * Copyright 2012 Jeanfrancois Arcand * * 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.atmosphere.websocket.protocol; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.cpr.AtmosphereConfig; import org.atmosphere.cpr.AtmosphereRequest; import org.atmosphere.cpr.AtmosphereResourceImpl; import org.atmosphere.cpr.FrameworkConfig; import org.atmosphere.websocket.WebSocket; import org.atmosphere.websocket.WebSocketProcessor; import org.atmosphere.websocket.WebSocketProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Like the {@link org.atmosphere.cpr.AsynchronousProcessor} class, this class is responsible for dispatching WebSocket messages to the * proper {@link org.atmosphere.websocket.WebSocket} implementation by wrapping the Websocket message's bytes within * an {@link javax.servlet.http.HttpServletRequest}. * <p/> * The content-type is defined using {@link org.atmosphere.cpr.ApplicationConfig#WEBSOCKET_CONTENT_TYPE} property * The method is defined using {@link org.atmosphere.cpr.ApplicationConfig#WEBSOCKET_METHOD} property * <p/> * * @author Jeanfrancois Arcand */ public class SimpleHttpProtocol implements WebSocketProtocol, Serializable { private static final Logger logger = LoggerFactory.getLogger(SimpleHttpProtocol.class); private String contentType = "text/plain"; private String methodType = "POST"; private String delimiter = "@@"; private boolean destroyable; /** * {@inheritDoc} */ @Override public void configure(AtmosphereConfig config) { String contentType = config.getInitParameter(ApplicationConfig.WEBSOCKET_CONTENT_TYPE); if (contentType == null) { contentType = "text/plain"; } this.contentType = contentType; String methodType = config.getInitParameter(ApplicationConfig.WEBSOCKET_METHOD); if (methodType == null) { methodType = "POST"; } this.methodType = methodType; String delimiter = config.getInitParameter(ApplicationConfig.WEBSOCKET_PATH_DELIMITER); if (delimiter == null) { delimiter = "@@"; } this.delimiter = delimiter; String s = config.getInitParameter(ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE); if (s != null && Boolean.valueOf(s)) { destroyable = true; } else { destroyable = false; } } /** * {@inheritDoc} */ @Override public List<AtmosphereRequest> onMessage(WebSocket webSocket, String d) { AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource(); if (resource == null) { logger.trace("The WebSocket has been closed before the message was processed."); return null; } String pathInfo = resource.getRequest().getPathInfo(); + String requestURI = resource.getRequest().getRequestURI(); if (d.startsWith(delimiter)) { int delimiterLength = delimiter.length(); int bodyBeginIndex = d.indexOf(delimiter, delimiterLength); if (bodyBeginIndex != -1) { pathInfo = d.substring(delimiterLength, bodyBeginIndex); + requestURI += pathInfo; d = d.substring(bodyBeginIndex + delimiterLength); } } Map<String,Object> m = new HashMap<String, Object>(); m.put(FrameworkConfig.WEBSOCKET_SUBPROTOCOL, FrameworkConfig.SIMPLE_HTTP_OVER_WEBSOCKET); // Propagate the original attribute to WebSocket message. m.putAll(resource.getRequest().attributes()); List<AtmosphereRequest> list = new ArrayList<AtmosphereRequest>(); // We need to create a new AtmosphereRequest as WebSocket message may arrive concurrently on the same connection. list.add(new AtmosphereRequest.Builder() .request(resource.getRequest()) .method(methodType) .contentType(contentType) .body(d) .attributes(m) .pathInfo(pathInfo) + .requestURI(requestURI) .destroyable(destroyable) .headers(resource.getRequest().headersMap()) .session(resource.session()) .build()); return list; } /** * {@inheritDoc} */ @Override public List<AtmosphereRequest> onMessage(WebSocket webSocket, byte[] d, final int offset, final int length) { return onMessage(webSocket, new String(d, offset, length)); } /** * {@inheritDoc} */ @Override public void onOpen(WebSocket webSocket) { } /** * {@inheritDoc} */ @Override public void onClose(WebSocket webSocket) { } /** * {@inheritDoc} */ @Override public void onError(WebSocket webSocket, WebSocketProcessor.WebSocketException t) { logger.warn(t.getMessage() + " Status {} Message {}", t.response().getStatus(), t.response().getStatusMessage()); } }
false
true
public List<AtmosphereRequest> onMessage(WebSocket webSocket, String d) { AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource(); if (resource == null) { logger.trace("The WebSocket has been closed before the message was processed."); return null; } String pathInfo = resource.getRequest().getPathInfo(); if (d.startsWith(delimiter)) { int delimiterLength = delimiter.length(); int bodyBeginIndex = d.indexOf(delimiter, delimiterLength); if (bodyBeginIndex != -1) { pathInfo = d.substring(delimiterLength, bodyBeginIndex); d = d.substring(bodyBeginIndex + delimiterLength); } } Map<String,Object> m = new HashMap<String, Object>(); m.put(FrameworkConfig.WEBSOCKET_SUBPROTOCOL, FrameworkConfig.SIMPLE_HTTP_OVER_WEBSOCKET); // Propagate the original attribute to WebSocket message. m.putAll(resource.getRequest().attributes()); List<AtmosphereRequest> list = new ArrayList<AtmosphereRequest>(); // We need to create a new AtmosphereRequest as WebSocket message may arrive concurrently on the same connection. list.add(new AtmosphereRequest.Builder() .request(resource.getRequest()) .method(methodType) .contentType(contentType) .body(d) .attributes(m) .pathInfo(pathInfo) .destroyable(destroyable) .headers(resource.getRequest().headersMap()) .session(resource.session()) .build()); return list; }
public List<AtmosphereRequest> onMessage(WebSocket webSocket, String d) { AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource(); if (resource == null) { logger.trace("The WebSocket has been closed before the message was processed."); return null; } String pathInfo = resource.getRequest().getPathInfo(); String requestURI = resource.getRequest().getRequestURI(); if (d.startsWith(delimiter)) { int delimiterLength = delimiter.length(); int bodyBeginIndex = d.indexOf(delimiter, delimiterLength); if (bodyBeginIndex != -1) { pathInfo = d.substring(delimiterLength, bodyBeginIndex); requestURI += pathInfo; d = d.substring(bodyBeginIndex + delimiterLength); } } Map<String,Object> m = new HashMap<String, Object>(); m.put(FrameworkConfig.WEBSOCKET_SUBPROTOCOL, FrameworkConfig.SIMPLE_HTTP_OVER_WEBSOCKET); // Propagate the original attribute to WebSocket message. m.putAll(resource.getRequest().attributes()); List<AtmosphereRequest> list = new ArrayList<AtmosphereRequest>(); // We need to create a new AtmosphereRequest as WebSocket message may arrive concurrently on the same connection. list.add(new AtmosphereRequest.Builder() .request(resource.getRequest()) .method(methodType) .contentType(contentType) .body(d) .attributes(m) .pathInfo(pathInfo) .requestURI(requestURI) .destroyable(destroyable) .headers(resource.getRequest().headersMap()) .session(resource.session()) .build()); return list; }
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesServlet.java b/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesServlet.java index d90f668ee..959f8b3af 100644 --- a/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesServlet.java +++ b/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesServlet.java @@ -1,163 +1,168 @@ /* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.pages; import groovy.lang.Writable; import groovy.text.Template; import java.io.IOException; import java.io.Writer; import java.net.URL; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException; import org.codehaus.groovy.grails.web.servlet.DefaultGrailsApplicationAttributes; import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes; /** * NOTE: Based on work done by on the GSP standalone project (https://gsp.dev.java.net/) * * Main servlet class. Example usage in web.xml: * <servlet> * <servlet-name>GroovyPagesServlet</servlet-name> * <servlet-class>org.codehaus.groovy.grails.web.pages.GroovyPagesServlet</servlet-class> * <init-param> * <param-name>showSource</param-name> * <param-value>1</param-value> * <description> * Allows developers to view the intermediade source code, when they pass * a showSource argument in the URL (eg /edit/list?showSource=true. * </description> * </init-param> * </servlet> * * @author Troy Heninger * @author Graeme Rocher * Date: Jan 10, 2004 * */ public class GroovyPagesServlet extends HttpServlet /*implements GroovyObject*/ { private static final Log LOG = LogFactory.getLog(GroovyPagesServlet.class); private ServletContext context; private boolean showSource = false; private static ClassLoader parent; private GroovyPagesTemplateEngine engine; private GrailsApplicationAttributes grailsAttributes; /** * @return the servlet context */ public ServletContext getServletContext() { return context; } /** * Initialize the servlet, set it's parameters. * @param config servlet settings */ public void init(ServletConfig config) { // Get the servlet context context = config.getServletContext(); context.log("GSP servlet initialized"); // Ensure that we use the correct classloader so that we can find // classes in an application server. parent = Thread.currentThread().getContextClassLoader(); if (parent == null) parent = getClass().getClassLoader(); showSource = config.getInitParameter("showSource") != null; this.grailsAttributes = new DefaultGrailsApplicationAttributes(context); } // init() /** * Handle HTTP GET requests. * @param request * @param response * @throws ServletException * @throws IOException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPage(request, response); } // doGet() /** * Handle HTTP POST requests. * @param request * @param response * @throws ServletException * @throws IOException */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPage(request, response); } // doPost() /** * Execute page and produce output. * @param request * @param response * @throws ServletException * @throws IOException */ public void doPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes); this.engine = grailsAttributes.getPagesTemplateEngine(); this.engine.setShowSource(this.showSource); String pageId = (String)request.getAttribute(GrailsApplicationAttributes.GSP_TO_RENDER); if(pageId == null) pageId = engine.getPageId(request); URL pageUrl = engine.getPageUrl(context,pageId); if (pageUrl == null) { context.log("GroovyPagesServlet: \"" + pageUrl + "\" not found"); response.sendError(404, "\"" + pageUrl + "\" not found."); return; } Template t = engine.createTemplate(context,request,response); if(t == null) { context.log("GroovyPagesServlet: \"" + pageUrl + "\" not found"); response.sendError(404, "\"" + pageUrl + "\" not found."); return; } Writable w = t.make(); Writer out = GSPResonseWriter.getInstance(response, 8192); try { w.writeTo(out); } catch(Exception e) { LOG.debug("Error processing GSP: " + e.getMessage(), e); request.setAttribute("exception",new GrailsWrappedRuntimeException(context,e)); RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/grails-app/views/error.jsp"); - rd.forward(request,response); + if(response.isCommitted()) { + rd.include(request,response); + } + else { + rd.forward(request,response); + } } finally { if (out != null) out.close(); } } // doPage() }
true
true
public void doPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes); this.engine = grailsAttributes.getPagesTemplateEngine(); this.engine.setShowSource(this.showSource); String pageId = (String)request.getAttribute(GrailsApplicationAttributes.GSP_TO_RENDER); if(pageId == null) pageId = engine.getPageId(request); URL pageUrl = engine.getPageUrl(context,pageId); if (pageUrl == null) { context.log("GroovyPagesServlet: \"" + pageUrl + "\" not found"); response.sendError(404, "\"" + pageUrl + "\" not found."); return; } Template t = engine.createTemplate(context,request,response); if(t == null) { context.log("GroovyPagesServlet: \"" + pageUrl + "\" not found"); response.sendError(404, "\"" + pageUrl + "\" not found."); return; } Writable w = t.make(); Writer out = GSPResonseWriter.getInstance(response, 8192); try { w.writeTo(out); } catch(Exception e) { LOG.debug("Error processing GSP: " + e.getMessage(), e); request.setAttribute("exception",new GrailsWrappedRuntimeException(context,e)); RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/grails-app/views/error.jsp"); rd.forward(request,response); } finally { if (out != null) out.close(); } } // doPage()
public void doPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes); this.engine = grailsAttributes.getPagesTemplateEngine(); this.engine.setShowSource(this.showSource); String pageId = (String)request.getAttribute(GrailsApplicationAttributes.GSP_TO_RENDER); if(pageId == null) pageId = engine.getPageId(request); URL pageUrl = engine.getPageUrl(context,pageId); if (pageUrl == null) { context.log("GroovyPagesServlet: \"" + pageUrl + "\" not found"); response.sendError(404, "\"" + pageUrl + "\" not found."); return; } Template t = engine.createTemplate(context,request,response); if(t == null) { context.log("GroovyPagesServlet: \"" + pageUrl + "\" not found"); response.sendError(404, "\"" + pageUrl + "\" not found."); return; } Writable w = t.make(); Writer out = GSPResonseWriter.getInstance(response, 8192); try { w.writeTo(out); } catch(Exception e) { LOG.debug("Error processing GSP: " + e.getMessage(), e); request.setAttribute("exception",new GrailsWrappedRuntimeException(context,e)); RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/grails-app/views/error.jsp"); if(response.isCommitted()) { rd.include(request,response); } else { rd.forward(request,response); } } finally { if (out != null) out.close(); } } // doPage()
diff --git a/src/vahdin/view/SingleBustSubview.java b/src/vahdin/view/SingleBustSubview.java index 646a8cf..4274c62 100644 --- a/src/vahdin/view/SingleBustSubview.java +++ b/src/vahdin/view/SingleBustSubview.java @@ -1,127 +1,127 @@ package vahdin.view; import java.util.Date; import vahdin.data.Bust; import vahdin.data.Mark; import com.vaadin.server.ExternalResource; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.CustomLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.UI; public class SingleBustSubview extends Subview { public SingleBustSubview() { } @Override public void show(String[] params) { if (params.length < 3) { UI.getCurrent().getNavigator().navigateTo("/"); } final String markId = params[2]; CustomLayout SingleBust = new CustomLayout("single-bust-sidebar"); Mark m1 = new Mark("Markin nimi", new Date(), "Markin kuvaus", 1, 1); Bust b1 = new Bust("Bustin nimi", 1, "Bustin kuvaus", 1, "1.3.2013", 123.123, 456.465); m1.addBust(b1); Label title = new Label("<h2>" + b1.getTitle() + "</h2>", Label.CONTENT_XHTML); Label date = new Label("<h4>" + b1.getTime() + "</h4>", Label.CONTENT_XHTML); Label user = new Label("<h4>Riku Riski</h4>", Label.CONTENT_XHTML); user.setStyleName("username"); Button voteup = new Button(); voteup.setStyleName("upvote"); voteup.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/up-arrow.png")); voteup.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Voteup clicked"); } }); Label votes = new Label("2"); votes.setStyleName("vote-count"); Button votedown = new Button(); votedown.setStyleName("downvote"); votedown.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/down-arrow.png")); votedown.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Votedown clicked"); } }); Button delete = new Button(); delete.setStyleName("new-mark-button"); delete.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/delete-button.png")); delete.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Delete clicked"); } }); Button back = new Button(); back.setStyleName("go-back-button"); back.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/back-button.png")); back.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { UI.getCurrent().getNavigator().navigateTo("/" + markId + "/"); } }); Label desc = new Label("<p>" + b1.getDescription() + "</p>", Label.CONTENT_XHTML); desc.setStyleName("mark-description"); Button viewImage = new Button("View image"); viewImage.setStyleName("view-image-button"); viewImage.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("View image"); } }); SingleBust.addComponent(title, "bust-title"); SingleBust.addComponent(date, "bust-datetime"); SingleBust.addComponent(user, "bust-submitter-nickname"); SingleBust.addComponent(voteup, "bust-upvote-arrow"); - SingleBust.addComponent(votes, "vote-count"); + SingleBust.addComponent(votes, "bust-vote-count"); SingleBust.addComponent(votedown, "bust-downvote-arrow"); SingleBust.addComponent(delete, "bust-delete-button"); SingleBust.addComponent(back, "bust-back-button"); SingleBust.addComponent(desc, "bust-description"); setCompositionRoot(SingleBust); addStyleName("open"); super.show(params); } }
true
true
public void show(String[] params) { if (params.length < 3) { UI.getCurrent().getNavigator().navigateTo("/"); } final String markId = params[2]; CustomLayout SingleBust = new CustomLayout("single-bust-sidebar"); Mark m1 = new Mark("Markin nimi", new Date(), "Markin kuvaus", 1, 1); Bust b1 = new Bust("Bustin nimi", 1, "Bustin kuvaus", 1, "1.3.2013", 123.123, 456.465); m1.addBust(b1); Label title = new Label("<h2>" + b1.getTitle() + "</h2>", Label.CONTENT_XHTML); Label date = new Label("<h4>" + b1.getTime() + "</h4>", Label.CONTENT_XHTML); Label user = new Label("<h4>Riku Riski</h4>", Label.CONTENT_XHTML); user.setStyleName("username"); Button voteup = new Button(); voteup.setStyleName("upvote"); voteup.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/up-arrow.png")); voteup.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Voteup clicked"); } }); Label votes = new Label("2"); votes.setStyleName("vote-count"); Button votedown = new Button(); votedown.setStyleName("downvote"); votedown.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/down-arrow.png")); votedown.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Votedown clicked"); } }); Button delete = new Button(); delete.setStyleName("new-mark-button"); delete.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/delete-button.png")); delete.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Delete clicked"); } }); Button back = new Button(); back.setStyleName("go-back-button"); back.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/back-button.png")); back.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { UI.getCurrent().getNavigator().navigateTo("/" + markId + "/"); } }); Label desc = new Label("<p>" + b1.getDescription() + "</p>", Label.CONTENT_XHTML); desc.setStyleName("mark-description"); Button viewImage = new Button("View image"); viewImage.setStyleName("view-image-button"); viewImage.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("View image"); } }); SingleBust.addComponent(title, "bust-title"); SingleBust.addComponent(date, "bust-datetime"); SingleBust.addComponent(user, "bust-submitter-nickname"); SingleBust.addComponent(voteup, "bust-upvote-arrow"); SingleBust.addComponent(votes, "vote-count"); SingleBust.addComponent(votedown, "bust-downvote-arrow"); SingleBust.addComponent(delete, "bust-delete-button"); SingleBust.addComponent(back, "bust-back-button"); SingleBust.addComponent(desc, "bust-description"); setCompositionRoot(SingleBust); addStyleName("open"); super.show(params); }
public void show(String[] params) { if (params.length < 3) { UI.getCurrent().getNavigator().navigateTo("/"); } final String markId = params[2]; CustomLayout SingleBust = new CustomLayout("single-bust-sidebar"); Mark m1 = new Mark("Markin nimi", new Date(), "Markin kuvaus", 1, 1); Bust b1 = new Bust("Bustin nimi", 1, "Bustin kuvaus", 1, "1.3.2013", 123.123, 456.465); m1.addBust(b1); Label title = new Label("<h2>" + b1.getTitle() + "</h2>", Label.CONTENT_XHTML); Label date = new Label("<h4>" + b1.getTime() + "</h4>", Label.CONTENT_XHTML); Label user = new Label("<h4>Riku Riski</h4>", Label.CONTENT_XHTML); user.setStyleName("username"); Button voteup = new Button(); voteup.setStyleName("upvote"); voteup.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/up-arrow.png")); voteup.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Voteup clicked"); } }); Label votes = new Label("2"); votes.setStyleName("vote-count"); Button votedown = new Button(); votedown.setStyleName("downvote"); votedown.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/down-arrow.png")); votedown.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Votedown clicked"); } }); Button delete = new Button(); delete.setStyleName("new-mark-button"); delete.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/delete-button.png")); delete.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("Delete clicked"); } }); Button back = new Button(); back.setStyleName("go-back-button"); back.setIcon(new ExternalResource( "VAADIN/themes/vahdintheme/img/back-button.png")); back.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { UI.getCurrent().getNavigator().navigateTo("/" + markId + "/"); } }); Label desc = new Label("<p>" + b1.getDescription() + "</p>", Label.CONTENT_XHTML); desc.setStyleName("mark-description"); Button viewImage = new Button("View image"); viewImage.setStyleName("view-image-button"); viewImage.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Notification.show("View image"); } }); SingleBust.addComponent(title, "bust-title"); SingleBust.addComponent(date, "bust-datetime"); SingleBust.addComponent(user, "bust-submitter-nickname"); SingleBust.addComponent(voteup, "bust-upvote-arrow"); SingleBust.addComponent(votes, "bust-vote-count"); SingleBust.addComponent(votedown, "bust-downvote-arrow"); SingleBust.addComponent(delete, "bust-delete-button"); SingleBust.addComponent(back, "bust-back-button"); SingleBust.addComponent(desc, "bust-description"); setCompositionRoot(SingleBust); addStyleName("open"); super.show(params); }
diff --git a/IceCaveProject/src/com/android/icecave/mapLogic/collision/BaseCollisionInvoker.java b/IceCaveProject/src/com/android/icecave/mapLogic/collision/BaseCollisionInvoker.java index 4a2d5a3..406b0a9 100644 --- a/IceCaveProject/src/com/android/icecave/mapLogic/collision/BaseCollisionInvoker.java +++ b/IceCaveProject/src/com/android/icecave/mapLogic/collision/BaseCollisionInvoker.java @@ -1,20 +1,20 @@ package com.android.icecave.mapLogic.collision; import android.graphics.Point; import com.android.icecave.general.IFunction; public class BaseCollisionInvoker<return_type> implements ICollisionInvoker<return_type> { IFunction<return_type> mFunction; public BaseCollisionInvoker(IFunction<return_type> function) { mFunction = function; } @Override public return_type onCollision(Point collisionPoint) { - return mFunction.invoke(collisionPoint); + return mFunction.invoke(new Point(collisionPoint)); } }
true
true
public return_type onCollision(Point collisionPoint) { return mFunction.invoke(collisionPoint); }
public return_type onCollision(Point collisionPoint) { return mFunction.invoke(new Point(collisionPoint)); }
diff --git a/src/main/java/org/molgenis/genotype/RandomAccessGenotypedDataReaderFormats.java b/src/main/java/org/molgenis/genotype/RandomAccessGenotypedDataReaderFormats.java index 6a33f36..74e8655 100644 --- a/src/main/java/org/molgenis/genotype/RandomAccessGenotypedDataReaderFormats.java +++ b/src/main/java/org/molgenis/genotype/RandomAccessGenotypedDataReaderFormats.java @@ -1,58 +1,58 @@ package org.molgenis.genotype; import java.io.File; import java.io.IOException; import org.molgenis.genotype.impute2.Impute2GenotypeData; import org.molgenis.genotype.multipart.IncompetibleMultiPartGenotypeDataException; import org.molgenis.genotype.multipart.MultiPartGenotypeData; import org.molgenis.genotype.plink.PedMapGenotypeData; import org.molgenis.genotype.vcf.VcfGenotypeData; public enum RandomAccessGenotypedDataReaderFormats { PED_MAP("PED / MAP file", "plink PED MAP files gziped with tabix index."), VCF("VCF file", "gziped vcf with tabix index file"), VCF_FOLDER("VCF folder", "Matches all gziped vcf files + tabix index in a folder"), SHAPEIT2("Shapeit2 output", ".haps and .samples with phased haplotypes as outputted by Shapeit2"); private final String name; private final String description; RandomAccessGenotypedDataReaderFormats(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } public RandomAccessGenotypeData createGenotypeData(String path, int cacheSize) throws IOException, IncompetibleMultiPartGenotypeDataException { switch (this) { case PED_MAP: return new PedMapGenotypeData(new File(path + ".ped"), new File(path + ".map")); case VCF: return new VcfGenotypeData(new File(path), cacheSize); case VCF_FOLDER: return MultiPartGenotypeData.createFromVcfFolder(new File(path), cacheSize); case SHAPEIT2: - return new Impute2GenotypeData(new File(path + ".haps"), new File(path + ".haps.tbi"), new File(path - + ".sample")); + return new Impute2GenotypeData(new File(path + ".haps.gz"), new File(path + ".haps.gz.tbi"), new File( + path + ".sample")); default: throw new RuntimeException("This should not be reachable. Please contact the autors"); } } }
true
true
public RandomAccessGenotypeData createGenotypeData(String path, int cacheSize) throws IOException, IncompetibleMultiPartGenotypeDataException { switch (this) { case PED_MAP: return new PedMapGenotypeData(new File(path + ".ped"), new File(path + ".map")); case VCF: return new VcfGenotypeData(new File(path), cacheSize); case VCF_FOLDER: return MultiPartGenotypeData.createFromVcfFolder(new File(path), cacheSize); case SHAPEIT2: return new Impute2GenotypeData(new File(path + ".haps"), new File(path + ".haps.tbi"), new File(path + ".sample")); default: throw new RuntimeException("This should not be reachable. Please contact the autors"); } }
public RandomAccessGenotypeData createGenotypeData(String path, int cacheSize) throws IOException, IncompetibleMultiPartGenotypeDataException { switch (this) { case PED_MAP: return new PedMapGenotypeData(new File(path + ".ped"), new File(path + ".map")); case VCF: return new VcfGenotypeData(new File(path), cacheSize); case VCF_FOLDER: return MultiPartGenotypeData.createFromVcfFolder(new File(path), cacheSize); case SHAPEIT2: return new Impute2GenotypeData(new File(path + ".haps.gz"), new File(path + ".haps.gz.tbi"), new File( path + ".sample")); default: throw new RuntimeException("This should not be reachable. Please contact the autors"); } }
diff --git a/src/net/sourceforge/mxupdate/update/AbstractBusObject_mxJPO.java b/src/net/sourceforge/mxupdate/update/AbstractBusObject_mxJPO.java index 12e863a5..9f963b1f 100644 --- a/src/net/sourceforge/mxupdate/update/AbstractBusObject_mxJPO.java +++ b/src/net/sourceforge/mxupdate/update/AbstractBusObject_mxJPO.java @@ -1,490 +1,490 @@ /* * Copyright 2008 The MxUpdate Team * * 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. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package net.sourceforge.mxupdate.update; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeSet; import matrix.db.BusinessObject; import matrix.db.BusinessObjectWithSelect; import matrix.db.BusinessObjectWithSelectList; import matrix.db.Context; import matrix.db.Query; import matrix.util.MatrixException; import matrix.util.StringList; import static net.sourceforge.mxupdate.update.util.StringUtil_mxJPO.convert; import static net.sourceforge.mxupdate.update.util.StringUtil_mxJPO.match; /** * @author tmoxter * @version $Id$ */ public abstract class AbstractBusObject_mxJPO extends net.sourceforge.mxupdate.update.AbstractPropertyObject_mxJPO { /** * Defines the serialize version unique identifier. */ private static final long serialVersionUID = -5381775541507933947L; /** * String used to split the name and revision of administrational business * object. */ private static final String SPLIT_NAME = "________"; /** * Attribute name of the author. */ private static final String ATTR_AUTHOR = "emxGerLibUpdateAuthor"; /** * Attribute name of the installation date. */ private static final String ATTR_INSTALLED_DATE = "emxGerLibUpdateInstalledDate"; /** * Attribute name of the updated version. */ private static final String ATTR_UPDATE_VERSION = "emxGerLibUpdateVersion"; /** * All attribute values of this business object. * * @see #parse(String, String) reads the attribute values * @see #prepare(Context) sortes the attribute values */ private final Stack<Attribute> attrValues = new Stack<Attribute>(); /** * Sorted set of attribute values. * * @see #prepare(Context) sorted the attribute values * @see #getAttrValuesSorted() */ private final Set<Attribute> attrValuesSorted = new TreeSet<Attribute>(); /** * Name of business object. * * @see #parse(String, String) * @see #getBusName() */ private String busName = null; /** * Revision of business object. * * @see #parse(String, String) * @see #getBusRevision() */ private String busRevision = null; /** * Vault of the business object. * * @see #parse(String, String) */ private String busVault = null; /** * Description of the business object (because the description within the * header of the TCL file includes the revision of the business object). * * @see #parse(String, String) * @see #getBusDescription() */ private String busDescription = null; /** * Evaluates the matching names for this administrational business objects. * Matching means, that the name and / or revision of the business object * matches the collection of given matches. * * @param _context context for this request * @param _matches collection of matches * @return set of found matching business object names */ @Override public Set<String> getMatchingNames(final Context _context, final Collection<String> _matches) throws MatrixException { final StringList selects = new StringList(); selects.addElement("name"); selects.addElement("revision"); final Query query = new Query(); query.open(_context); query.setBusinessObjectType(getBusType()); final BusinessObjectWithSelectList list = query.select(_context, selects); query.close(_context); final Set<String> ret = new TreeSet<String>(); for (final Object mapObj : list) { final BusinessObjectWithSelect map = (BusinessObjectWithSelect) mapObj; final StringBuilder name = new StringBuilder() .append(map.getSelectDataList("name").get(0)); final String revision = (String) map.getSelectDataList("revision").get(0); if ((revision != null) && !"".equals(revision)) { name.append(SPLIT_NAME) .append(map.getSelectDataList("revision").get(0)); } for (final String match : _matches) { if (match(name.toString(), match)) { ret.add(name.toString()); } } } return ret; } /** * Prepares the MQL statement to export the business object as XML string. * * @param _name name of business object to export (name and revision, * separated by the splitter string) * @return prepared MQL statement * @see #SPLIT_NAME used splitter between name and revision */ @Override protected String getExportMQL(final String _name) { final String[] nameRev = _name.split(SPLIT_NAME); return new StringBuilder() .append("export bus \"") .append(getBusType()) .append("\" \"").append(nameRev[0]) .append("\" \"").append((nameRev.length > 1) ? nameRev[1] : "") .append("\" !file !icon !history !relationship !state xml") .toString(); } /** * Parses the XML url for the business object XML export file. * * @param _url url * @param _content content */ @Override protected void parse(final String _url, final String _content) { if ("/attributeList".equals(_url)) { // to be ignored ... } else if ("/attributeList/attribute".equals(_url)) { this.attrValues.add(new Attribute()); } else if ("/attributeList/attribute/name".equals(_url)) { this.attrValues.peek().name = _content; } else if ("/attributeList/attribute/string".equals(_url)) { this.attrValues.peek().value = _content; } else if ("/objectType".equals(_url)) { // to be ignored ... } else if ("/objectName".equals(_url)) { this.busName = _content; } else if ("/objectRevision".equals(_url)) { this.busRevision = _content; } else if ("/description".equals(_url)) { this.busDescription = _content; } else if ("/vaultRef".equals(_url)) { this.busVault = _content; } else if ("/policyRef".equals(_url)) { // to be ignored ... } else if ("/owner".equals(_url)) { // to be ignored ... } else if ("/owner/userRef".equals(_url)) { // to be ignored ... } else if ("/creationInfo".equals(_url)) { // to be ignored ... } else if ("/creationInfo/datetime".equals(_url)) { // to be ignored ... } else if ("/modificationInfo".equals(_url)) { // to be ignored ... } else if ("/modificationInfo/datetime".equals(_url)) { // to be ignored ... } else { super.parse(_url, _content); } } /** * Sorts the attribute values, defines the description for the TCL * update script (concatenation of the revision and description) and the * name (concatenation of name and revision). * * @param _context context for this request * @see #attrValues unsorted attribute values * @see #attrValuesSorted sorted attribute values * @see #busDescription business description * @see #busRevision business revison */ @Override protected void prepare(final Context _context) throws MatrixException { for (final Attribute attrValue : this.attrValues) { if (ATTR_AUTHOR.equals(attrValue.name)) { this.setAuthor(attrValue.value); } else if (ATTR_UPDATE_VERSION.equals(attrValue.name)) { this.setVersion(attrValue.value); } else if (!ATTR_INSTALLED_DATE.equals(attrValue.name)) { this.attrValuesSorted.add(attrValue); } } // defines the description final StringBuilder desc = new StringBuilder(); if (this.busRevision != null) { desc.append(this.busRevision); if (this.busDescription != null) { desc.append('\n'); } } if (this.busDescription != null) { desc.append(this.busDescription); } setDescription(desc.toString()); // defines the name final StringBuilder name = new StringBuilder().append(this.busName); if (this.busRevision != null) { name.append(SPLIT_NAME).append(this.busRevision); } setName(name.toString()); } /** * Writes the information to update the business objects. * * @param _out writer instance */ @Override protected void write(final Writer _out) throws IOException { writeHeader(_out); _out.append("mql mod bus \"${OBJECTID}\"") .append(" \\\n description \"").append(convert(this.busDescription)).append("\""); for (final Attribute attr : this.attrValuesSorted) { _out.append(" \\\n \"").append(convert(attr.name)) .append("\" \"").append(convert(attr.value)).append("\""); } } /** * The method overwrites the original method to * <ul> * <li>reset the description</li> * <li>set the version and author attribute</li> * <li>reset all not ignored attributes</li> * <li>define the TCL variable &quot;OBJECTID&quot; with the object id of * the represented business object</li> * </ul> * The original method of the super class if called surrounded with a * history off, because if the update itself is done the modified basic * attribute and the version attribute of the business object is updated. * <br/> * The new generated MQL code is set in the front of the already defined * MQL code in <code>_preMQLCode</code> and appended to the MQL statements * in <code>_postMQLCode</code>. * * @param _context context for this request * @param _preMQLCode MQL statements which must be called before the * TCL code is executed * @param _postMQLCode MQL statements which must be called after the * TCL code is executed * @param _tclCode TCL code from the file used to update * @param _tclVariables map of all TCL variables where the key is the * name and the value is value of the TCL variable * (the value is automatically converted to TCL * syntax!) */ @Override protected void update(final Context _context, final CharSequence _preMQLCode, final CharSequence _postMQLCode, final CharSequence _tclCode, final Map<String,String> _tclVariables) throws Exception { // found the business object final BusinessObject bus = new BusinessObject(this.getBusType(), this.getBusName(), this.getBusRevision(), this.getBusVault()); final String objectId = bus.getObjectId(_context); // resets the description final StringBuilder preMQLCode = new StringBuilder() .append("mod bus ").append(objectId).append(" description \"\""); // reset all attributes (if they must not be ignored...) final String[] ignoreAttrs = this.getInfoAnno().busIgnoreAttributes(); for (final Attribute attr : this.attrValuesSorted) { // TODO: use default attribute value instead of "" boolean found = false; for (final String ignoreAttr : ignoreAttrs) { if (ignoreAttr.equals(attr.name)) { found = true; break; } } if (!found) { preMQLCode.append(" \"").append(attr.name).append("\" \"\""); } } preMQLCode.append(";\n"); // append other pre MQL code preMQLCode.append(_preMQLCode); // post update MQL statements to define the version final StringBuilder postMQLCode = new StringBuilder() .append(_postMQLCode) .append("mod bus ").append(objectId).append(" \"") - .append(ATTR_UPDATE_VERSION).append("\" \"").append(_tclVariables.get("VERSION")).append("\" \""); + .append(ATTR_UPDATE_VERSION).append("\" \"").append(_tclVariables.get("VERSION")).append("\";\n"); // prepare map of all TCL variables incl. id of business object final Map<String,String> tclVariables = new HashMap<String,String>(); tclVariables.put("OBJECTID", objectId); tclVariables.putAll(_tclVariables); // update must be done with history off (because not required...) try { this.execMql(_context, "history off;"); super.update(_context, preMQLCode, postMQLCode, _tclCode, tclVariables); } finally { this.execMql(_context, "history on;"); } } /** * Returns the business type of this business object instance. The business * type is evaluated from the business type annotation. * * @return business type */ protected String getBusType() { return getInfoAnno().busType(); } /** * Getter method for instance variable {@link #busName}. * * @return value of instance variable {@link #busName} * @see #busName */ protected String getBusName() { return this.busName; } /** * Getter method for instance variable {@link #busRevision}. If * {@link #busRevision} is <code>null</code> an empty string "" is returned. * * @return value of instance variable {@link #busRevision} * @see #busRevision */ protected String getBusRevision() { return (this.busRevision == null) ? "" : this.busRevision; } /** * Getter method for instance variable {@link #busVault}. * * @return value of instance variable {@link #busVault} * @see #busVault */ protected String getBusVault() { return this.busVault; } /** * Getter method for instance variable {@link #busDescription}. * * @return value of instance variable {@link #busDescription} * @see #busDescription */ protected String getBusDescription() { return this.busDescription; } /** * Getter method for instance variable {@link #attrValuesSorted}. * * @return value of instance variable {@link #attrValuesSorted} * @see #attrValuesSorted */ protected Set<Attribute> getAttrValuesSorted() { return this.attrValuesSorted; } /** * Class used to hold the user access. */ protected class Attribute implements Comparable<Attribute> { /** * Holds the user references of a user access. */ public String name = null; /** * Holds the expression filter of a user access. */ public String value = null; /** * @param _attribute attribute instance to compare */ public int compareTo(final Attribute _attribute) { final String name1 = this.name.replaceAll(" [0-9]*$", ""); final String name2 = _attribute.name.replaceAll(" [0-9]*$", ""); int ret = 0; if (name1.equals(name2) && !name1.equals(this.name)) { final int index = name1.length(); final Integer num1 = Integer.parseInt(this.name.substring(index).trim()); final Integer num2 = Integer.parseInt(_attribute.name.substring(index).trim()); ret = num1.compareTo(num2); } else { ret = this.name.compareTo(_attribute.name); } return ret; } } }
true
true
protected void update(final Context _context, final CharSequence _preMQLCode, final CharSequence _postMQLCode, final CharSequence _tclCode, final Map<String,String> _tclVariables) throws Exception { // found the business object final BusinessObject bus = new BusinessObject(this.getBusType(), this.getBusName(), this.getBusRevision(), this.getBusVault()); final String objectId = bus.getObjectId(_context); // resets the description final StringBuilder preMQLCode = new StringBuilder() .append("mod bus ").append(objectId).append(" description \"\""); // reset all attributes (if they must not be ignored...) final String[] ignoreAttrs = this.getInfoAnno().busIgnoreAttributes(); for (final Attribute attr : this.attrValuesSorted) { // TODO: use default attribute value instead of "" boolean found = false; for (final String ignoreAttr : ignoreAttrs) { if (ignoreAttr.equals(attr.name)) { found = true; break; } } if (!found) { preMQLCode.append(" \"").append(attr.name).append("\" \"\""); } } preMQLCode.append(";\n"); // append other pre MQL code preMQLCode.append(_preMQLCode); // post update MQL statements to define the version final StringBuilder postMQLCode = new StringBuilder() .append(_postMQLCode) .append("mod bus ").append(objectId).append(" \"") .append(ATTR_UPDATE_VERSION).append("\" \"").append(_tclVariables.get("VERSION")).append("\" \""); // prepare map of all TCL variables incl. id of business object final Map<String,String> tclVariables = new HashMap<String,String>(); tclVariables.put("OBJECTID", objectId); tclVariables.putAll(_tclVariables); // update must be done with history off (because not required...) try { this.execMql(_context, "history off;"); super.update(_context, preMQLCode, postMQLCode, _tclCode, tclVariables); } finally { this.execMql(_context, "history on;"); } }
protected void update(final Context _context, final CharSequence _preMQLCode, final CharSequence _postMQLCode, final CharSequence _tclCode, final Map<String,String> _tclVariables) throws Exception { // found the business object final BusinessObject bus = new BusinessObject(this.getBusType(), this.getBusName(), this.getBusRevision(), this.getBusVault()); final String objectId = bus.getObjectId(_context); // resets the description final StringBuilder preMQLCode = new StringBuilder() .append("mod bus ").append(objectId).append(" description \"\""); // reset all attributes (if they must not be ignored...) final String[] ignoreAttrs = this.getInfoAnno().busIgnoreAttributes(); for (final Attribute attr : this.attrValuesSorted) { // TODO: use default attribute value instead of "" boolean found = false; for (final String ignoreAttr : ignoreAttrs) { if (ignoreAttr.equals(attr.name)) { found = true; break; } } if (!found) { preMQLCode.append(" \"").append(attr.name).append("\" \"\""); } } preMQLCode.append(";\n"); // append other pre MQL code preMQLCode.append(_preMQLCode); // post update MQL statements to define the version final StringBuilder postMQLCode = new StringBuilder() .append(_postMQLCode) .append("mod bus ").append(objectId).append(" \"") .append(ATTR_UPDATE_VERSION).append("\" \"").append(_tclVariables.get("VERSION")).append("\";\n"); // prepare map of all TCL variables incl. id of business object final Map<String,String> tclVariables = new HashMap<String,String>(); tclVariables.put("OBJECTID", objectId); tclVariables.putAll(_tclVariables); // update must be done with history off (because not required...) try { this.execMql(_context, "history off;"); super.update(_context, preMQLCode, postMQLCode, _tclCode, tclVariables); } finally { this.execMql(_context, "history on;"); } }
diff --git a/src/core/org/luaj/vm2/lib/BaseLib.java b/src/core/org/luaj/vm2/lib/BaseLib.java index f5b639f..fabc868 100644 --- a/src/core/org/luaj/vm2/lib/BaseLib.java +++ b/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/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTaskListPlugin.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTaskListPlugin.java index d95c685c8..7715c51d9 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTaskListPlugin.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTaskListPlugin.java @@ -1,642 +1,634 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia 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: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.tasklist; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.core.MylarPrefContstants; import org.eclipse.mylar.core.util.MylarStatusHandler; import org.eclipse.mylar.tasklist.internal.TaskListExtensionReader; import org.eclipse.mylar.tasklist.internal.TaskListManager; import org.eclipse.mylar.tasklist.internal.TaskListSaveManager; import org.eclipse.mylar.tasklist.internal.TaskListWriter; import org.eclipse.mylar.tasklist.internal.planner.ReminderRequiredCollector; import org.eclipse.mylar.tasklist.internal.planner.TaskReportGenerator; import org.eclipse.mylar.tasklist.repositories.TaskRepository; import org.eclipse.mylar.tasklist.repositories.TaskRepositoryManager; import org.eclipse.mylar.tasklist.ui.IContextEditorFactory; import org.eclipse.mylar.tasklist.ui.IDynamicSubMenuContributor; import org.eclipse.mylar.tasklist.ui.ITaskHighlighter; import org.eclipse.mylar.tasklist.ui.ITaskListElement; import org.eclipse.mylar.tasklist.ui.TasksReminderDialog; import org.eclipse.mylar.tasklist.ui.views.TaskListView; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.ShellListener; import org.eclipse.ui.IStartup; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.Workbench; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * @author Mik Kersten * * TODO: this class is in serious need of refactoring */ public class MylarTaskListPlugin extends AbstractUIPlugin implements IStartup { public static final String PLUGIN_ID = "org.eclipse.mylar.tasklist"; private static MylarTaskListPlugin INSTANCE; private static TaskListManager taskListManager; private static TaskRepositoryManager taskRepositoryManager; private TaskListSaveManager taskListSaveManager = new TaskListSaveManager(); private List<ITaskHandler> taskHandlers = new ArrayList<ITaskHandler>(); // TODO: // use // extension // points private List<IContextEditorFactory> contextEditors = new ArrayList<IContextEditorFactory>(); private TaskListWriter taskListWriter; public static final String FILE_EXTENSION = ".xml"; public static final String DEFAULT_TASK_LIST_FILE = "tasklist" + FILE_EXTENSION; private ResourceBundle resourceBundle; private long AUTOMATIC_BACKUP_SAVE_INTERVAL = 1 * 3600 * 1000; // every // hour private static Date lastBackup = new Date(); private ITaskHighlighter highlighter; private static boolean shellActive = true; public enum TaskListSaveMode { ONE_HOUR, THREE_HOURS, DAY; @Override public String toString() { switch (this) { case ONE_HOUR: return "1 hour"; case THREE_HOURS: return "3 hours"; case DAY: return "1 day"; default: return "3 hours"; } } public static TaskListSaveMode fromString(String string) { if (string == null) return null; if (string.equals("1 hour")) return ONE_HOUR; if (string.equals("3 hours")) return THREE_HOURS; if (string.equals("1 day")) return DAY; return null; } public static long fromStringToLong(String string) { long hour = 3600 * 1000; switch (fromString(string)) { case ONE_HOUR: return hour; case THREE_HOURS: return hour * 3; case DAY: return hour * 24; default: return hour * 3; } } } public enum ReportOpenMode { EDITOR, INTERNAL_BROWSER, EXTERNAL_BROWSER; } public enum PriorityLevel { P1, P2, P3, P4, P5; @Override public String toString() { switch (this) { case P1: return "P1"; case P2: return "P2"; case P3: return "P3"; case P4: return "P4"; case P5: return "P5"; default: return "P5"; } } public static PriorityLevel fromString(String string) { if (string == null) return null; if (string.equals("P1")) return P1; if (string.equals("P2")) return P2; if (string.equals("P3")) return P3; if (string.equals("P4")) return P4; if (string.equals("P5")) return P5; return null; } } private static ITaskActivityListener CONTEXT_TASK_ACTIVITY_LISTENER = new ITaskActivityListener() { public void taskActivated(ITask task) { MylarPlugin.getContextManager().contextActivated(task.getHandleIdentifier()); } public void tasksActivated(List<ITask> tasks) { for (ITask task : tasks) { MylarPlugin.getContextManager().contextActivated(task.getHandleIdentifier()); } } public void taskDeactivated(ITask task) { MylarPlugin.getContextManager().contextDeactivated(task.getHandleIdentifier()); } public void tasklistRead() { // ignore } public void taskChanged(ITask task) { // TODO Auto-generated method stub } public void tasklistModified() { // TODO Auto-generated method stub } }; /** * TODO: move into reminder mechanims */ private static ShellListener SHELL_LISTENER = new ShellListener() { public void shellClosed(ShellEvent arg0) { // ignore } /** * bug 1002249: too slow to save state here */ public void shellDeactivated(ShellEvent arg0) { shellActive = false; } public void shellActivated(ShellEvent arg0) { getDefault().checkTaskListBackup(); getDefault().checkReminders(); shellActive = true; } public void shellDeiconified(ShellEvent arg0) { // ingore } public void shellIconified(ShellEvent arg0) { // ignore } }; private final IPropertyChangeListener PREFERENCE_LISTENER = new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(MylarTaskListPrefConstants.MULTIPLE_ACTIVE_TASKS)) { TaskListView.getDefault().togglePreviousAction( !getPrefs().getBoolean(MylarTaskListPrefConstants.MULTIPLE_ACTIVE_TASKS)); TaskListView.getDefault().toggleNextAction( !getPrefs().getBoolean(MylarTaskListPrefConstants.MULTIPLE_ACTIVE_TASKS)); TaskListView.getDefault().clearTaskHistory(); } if (event.getProperty().equals(MylarPrefContstants.PREF_DATA_DIR)) { if (event.getOldValue() instanceof String) { String newDirPath = MylarPlugin.getDefault().getDataDirectory(); String taskListFilePath = newDirPath + File.separator + DEFAULT_TASK_LIST_FILE; getTaskListSaveManager().saveTaskListAndContexts(); getTaskListManager().setTaskListFile(new File(taskListFilePath)); getTaskListManager().createNewTaskList(); getTaskListManager().readOrCreateTaskList(); if (TaskListView.getDefault() != null) TaskListView.getDefault().clearTaskHistory(); } } } }; public MylarTaskListPlugin() { super(); INSTANCE = this; // List<ITaskListExternalizer> externalizers = new // ArrayList<ITaskListExternalizer>(); try { initializeDefaultPreferences(getPrefs()); taskListWriter = new TaskListWriter(); String path = MylarPlugin.getDefault().getDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE; File taskListFile = new File(path); // TODO: decouple from core int nextTaskId = 1; if (MylarPlugin.getDefault() != null && MylarPlugin.getDefault().getPreferenceStore().contains(MylarTaskListPrefConstants.TASK_ID)) { // TODO: // fix // to // MylarTaskListPlugin nextTaskId = MylarPlugin.getDefault().getPreferenceStore().getInt(MylarTaskListPrefConstants.TASK_ID); } taskListManager = new TaskListManager(taskListWriter, taskListFile, nextTaskId); taskRepositoryManager = new TaskRepositoryManager(); } catch (Exception e) { MylarStatusHandler.fail(e, "Mylar Task List initialization failed", false); } } /** * Startup order is critical */ public void earlyStartup() { final IWorkbench workbench = PlatformUI.getWorkbench(); workbench.getDisplay().asyncExec(new Runnable() { public void run() { try { TaskListExtensionReader.initExtensions(taskListWriter); taskRepositoryManager.readRepositories(); taskListManager.addListener(CONTEXT_TASK_ACTIVITY_LISTENER); taskListManager.addListener(taskListSaveManager); Workbench.getInstance().getActiveWorkbenchWindow().getShell().addShellListener(SHELL_LISTENER); MylarPlugin.getDefault().getPluginPreferences().addPropertyChangeListener(PREFERENCE_LISTENER); Workbench.getInstance().getActiveWorkbenchWindow().getShell().addDisposeListener( taskListSaveManager); restoreTaskHandlerState(); taskListManager.readOrCreateTaskList(); restoreTaskHandlerState(); migrateHandlesToRepositorySupport(); } catch (Exception e) { MylarStatusHandler.fail(e, "Task List initialization failed", true); } } }); } private void migrateHandlesToRepositorySupport() { boolean migrated = false; if (!getPreferenceStore().getBoolean(MylarTaskListPrefConstants.CONTEXTS_MIGRATED)) { File dataDir = new File(MylarPlugin.getDefault().getDataDirectory()); TaskRepository defaultRepository = MylarTaskListPlugin.getRepositoryManager().getDefaultRepository( TaskRepositoryManager.PREFIX_REPOSITORY_OLD.toLowerCase()); if (defaultRepository != null) { String repositoryUrl = defaultRepository.getUrl().toExternalForm(); migrated = true; if (dataDir.exists() && dataDir.isDirectory()) { for (File file : dataDir.listFiles()) { String oldHandle = file.getName().substring(0, file.getName().lastIndexOf('.')); if (oldHandle.startsWith(TaskRepositoryManager.PREFIX_REPOSITORY_OLD)) { String id = TaskRepositoryManager.getTaskId(oldHandle); String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); File newFile = MylarPlugin.getContextManager().getFileForContext(newHandle); file.renameTo(newFile); } } } for (ITask task : taskListManager.getTaskList().getAllTasks()) { if (!task.isLocal()) { String id = TaskRepositoryManager.getTaskId(task.getHandleIdentifier()); String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); task.setHandleIdentifier(newHandle); -// System.err.println(">>> task: " + task.getHandleIdentifier()); } } for (ITaskQuery query : taskListManager.getTaskList().getQueries()) { query.setRepositoryUrl(repositoryUrl); for (IQueryHit hit : query.getHits()) { -// String id = TaskRepositoryManager.getTaskId(hit.getHandleIdentifier()); -// String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); hit.setRepositoryUrl(repositoryUrl); - // hit.setHandleIdentifier(newHandle); -// System.err.println(">>> hit: " + hit.getHandleIdentifier()); } } } } if (migrated) { MylarStatusHandler.log("Migrated context files to repository-aware paths", this); - getPreferenceStore().setValue(MylarTaskListPrefConstants.CONTEXTS_MIGRATED, false); -// taskListManager.saveTaskList(); -// taskListManager.readOrCreateTaskList(); -// restoreTaskHandlerState(); + getPreferenceStore().setValue(MylarTaskListPrefConstants.CONTEXTS_MIGRATED, true); } } @Override public void start(BundleContext context) throws Exception { super.start(context); } @Override public void stop(BundleContext context) throws Exception { super.stop(context); INSTANCE = null; resourceBundle = null; try { taskListManager.removeListener(taskListSaveManager); if (MylarPlugin.getDefault() != null) { MylarPlugin.getDefault().getPluginPreferences().removePropertyChangeListener(PREFERENCE_LISTENER); } if (Workbench.getInstance() != null && Workbench.getInstance().getActiveWorkbenchWindow() != null) { Workbench.getInstance().getActiveWorkbenchWindow().getShell().removeShellListener(SHELL_LISTENER); Workbench.getInstance().getActiveWorkbenchWindow().getShell() .removeDisposeListener(taskListSaveManager); } } catch (Exception e) { MylarStatusHandler.fail(e, "Mylar Java stop failed", false); } } @Override protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(MylarTaskListPrefConstants.AUTO_MANAGE_EDITORS, true); store.setDefault(MylarTaskListPrefConstants.SELECTED_PRIORITY, "P5"); store.setDefault(MylarTaskListPrefConstants.REPORT_OPEN_EDITOR, true); store.setDefault(MylarTaskListPrefConstants.REPORT_OPEN_INTERNAL, false); store.setDefault(MylarTaskListPrefConstants.REPORT_OPEN_EXTERNAL, false); store.setDefault(MylarTaskListPrefConstants.MULTIPLE_ACTIVE_TASKS, false); store.setDefault(MylarTaskListPrefConstants.SAVE_TASKLIST_MODE, TaskListSaveMode.THREE_HOURS.toString()); } public static TaskListManager getTaskListManager() { return taskListManager; } /** * Returns the shared instance. */ public static MylarTaskListPlugin getDefault() { return INSTANCE; } /** * Returns the string from the INSTANCE's resource bundle, or 'key' if not * found. */ public static String getResourceString(String key) { ResourceBundle bundle = MylarTaskListPlugin.getDefault().getResourceBundle(); try { return (bundle != null) ? bundle.getString(key) : key; } catch (MissingResourceException e) { return key; } } /** * Returns the INSTANCE's resource bundle, */ public ResourceBundle getResourceBundle() { try { if (resourceBundle == null) resourceBundle = ResourceBundle.getBundle("taskListPlugin.TaskListPluginPluginResources"); } catch (MissingResourceException x) { resourceBundle = null; } return resourceBundle; } public static IPreferenceStore getPrefs() { return MylarPlugin.getDefault().getPreferenceStore(); } // /** // * Sets the directory containing the task list file to use. // * Switches immediately to use the data at that location. // */ // public void setDataDirectory(String newDirPath) { // String taskListFilePath = newDirPath + File.separator + // DEFAULT_TASK_LIST_FILE; // getTaskListManager().setTaskListFile(new File(taskListFilePath)); // getTaskListManager().createNewTaskList(); // getTaskListManager().readTaskList(); // // if (TaskListView.getDefault() != null) // TaskListView.getDefault().clearTaskHistory(); // } private void checkTaskListBackup() { // if (getPrefs().contains(PREVIOUS_SAVE_DATE)) { // lastSave = new Date(getPrefs().getLong(PREVIOUS_SAVE_DATE)); // } else { // lastSave = new Date(); // getPrefs().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime()); // } Date currentTime = new Date(); if (currentTime.getTime() > lastBackup.getTime() + AUTOMATIC_BACKUP_SAVE_INTERVAL) {// TaskListSaveMode.fromStringToLong(getPrefs().getString(SAVE_TASKLIST_MODE))) // { MylarTaskListPlugin.getDefault().getTaskListSaveManager().createTaskListBackupFile(); lastBackup = new Date(); // INSTANCE.getPreferenceStore().setValue(PREVIOUS_SAVE_DATE, // lastSave.getTime()); } } private void checkReminders() { final TaskReportGenerator parser = new TaskReportGenerator(MylarTaskListPlugin.getTaskListManager() .getTaskList()); parser.addCollector(new ReminderRequiredCollector()); parser.collectTasks(); if (!parser.getAllCollectedTasks().isEmpty()) { Workbench.getInstance().getDisplay().asyncExec(new Runnable() { public void run() { TasksReminderDialog dialog = new TasksReminderDialog(Workbench.getInstance().getDisplay() .getActiveShell(), parser.getAllCollectedTasks()); dialog.setBlockOnOpen(false); dialog.open(); } }); } } public static void setPriorityLevel(PriorityLevel pl) { getPrefs().setValue(MylarTaskListPrefConstants.SELECTED_PRIORITY, pl.toString()); } public static String getPriorityLevel() { if (getPrefs().contains(MylarTaskListPrefConstants.SELECTED_PRIORITY)) { return getPrefs().getString(MylarTaskListPrefConstants.SELECTED_PRIORITY); } else { return PriorityLevel.P5.toString(); } } public void setFilterCompleteMode(boolean isFilterOn) { getPrefs().setValue(MylarTaskListPrefConstants.FILTER_COMPLETE_MODE, isFilterOn); } public boolean isFilterCompleteMode() { if (getPrefs().contains(MylarTaskListPrefConstants.FILTER_COMPLETE_MODE)) { return getPrefs().getBoolean(MylarTaskListPrefConstants.FILTER_COMPLETE_MODE); } else { return false; } } public void setFilterInCompleteMode(boolean isFilterOn) { getPrefs().setValue(MylarTaskListPrefConstants.FILTER_INCOMPLETE_MODE, isFilterOn); } public boolean isFilterInCompleteMode() { if (getPrefs().contains(MylarTaskListPrefConstants.FILTER_INCOMPLETE_MODE)) { return getPrefs().getBoolean(MylarTaskListPrefConstants.FILTER_INCOMPLETE_MODE); } else { return false; } } /** * TODO: remove */ public ReportOpenMode getReportMode() { return ReportOpenMode.EDITOR; // if (getPrefs().getBoolean(REPORT_OPEN_EDITOR)) { // return ReportOpenMode.EDITOR; // } else if (getPrefs().getBoolean(REPORT_OPEN_INTERNAL)) { // return ReportOpenMode.INTERNAL_BROWSER; // } else { // return ReportOpenMode.EXTERNAL_BROWSER; // } } // public TaskListWriter getTaskListExternalizer() { // return externalizer; // } public List<ITaskHandler> getTaskHandlers() { return taskHandlers; } public ITaskHandler getHandlerForElement(ITaskListElement element) { for (ITaskHandler taskHandler : taskHandlers) { if (taskHandler.acceptsItem(element)) return taskHandler; } return null; } public void addTaskHandler(ITaskHandler taskHandler) { taskHandlers.add(taskHandler); } private void restoreTaskHandlerState() { for (ITaskHandler handler : taskHandlers) { handler.restoreState(TaskListView.getDefault()); } } private List<IDynamicSubMenuContributor> menuContributors = new ArrayList<IDynamicSubMenuContributor>(); public List<IDynamicSubMenuContributor> getDynamicMenuContributers() { return menuContributors; } public void addDynamicPopupContributor(IDynamicSubMenuContributor contributor) { menuContributors.add(contributor); } public boolean isMultipleActiveTasksMode() { return getPrefs().getBoolean(MylarTaskListPrefConstants.MULTIPLE_ACTIVE_TASKS); } public String[] getSaveOptions() { String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() }; return options; } public ITaskHighlighter getHighlighter() { return highlighter; } public void setHighlighter(ITaskHighlighter highlighter) { this.highlighter = highlighter; } public List<IContextEditorFactory> getContextEditors() { return contextEditors; } public void addContextEditor(IContextEditorFactory contextEditor) { if (contextEditor != null) this.contextEditors.add(contextEditor); } public TaskListSaveManager getTaskListSaveManager() { return taskListSaveManager; } public boolean isShellActive() { return MylarTaskListPlugin.shellActive; } public static TaskRepositoryManager getRepositoryManager() { return taskRepositoryManager; } } // private List<ITaskActivationListener> taskListListeners = new // ArrayList<ITaskActivationListener>(); // // public List<ITaskActivationListener> getTaskListListeners() { // return taskListListeners; // } // // public void addTaskListListener(ITaskActivationListener taskListListner) { // taskListListeners.add(taskListListner); // }
false
true
private void migrateHandlesToRepositorySupport() { boolean migrated = false; if (!getPreferenceStore().getBoolean(MylarTaskListPrefConstants.CONTEXTS_MIGRATED)) { File dataDir = new File(MylarPlugin.getDefault().getDataDirectory()); TaskRepository defaultRepository = MylarTaskListPlugin.getRepositoryManager().getDefaultRepository( TaskRepositoryManager.PREFIX_REPOSITORY_OLD.toLowerCase()); if (defaultRepository != null) { String repositoryUrl = defaultRepository.getUrl().toExternalForm(); migrated = true; if (dataDir.exists() && dataDir.isDirectory()) { for (File file : dataDir.listFiles()) { String oldHandle = file.getName().substring(0, file.getName().lastIndexOf('.')); if (oldHandle.startsWith(TaskRepositoryManager.PREFIX_REPOSITORY_OLD)) { String id = TaskRepositoryManager.getTaskId(oldHandle); String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); File newFile = MylarPlugin.getContextManager().getFileForContext(newHandle); file.renameTo(newFile); } } } for (ITask task : taskListManager.getTaskList().getAllTasks()) { if (!task.isLocal()) { String id = TaskRepositoryManager.getTaskId(task.getHandleIdentifier()); String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); task.setHandleIdentifier(newHandle); // System.err.println(">>> task: " + task.getHandleIdentifier()); } } for (ITaskQuery query : taskListManager.getTaskList().getQueries()) { query.setRepositoryUrl(repositoryUrl); for (IQueryHit hit : query.getHits()) { // String id = TaskRepositoryManager.getTaskId(hit.getHandleIdentifier()); // String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); hit.setRepositoryUrl(repositoryUrl); // hit.setHandleIdentifier(newHandle); // System.err.println(">>> hit: " + hit.getHandleIdentifier()); } } } } if (migrated) { MylarStatusHandler.log("Migrated context files to repository-aware paths", this); getPreferenceStore().setValue(MylarTaskListPrefConstants.CONTEXTS_MIGRATED, false); // taskListManager.saveTaskList(); // taskListManager.readOrCreateTaskList(); // restoreTaskHandlerState(); } }
private void migrateHandlesToRepositorySupport() { boolean migrated = false; if (!getPreferenceStore().getBoolean(MylarTaskListPrefConstants.CONTEXTS_MIGRATED)) { File dataDir = new File(MylarPlugin.getDefault().getDataDirectory()); TaskRepository defaultRepository = MylarTaskListPlugin.getRepositoryManager().getDefaultRepository( TaskRepositoryManager.PREFIX_REPOSITORY_OLD.toLowerCase()); if (defaultRepository != null) { String repositoryUrl = defaultRepository.getUrl().toExternalForm(); migrated = true; if (dataDir.exists() && dataDir.isDirectory()) { for (File file : dataDir.listFiles()) { String oldHandle = file.getName().substring(0, file.getName().lastIndexOf('.')); if (oldHandle.startsWith(TaskRepositoryManager.PREFIX_REPOSITORY_OLD)) { String id = TaskRepositoryManager.getTaskId(oldHandle); String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); File newFile = MylarPlugin.getContextManager().getFileForContext(newHandle); file.renameTo(newFile); } } } for (ITask task : taskListManager.getTaskList().getAllTasks()) { if (!task.isLocal()) { String id = TaskRepositoryManager.getTaskId(task.getHandleIdentifier()); String newHandle = TaskRepositoryManager.getHandle(repositoryUrl, id); task.setHandleIdentifier(newHandle); } } for (ITaskQuery query : taskListManager.getTaskList().getQueries()) { query.setRepositoryUrl(repositoryUrl); for (IQueryHit hit : query.getHits()) { hit.setRepositoryUrl(repositoryUrl); } } } } if (migrated) { MylarStatusHandler.log("Migrated context files to repository-aware paths", this); getPreferenceStore().setValue(MylarTaskListPrefConstants.CONTEXTS_MIGRATED, true); } }
diff --git a/org.orbisgis.core-ui/src/main/java/org/orbisgis/editorViews/toc/actions/SetActive.java b/org.orbisgis.core-ui/src/main/java/org/orbisgis/editorViews/toc/actions/SetActive.java index 94a744e87..a03a53e1e 100644 --- a/org.orbisgis.core-ui/src/main/java/org/orbisgis/editorViews/toc/actions/SetActive.java +++ b/org.orbisgis.core-ui/src/main/java/org/orbisgis/editorViews/toc/actions/SetActive.java @@ -1,62 +1,63 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able * to manipulate and create vector and raster spatial information. OrbisGIS * is distributed under GPL 3 license. It is produced by the geo-informatic team of * the IRSTV Institute <http://www.irstv.cnrs.fr/>, CNRS FR 2488: * Erwan BOCHER, scientific researcher, * Thomas LEDUC, scientific researcher, * Fernando GONZALEZ CORTES, computer engineer. * * Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: * <http://orbisgis.cerma.archi.fr/> * <http://sourcesup.cru.fr/projects/orbisgis/> * * or contact directly: * erwan.bocher _at_ ec-nantes.fr * fergonco _at_ gmail.com * thomas.leduc _at_ cerma.archi.fr */ package org.orbisgis.editorViews.toc.actions; import org.gdms.driver.DriverException; import org.orbisgis.editorViews.toc.action.ILayerAction; import org.orbisgis.layerModel.ILayer; import org.orbisgis.layerModel.MapContext; public class SetActive implements ILayerAction { public boolean accepts(MapContext mc, ILayer layer) { try { - return (mc.getActiveLayer() != layer) && (layer.isVectorial()); + return (mc.getActiveLayer() != layer) && layer.isVectorial() + && layer.getDataSource().isEditable(); } catch (DriverException e) { return false; } } public boolean acceptsSelectionCount(int selectionCount) { return selectionCount == 1; } public void execute(MapContext mapContext, ILayer layer) { mapContext.setActiveLayer(layer); } }
true
true
public boolean accepts(MapContext mc, ILayer layer) { try { return (mc.getActiveLayer() != layer) && (layer.isVectorial()); } catch (DriverException e) { return false; } }
public boolean accepts(MapContext mc, ILayer layer) { try { return (mc.getActiveLayer() != layer) && layer.isVectorial() && layer.getDataSource().isEditable(); } catch (DriverException e) { return false; } }
diff --git a/src/jp/knct/di/c6t/ui/route/MyRoutesActivity.java b/src/jp/knct/di/c6t/ui/route/MyRoutesActivity.java index c371e2f..589c5ba 100644 --- a/src/jp/knct/di/c6t/ui/route/MyRoutesActivity.java +++ b/src/jp/knct/di/c6t/ui/route/MyRoutesActivity.java @@ -1,40 +1,40 @@ package jp.knct.di.c6t.ui.route; import java.util.List; import jp.knct.di.c6t.R; import jp.knct.di.c6t.communication.Client; import jp.knct.di.c6t.communication.DebugSharedPreferencesClient; import jp.knct.di.c6t.model.Route; import jp.knct.di.c6t.model.User; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ListView; public class MyRoutesActivity extends ListActivity { private List<Route> mRoutes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_routes); - Client client = new DebugSharedPreferencesClient(); + Client client = new DebugSharedPreferencesClient(this); - mRoutes = client.getRoutes(new User(0, "user", "tokyo")); // TODO + mRoutes = client.getRoutes(client.getMyUserData()); // TODO RoutesAdapter adapter = new RoutesAdapter(this, mRoutes); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Route targetRoute = mRoutes.get(position); Intent intent = new Intent(this, RouteActivity.class) .putExtra(IntentData.EXTRA_KEY_ROUTE, targetRoute); startActivity(intent); finish(); } }
false
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_routes); Client client = new DebugSharedPreferencesClient(); mRoutes = client.getRoutes(new User(0, "user", "tokyo")); // TODO RoutesAdapter adapter = new RoutesAdapter(this, mRoutes); setListAdapter(adapter); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_routes); Client client = new DebugSharedPreferencesClient(this); mRoutes = client.getRoutes(client.getMyUserData()); // TODO RoutesAdapter adapter = new RoutesAdapter(this, mRoutes); setListAdapter(adapter); }
diff --git a/Plugin/com/rusketh/creator/masks/MaskBuilder.java b/Plugin/com/rusketh/creator/masks/MaskBuilder.java index 7416da0..c0cfc0d 100644 --- a/Plugin/com/rusketh/creator/masks/MaskBuilder.java +++ b/Plugin/com/rusketh/creator/masks/MaskBuilder.java @@ -1,142 +1,142 @@ /* * Creator - Bukkit Plugin * Copyright (C) 2012 Rusketh & Oskar94 <www.Rusketh.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.rusketh.creator.masks; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.inventory.ItemStack; import com.rusketh.creator.Extensions.ItemExtension; import com.rusketh.creator.blocks.CreatorBlock; import com.rusketh.creator.blocks.CreatorItem; import com.rusketh.creator.exceptions.CmdException; import com.rusketh.creator.exceptions.WildDataException; public class MaskBuilder { public MaskBuilder(String string) { buffer = string; pos = 0; mask = nextMask(); } /*========================================================================================================*/ public Mask getMask() { return mask; } /*========================================================================================================*/ public Mask nextMask() { Mask mask; if ( pos >= buffer.length() ) throw new CmdException("%rInvalid mask - mask exspected."); switch( buffer.charAt( pos ) ) { case '(': int epos = pos; pos++; mask = nextMask(); if (buffer.charAt( pos ) != ')') throw new CmdException("%rInvalid mask - '%c)%r' expected to end '%c(%r' at char %c").append( epos ).append("%r."); break; case '!': pos++; mask = new NotMask( nextMask() ); break; - case '>': + case '<': pos++; mask = new UnderMask( nextMask() ); break; - case '<': + case '>': pos++; mask = new AboveMask( nextMask() ); break; case '&': case '|': //These can't be used here. - throw new CmdException("%rInvalid mask - unexpected '%c").append( buffer.charAt( pos ) ).append( "%r' at char %c").append( pos ).append("%r."); + throw new CmdException("%rInvalid mask - unexpected '%c&|%r' at char %c").append( pos ).append("%r."); default: mask = nextBlockMask(); } if ( pos >= buffer.length() ) return mask; //Now find the operators. switch( buffer.charAt( pos ) ) { case '&': pos++; mask = new AndMask( mask, nextMask() ); break; case '|': pos++; mask = new OrMask( mask, nextMask() ); break; } return mask; } /*========================================================================================================*/ public Mask nextBlockMask() { Matcher m = pattern.matcher( buffer.substring( pos ) ); if ( !m.matches( ) ) throw new CmdException("%rInvalid mask - '%c", buffer, "%r'."); BlockMask mask = new BlockMask(); for ( String string : m.group( ).split( "," ) ) { pos += 1 + string.length( ); try { ItemStack item = ItemExtension.stringToItemStack( string ); int type = item.getTypeId( ); byte data = item.getData( ).getData( ); if ( CreatorBlock.get( type ) == null ) throw new CmdException("%r'%c", CreatorItem.get( type ).niceName( data ), "%r' is not a placeable block." ); mask.add(type, data); } catch (WildDataException e) { if ( CreatorBlock.get( e.typeId ) == null ) throw new CmdException("%r'%c", CreatorItem.get( e.typeId ).name( ), "%r' is not a placeable block." ); for ( int data : CreatorItem.get( e.typeId ).dataValues( ).values( ) ) mask.add( e.typeId, (byte) data); } } pos--; return mask; } /*========================================================================================================*/ private int pos; private String buffer; private Mask mask; public final Pattern pattern = Pattern.compile( "(^[0-9a-zA-z:*,]+)" ); }
false
true
public Mask nextMask() { Mask mask; if ( pos >= buffer.length() ) throw new CmdException("%rInvalid mask - mask exspected."); switch( buffer.charAt( pos ) ) { case '(': int epos = pos; pos++; mask = nextMask(); if (buffer.charAt( pos ) != ')') throw new CmdException("%rInvalid mask - '%c)%r' expected to end '%c(%r' at char %c").append( epos ).append("%r."); break; case '!': pos++; mask = new NotMask( nextMask() ); break; case '>': pos++; mask = new UnderMask( nextMask() ); break; case '<': pos++; mask = new AboveMask( nextMask() ); break; case '&': case '|': //These can't be used here. throw new CmdException("%rInvalid mask - unexpected '%c").append( buffer.charAt( pos ) ).append( "%r' at char %c").append( pos ).append("%r."); default: mask = nextBlockMask(); } if ( pos >= buffer.length() ) return mask; //Now find the operators. switch( buffer.charAt( pos ) ) { case '&': pos++; mask = new AndMask( mask, nextMask() ); break; case '|': pos++; mask = new OrMask( mask, nextMask() ); break; } return mask; }
public Mask nextMask() { Mask mask; if ( pos >= buffer.length() ) throw new CmdException("%rInvalid mask - mask exspected."); switch( buffer.charAt( pos ) ) { case '(': int epos = pos; pos++; mask = nextMask(); if (buffer.charAt( pos ) != ')') throw new CmdException("%rInvalid mask - '%c)%r' expected to end '%c(%r' at char %c").append( epos ).append("%r."); break; case '!': pos++; mask = new NotMask( nextMask() ); break; case '<': pos++; mask = new UnderMask( nextMask() ); break; case '>': pos++; mask = new AboveMask( nextMask() ); break; case '&': case '|': //These can't be used here. throw new CmdException("%rInvalid mask - unexpected '%c&|%r' at char %c").append( pos ).append("%r."); default: mask = nextBlockMask(); } if ( pos >= buffer.length() ) return mask; //Now find the operators. switch( buffer.charAt( pos ) ) { case '&': pos++; mask = new AndMask( mask, nextMask() ); break; case '|': pos++; mask = new OrMask( mask, nextMask() ); break; } return mask; }
diff --git a/src/test/java/nl/mineleni/cbsviewer/servlet/wms/WMSClientServletIntegrationTest.java b/src/test/java/nl/mineleni/cbsviewer/servlet/wms/WMSClientServletIntegrationTest.java index b2fe5b450..7e652a3fb 100644 --- a/src/test/java/nl/mineleni/cbsviewer/servlet/wms/WMSClientServletIntegrationTest.java +++ b/src/test/java/nl/mineleni/cbsviewer/servlet/wms/WMSClientServletIntegrationTest.java @@ -1,188 +1,191 @@ /* * Copyright (c) 2012-2013, Dienst Landelijk Gebied - Ministerie van Economische Zaken * * Gepubliceerd onder de BSD 2-clause licentie, * zie https://github.com/MinELenI/CBSviewer/blob/master/LICENSE.md voor de volledige licentie. */ package nl.mineleni.cbsviewer.servlet.wms; import static nl.mineleni.cbsviewer.servlet.AbstractBaseServlet.USER_ID; import static nl.mineleni.cbsviewer.servlet.AbstractBaseServlet.USER_PASSWORD; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_BGMAP; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_FGMAP_ALPHA; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_MAPID; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_STRAAL; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_XCOORD; import static nl.mineleni.cbsviewer.util.StringConstants.REQ_PARAM_YCOORD; import static org.junit.Assume.assumeNoException; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nl.mineleni.cbsviewer.util.StringConstants; import org.jmock.Expectations; import org.jmock.integration.junit4.JUnitRuleMockery; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Test case for {@link nl.mineleni.cbsviewer.servlet.wms.WMSClientServlet}. dit * is een online/ integratie test omdat er met live sevices wordt * gecommuniceerd. * * @author mprins */ public class WMSClientServletIntegrationTest { /** servlet die we testen. */ private WMSClientServlet servlet; /** junit mockery. */ private final JUnitRuleMockery mockery = new JUnitRuleMockery(); /** mocked servlet request. */ private HttpServletRequest request; /** ge-mockte servlet config gebruikt in de test. */ private ServletConfig servletConfig; /** ge-mockte servlet context gebruikt in de test. */ private ServletContext servletContext; /** ge-mockte servlet response gebruikt in de test. */ private HttpServletResponse response; /** * Set up before each test. * * @throws Exception * the exception */ @SuppressWarnings("serial") @Before public void setUp() throws Exception { this.request = this.mockery.mock(HttpServletRequest.class); this.servletConfig = this.mockery.mock(ServletConfig.class); this.servletContext = this.mockery.mock(ServletContext.class); this.response = this.mockery.mock(HttpServletResponse.class); this.servlet = new WMSClientServlet() { /** return de mocked servletContext. */ @Override public ServletContext getServletContext() { return WMSClientServletIntegrationTest.this.servletContext; } /** return de mocked servletConfig. */ @Override public ServletConfig getServletConfig() { return WMSClientServletIntegrationTest.this.servletConfig; } }; this.mockery.checking(new Expectations() { { this.atLeast(1) .of(WMSClientServletIntegrationTest.this.servletContext) .getRealPath(StringConstants.MAP_CACHE_DIR.code); this.will(returnValue("C:/workspace/CBSviewer/target/" + StringConstants.MAP_CACHE_DIR.code)); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter(USER_ID); this.will(returnValue("userID")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter(USER_PASSWORD); this.will(returnValue("passID")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("bgCapabilitiesURL"); this.will(returnValue("http://osm.wheregroup.com/cgi-bin/osm_basic.xml?REQUEST=GetCapabilities&SERVICE=WMS&amp;VERSION=1.1.1")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("bgWMSlayers"); this.will(returnValue("Grenzen")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("lufoCapabilitiesURL"); this.will(returnValue("http://gisdemo2.agro.nl/arcgis/services/Luchtfoto2010/MapServer/WMSServer?REQUEST=GetCapabilities&SERVICE=WMS")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("lufoWMSlayers"); this.will(returnValue("")); + this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) + .getInitParameter("featureInfoType"); + this.will(returnValue("")); } }); // init servlet this.servlet.init(this.servletConfig); } /** * Tear down after each test. * * @throws Exception * the exception */ @After public void tearDown() throws Exception { this.servlet.destroy(); } /** * Test methode voor * {@link nl.mineleni.cbsviewer.servlet.wms.WMSClientServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)} * . * * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Test // @Ignore("needs more work") public void testServiceHttpServletRequestHttpServletResponse() { this.mockery.checking(new Expectations() { { this.allowing(WMSClientServletIntegrationTest.this.request) .getAttributeNames(); this.allowing(WMSClientServletIntegrationTest.this.request) .getParameterMap(); this.allowing(WMSClientServletIntegrationTest.this.request) .getParameter(REQ_PARAM_XCOORD.code); this.will(returnValue("143542")); this.allowing(WMSClientServletIntegrationTest.this.request) .getParameter(REQ_PARAM_YCOORD.code); this.will(returnValue("453977")); this.allowing(WMSClientServletIntegrationTest.this.request) .getParameter(REQ_PARAM_STRAAL.code); this.will(returnValue("3000")); this.allowing(WMSClientServletIntegrationTest.this.request) .getParameter(REQ_PARAM_BGMAP.code); this.will(returnValue("topografie")); this.allowing(WMSClientServletIntegrationTest.this.request) .getParameter(REQ_PARAM_FGMAP_ALPHA.code); this.will(returnValue(".7")); this.allowing(WMSClientServletIntegrationTest.this.request) .getParameter(REQ_PARAM_MAPID.code); this.will(returnValue("wijkenbuurten2011_thema_gemeenten2011_aantal_inwoners")); this.allowing(WMSClientServletIntegrationTest.this.request) .setAttribute(this.with(any(String.class)), this.with(any(Object.class))); } }); try { this.servlet.service(this.request, this.response); } catch (final ServletException | IOException e) { assumeNoException(e); } // cant't do this // assertNotNull(this.request.getAttribute(REQ_PARAM_MAPID.code)); // assertNotNull(this.request.getAttribute(REQ_PARAM_LEGENDAS.code)); // assertNotNull(this.request.getAttribute(REQ_PARAM_FEATUREINFO.code)); // assertNotNull(this.request.getAttribute(REQ_PARAM_DOWNLOADLINK.code)); } }
true
true
public void setUp() throws Exception { this.request = this.mockery.mock(HttpServletRequest.class); this.servletConfig = this.mockery.mock(ServletConfig.class); this.servletContext = this.mockery.mock(ServletContext.class); this.response = this.mockery.mock(HttpServletResponse.class); this.servlet = new WMSClientServlet() { /** return de mocked servletContext. */ @Override public ServletContext getServletContext() { return WMSClientServletIntegrationTest.this.servletContext; } /** return de mocked servletConfig. */ @Override public ServletConfig getServletConfig() { return WMSClientServletIntegrationTest.this.servletConfig; } }; this.mockery.checking(new Expectations() { { this.atLeast(1) .of(WMSClientServletIntegrationTest.this.servletContext) .getRealPath(StringConstants.MAP_CACHE_DIR.code); this.will(returnValue("C:/workspace/CBSviewer/target/" + StringConstants.MAP_CACHE_DIR.code)); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter(USER_ID); this.will(returnValue("userID")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter(USER_PASSWORD); this.will(returnValue("passID")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("bgCapabilitiesURL"); this.will(returnValue("http://osm.wheregroup.com/cgi-bin/osm_basic.xml?REQUEST=GetCapabilities&SERVICE=WMS&amp;VERSION=1.1.1")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("bgWMSlayers"); this.will(returnValue("Grenzen")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("lufoCapabilitiesURL"); this.will(returnValue("http://gisdemo2.agro.nl/arcgis/services/Luchtfoto2010/MapServer/WMSServer?REQUEST=GetCapabilities&SERVICE=WMS")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("lufoWMSlayers"); this.will(returnValue("")); } }); // init servlet this.servlet.init(this.servletConfig); }
public void setUp() throws Exception { this.request = this.mockery.mock(HttpServletRequest.class); this.servletConfig = this.mockery.mock(ServletConfig.class); this.servletContext = this.mockery.mock(ServletContext.class); this.response = this.mockery.mock(HttpServletResponse.class); this.servlet = new WMSClientServlet() { /** return de mocked servletContext. */ @Override public ServletContext getServletContext() { return WMSClientServletIntegrationTest.this.servletContext; } /** return de mocked servletConfig. */ @Override public ServletConfig getServletConfig() { return WMSClientServletIntegrationTest.this.servletConfig; } }; this.mockery.checking(new Expectations() { { this.atLeast(1) .of(WMSClientServletIntegrationTest.this.servletContext) .getRealPath(StringConstants.MAP_CACHE_DIR.code); this.will(returnValue("C:/workspace/CBSviewer/target/" + StringConstants.MAP_CACHE_DIR.code)); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter(USER_ID); this.will(returnValue("userID")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter(USER_PASSWORD); this.will(returnValue("passID")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("bgCapabilitiesURL"); this.will(returnValue("http://osm.wheregroup.com/cgi-bin/osm_basic.xml?REQUEST=GetCapabilities&SERVICE=WMS&amp;VERSION=1.1.1")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("bgWMSlayers"); this.will(returnValue("Grenzen")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("lufoCapabilitiesURL"); this.will(returnValue("http://gisdemo2.agro.nl/arcgis/services/Luchtfoto2010/MapServer/WMSServer?REQUEST=GetCapabilities&SERVICE=WMS")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("lufoWMSlayers"); this.will(returnValue("")); this.oneOf(WMSClientServletIntegrationTest.this.servletConfig) .getInitParameter("featureInfoType"); this.will(returnValue("")); } }); // init servlet this.servlet.init(this.servletConfig); }
diff --git a/src/com/mohammadag/xposedvinedownloader/VineDownloader.java b/src/com/mohammadag/xposedvinedownloader/VineDownloader.java index 4830510..4bc0d38 100644 --- a/src/com/mohammadag/xposedvinedownloader/VineDownloader.java +++ b/src/com/mohammadag/xposedvinedownloader/VineDownloader.java @@ -1,152 +1,152 @@ package com.mohammadag.xposedvinedownloader; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findClass; import static de.robv.android.xposed.XposedHelpers.findConstructorExact; import static de.robv.android.xposed.XposedHelpers.getObjectField; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import android.app.DownloadManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.util.SparseArray; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public class VineDownloader implements IXposedHookLoadPackage { private long mPostId; private Context mContext; private static int VINE_DOWNLOADER_RESULT = 99; private static int VINE_POST_ID_ERROR = -91; private static int VINE_ACTIVITY_RESULT = 999; public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals("co.vine.android")) return; Class<?> optionClass = findClass("co.vine.android.PostOptionsDialogActivity$Option", lpparam.classLoader); final Constructor<?> optionConsturctor = findConstructorExact(optionClass, int.class, String.class); final Class<?> postOptionsDialogActivityClass = findClass("co.vine.android.PostOptionsDialogActivity", lpparam.classLoader); Class<?> optionArrayAdapterClass = findClass("co.vine.android.PostOptionsDialogActivity$OptionArrayAdapter", lpparam.classLoader); XposedBridge.hookAllConstructors(optionArrayAdapterClass, new XC_MethodHook() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { mContext = (Context) param.args[0]; ArrayAdapter<?> array = (ArrayAdapter<?>) param.thisObject; ArrayList localArrayList = new ArrayList(); localArrayList.add(optionConsturctor.newInstance(VINE_DOWNLOADER_RESULT, "Download")); array.addAll(localArrayList); } }); findAndHookMethod("co.vine.android.PostOptionsDialogActivity", lpparam.classLoader, "onDialogDone", DialogInterface.class, int.class, int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { XposedBridge.log("onDialogDone " + String.valueOf(param.args[1]) + " " + String.valueOf(param.args[2])); } }); findAndHookMethod("co.vine.android.BaseTimelineFragment", lpparam.classLoader, "onActivityResult", int.class, int.class, Intent.class, new XC_MethodHook() { @SuppressWarnings("rawtypes") @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (((Integer) param.args[1]).equals(VINE_ACTIVITY_RESULT)) { Intent paramIntent = (Intent) param.args[2]; if (paramIntent != null) { long postId = paramIntent.getLongExtra("post_id", VINE_POST_ID_ERROR); if (postId != VINE_POST_ID_ERROR) { Object feedAdapter = getObjectField(param.thisObject, "mFeedAdapter"); SparseArray vinePostArray = (SparseArray) getObjectField(feedAdapter, "mPosts"); Object vinePost = null; if (vinePostArray != null) { int key = 0; for(int i = 0; i < vinePostArray.size(); i++) { key = vinePostArray.keyAt(i); Object obj = vinePostArray.get(key); long localPostId = XposedHelpers.getLongField(obj, "postId"); if (localPostId == postId) { vinePost = obj; break; } } if (vinePost != null) { String videoUrl = (String) getObjectField(vinePost, "videoUrl"); if (videoUrl != null && videoUrl.isEmpty()) { videoUrl = (String) getObjectField(vinePost, "videoLowURL"); } if (!videoUrl.isEmpty()) { Toast.makeText(mContext, "Downloading video", Toast.LENGTH_SHORT).show(); String description = (String) getObjectField(vinePost, "description"); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoUrl)); request.setDescription(description); request.setTitle("Vine Video"); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Vine/" + description + ".mp4"); DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); } } } } } param.setResult(false); } } }); findAndHookMethod(postOptionsDialogActivityClass, "onListItemClick", ListView.class, View.class, int.class, long.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { View paramView = (View) param.args[1]; int tag = ((Integer)paramView.getTag()).intValue(); if (tag == VINE_DOWNLOADER_RESULT) { - mPostId = (Long) getObjectField(param.thisObject, "mPostId"); + mPostId = (Long) getObjectField(param.thisObject, "mPostId"); Intent localIntent = new Intent(); localIntent.putExtra("post_id", mPostId); Method setResultMethod = postOptionsDialogActivityClass.getMethod("setResult", int.class, Intent.class); setResultMethod.invoke(param.thisObject, VINE_ACTIVITY_RESULT, localIntent); Method finishMethod = postOptionsDialogActivityClass.getMethod("finish"); finishMethod.invoke(param.thisObject); - param.setResult(false); + param.setResult(false); } } }); } }
false
true
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals("co.vine.android")) return; Class<?> optionClass = findClass("co.vine.android.PostOptionsDialogActivity$Option", lpparam.classLoader); final Constructor<?> optionConsturctor = findConstructorExact(optionClass, int.class, String.class); final Class<?> postOptionsDialogActivityClass = findClass("co.vine.android.PostOptionsDialogActivity", lpparam.classLoader); Class<?> optionArrayAdapterClass = findClass("co.vine.android.PostOptionsDialogActivity$OptionArrayAdapter", lpparam.classLoader); XposedBridge.hookAllConstructors(optionArrayAdapterClass, new XC_MethodHook() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { mContext = (Context) param.args[0]; ArrayAdapter<?> array = (ArrayAdapter<?>) param.thisObject; ArrayList localArrayList = new ArrayList(); localArrayList.add(optionConsturctor.newInstance(VINE_DOWNLOADER_RESULT, "Download")); array.addAll(localArrayList); } }); findAndHookMethod("co.vine.android.PostOptionsDialogActivity", lpparam.classLoader, "onDialogDone", DialogInterface.class, int.class, int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { XposedBridge.log("onDialogDone " + String.valueOf(param.args[1]) + " " + String.valueOf(param.args[2])); } }); findAndHookMethod("co.vine.android.BaseTimelineFragment", lpparam.classLoader, "onActivityResult", int.class, int.class, Intent.class, new XC_MethodHook() { @SuppressWarnings("rawtypes") @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (((Integer) param.args[1]).equals(VINE_ACTIVITY_RESULT)) { Intent paramIntent = (Intent) param.args[2]; if (paramIntent != null) { long postId = paramIntent.getLongExtra("post_id", VINE_POST_ID_ERROR); if (postId != VINE_POST_ID_ERROR) { Object feedAdapter = getObjectField(param.thisObject, "mFeedAdapter"); SparseArray vinePostArray = (SparseArray) getObjectField(feedAdapter, "mPosts"); Object vinePost = null; if (vinePostArray != null) { int key = 0; for(int i = 0; i < vinePostArray.size(); i++) { key = vinePostArray.keyAt(i); Object obj = vinePostArray.get(key); long localPostId = XposedHelpers.getLongField(obj, "postId"); if (localPostId == postId) { vinePost = obj; break; } } if (vinePost != null) { String videoUrl = (String) getObjectField(vinePost, "videoUrl"); if (videoUrl != null && videoUrl.isEmpty()) { videoUrl = (String) getObjectField(vinePost, "videoLowURL"); } if (!videoUrl.isEmpty()) { Toast.makeText(mContext, "Downloading video", Toast.LENGTH_SHORT).show(); String description = (String) getObjectField(vinePost, "description"); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoUrl)); request.setDescription(description); request.setTitle("Vine Video"); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Vine/" + description + ".mp4"); DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); } } } } } param.setResult(false); } } }); findAndHookMethod(postOptionsDialogActivityClass, "onListItemClick", ListView.class, View.class, int.class, long.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { View paramView = (View) param.args[1]; int tag = ((Integer)paramView.getTag()).intValue(); if (tag == VINE_DOWNLOADER_RESULT) { mPostId = (Long) getObjectField(param.thisObject, "mPostId"); Intent localIntent = new Intent(); localIntent.putExtra("post_id", mPostId); Method setResultMethod = postOptionsDialogActivityClass.getMethod("setResult", int.class, Intent.class); setResultMethod.invoke(param.thisObject, VINE_ACTIVITY_RESULT, localIntent); Method finishMethod = postOptionsDialogActivityClass.getMethod("finish"); finishMethod.invoke(param.thisObject); param.setResult(false); } } }); }
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals("co.vine.android")) return; Class<?> optionClass = findClass("co.vine.android.PostOptionsDialogActivity$Option", lpparam.classLoader); final Constructor<?> optionConsturctor = findConstructorExact(optionClass, int.class, String.class); final Class<?> postOptionsDialogActivityClass = findClass("co.vine.android.PostOptionsDialogActivity", lpparam.classLoader); Class<?> optionArrayAdapterClass = findClass("co.vine.android.PostOptionsDialogActivity$OptionArrayAdapter", lpparam.classLoader); XposedBridge.hookAllConstructors(optionArrayAdapterClass, new XC_MethodHook() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { mContext = (Context) param.args[0]; ArrayAdapter<?> array = (ArrayAdapter<?>) param.thisObject; ArrayList localArrayList = new ArrayList(); localArrayList.add(optionConsturctor.newInstance(VINE_DOWNLOADER_RESULT, "Download")); array.addAll(localArrayList); } }); findAndHookMethod("co.vine.android.PostOptionsDialogActivity", lpparam.classLoader, "onDialogDone", DialogInterface.class, int.class, int.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { XposedBridge.log("onDialogDone " + String.valueOf(param.args[1]) + " " + String.valueOf(param.args[2])); } }); findAndHookMethod("co.vine.android.BaseTimelineFragment", lpparam.classLoader, "onActivityResult", int.class, int.class, Intent.class, new XC_MethodHook() { @SuppressWarnings("rawtypes") @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (((Integer) param.args[1]).equals(VINE_ACTIVITY_RESULT)) { Intent paramIntent = (Intent) param.args[2]; if (paramIntent != null) { long postId = paramIntent.getLongExtra("post_id", VINE_POST_ID_ERROR); if (postId != VINE_POST_ID_ERROR) { Object feedAdapter = getObjectField(param.thisObject, "mFeedAdapter"); SparseArray vinePostArray = (SparseArray) getObjectField(feedAdapter, "mPosts"); Object vinePost = null; if (vinePostArray != null) { int key = 0; for(int i = 0; i < vinePostArray.size(); i++) { key = vinePostArray.keyAt(i); Object obj = vinePostArray.get(key); long localPostId = XposedHelpers.getLongField(obj, "postId"); if (localPostId == postId) { vinePost = obj; break; } } if (vinePost != null) { String videoUrl = (String) getObjectField(vinePost, "videoUrl"); if (videoUrl != null && videoUrl.isEmpty()) { videoUrl = (String) getObjectField(vinePost, "videoLowURL"); } if (!videoUrl.isEmpty()) { Toast.makeText(mContext, "Downloading video", Toast.LENGTH_SHORT).show(); String description = (String) getObjectField(vinePost, "description"); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoUrl)); request.setDescription(description); request.setTitle("Vine Video"); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Vine/" + description + ".mp4"); DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); manager.enqueue(request); } } } } } param.setResult(false); } } }); findAndHookMethod(postOptionsDialogActivityClass, "onListItemClick", ListView.class, View.class, int.class, long.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { View paramView = (View) param.args[1]; int tag = ((Integer)paramView.getTag()).intValue(); if (tag == VINE_DOWNLOADER_RESULT) { mPostId = (Long) getObjectField(param.thisObject, "mPostId"); Intent localIntent = new Intent(); localIntent.putExtra("post_id", mPostId); Method setResultMethod = postOptionsDialogActivityClass.getMethod("setResult", int.class, Intent.class); setResultMethod.invoke(param.thisObject, VINE_ACTIVITY_RESULT, localIntent); Method finishMethod = postOptionsDialogActivityClass.getMethod("finish"); finishMethod.invoke(param.thisObject); param.setResult(false); } } }); }
diff --git a/modules/core/src/main/java/org/apache/sandesha2/workers/SenderWorker.java b/modules/core/src/main/java/org/apache/sandesha2/workers/SenderWorker.java index 86a0b460..e335939a 100644 --- a/modules/core/src/main/java/org/apache/sandesha2/workers/SenderWorker.java +++ b/modules/core/src/main/java/org/apache/sandesha2/workers/SenderWorker.java @@ -1,765 +1,765 @@ /* * 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.sandesha2.workers; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import org.apache.axiom.om.impl.builder.StAXBuilder; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.addressing.AddressingConstants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.OperationContext; import org.apache.axis2.context.OperationContextFactory; import org.apache.axis2.context.ServiceContext; import org.apache.axis2.description.AxisOperation; import org.apache.axis2.description.OutOnlyAxisOperation; import org.apache.axis2.engine.AxisEngine; import org.apache.axis2.engine.Handler.InvocationResponse; import org.apache.axis2.transport.RequestResponseTransport; import org.apache.axis2.transport.TransportUtils; import org.apache.axis2.transport.RequestResponseTransport.RequestResponseTransportStatus; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.sandesha2.RMMsgContext; import org.apache.sandesha2.Sandesha2Constants; import org.apache.sandesha2.SandeshaException; import org.apache.sandesha2.i18n.SandeshaMessageHelper; import org.apache.sandesha2.i18n.SandeshaMessageKeys; import org.apache.sandesha2.storage.SandeshaStorageException; import org.apache.sandesha2.storage.StorageManager; import org.apache.sandesha2.storage.Transaction; import org.apache.sandesha2.storage.beanmanagers.SenderBeanMgr; import org.apache.sandesha2.storage.beans.RMDBean; import org.apache.sandesha2.storage.beans.RMSBean; import org.apache.sandesha2.storage.beans.SenderBean; import org.apache.sandesha2.util.AcknowledgementManager; import org.apache.sandesha2.util.MessageRetransmissionAdjuster; import org.apache.sandesha2.util.MsgInitializer; import org.apache.sandesha2.util.RMMsgCreator; import org.apache.sandesha2.util.SandeshaUtil; import org.apache.sandesha2.util.SpecSpecificConstants; import org.apache.sandesha2.util.TerminateManager; import org.apache.sandesha2.wsrm.AckRequested; import org.apache.sandesha2.wsrm.CloseSequence; import org.apache.sandesha2.wsrm.Identifier; import org.apache.sandesha2.wsrm.LastMessage; import org.apache.sandesha2.wsrm.MessageNumber; import org.apache.sandesha2.wsrm.Sequence; import org.apache.sandesha2.wsrm.TerminateSequence; public class SenderWorker extends SandeshaWorker implements Runnable { private static final Log log = LogFactory.getLog(SenderWorker.class); private ConfigurationContext configurationContext = null; private SenderBean senderBean = null; private RMMsgContext messageToSend = null; private String rmVersion = null; public SenderWorker (ConfigurationContext configurationContext, SenderBean senderBean, String rmVersion) { this.configurationContext = configurationContext; this.senderBean = senderBean; this.rmVersion = rmVersion; } public void setMessage(RMMsgContext msg) { this.messageToSend = msg; } public void run () { if (log.isDebugEnabled()) log.debug("Enter: SenderWorker::run"); // If we are not the holder of the correct lock, then we have to stop if(lock != null && !lock.ownsLock(workId, this)) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, another worker holds the lock"); return; } Transaction transaction = null; try { StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(configurationContext, configurationContext.getAxisConfiguration()); SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr(); transaction = storageManager.getTransaction(); String key = senderBean.getMessageContextRefKey(); MessageContext msgCtx = null; RMMsgContext rmMsgCtx = null; if(messageToSend != null) { msgCtx = messageToSend.getMessageContext(); rmMsgCtx = messageToSend; } else { msgCtx = storageManager.retrieveMessageContext(key, configurationContext); if (msgCtx == null) { // This sender bean has already been processed if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; return; } rmMsgCtx = MsgInitializer.initializeMessage(msgCtx); } // sender will not send the message if following property is // set and not true. // But it will set if it is not set (null) // This is used to make sure that the mesage get passed the // Sandesha2TransportSender. String qualifiedForSending = (String) msgCtx.getProperty(Sandesha2Constants.QUALIFIED_FOR_SENDING); if (qualifiedForSending != null && !qualifiedForSending.equals(Sandesha2Constants.VALUE_TRUE)) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, !qualified for sending"); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } if (msgCtx == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.sendHasUnavailableMsgEntry)); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } // operation is the lowest level Sandesha2 should be attached ArrayList msgsNotToSend = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation()).getMsgTypesToDrop(); if (msgsNotToSend != null && msgsNotToSend.contains(new Integer(rmMsgCtx.getMessageType()))) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, message type to be dropped " + rmMsgCtx.getMessageType()); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } // If we are sending to the anonymous URI then we _must_ have a transport waiting, // or the message can't go anywhere. If there is nothing here then we leave the // message in the sender queue, and a MakeConnection (or a retransmitted request) // will hopefully pick it up soon. Boolean makeConnection = (Boolean) msgCtx.getProperty(Sandesha2Constants.MAKE_CONNECTION_RESPONSE); EndpointReference toEPR = msgCtx.getTo(); MessageContext inMsg = null; OperationContext op = msgCtx.getOperationContext(); RequestResponseTransport t = (RequestResponseTransport) msgCtx.getProperty(RequestResponseTransport.TRANSPORT_CONTROL); if (t==null) { if (op != null) inMsg = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMsg != null) t = (RequestResponseTransport) inMsg.getProperty(RequestResponseTransport.TRANSPORT_CONTROL); } // If we are anonymous, and this is not a makeConnection, then we must have a transport waiting if((toEPR==null || toEPR.hasAnonymousAddress()) && (makeConnection == null || !makeConnection.booleanValue()) && - (t == null && !t.getStatus().equals(RequestResponseTransportStatus.WAITING))) { + (t == null || !t.getStatus().equals(RequestResponseTransportStatus.WAITING))) { // Mark this sender bean so that we know that the transport is unavailable, if the // bean is still stored. SenderBean bean = senderBeanMgr.retrieve(senderBean.getMessageID()); if(bean != null && bean.isTransportAvailable()) { bean.setTransportAvailable(false); senderBeanMgr.update(bean); } // Commit the update if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, no response transport for anonymous message"); return; } int messageType = senderBean.getMessageType(); if (isAckPiggybackableMsgType(messageType)) { // Commit the update if(transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); // Piggyback ack messages based on the 'To' address of the message AcknowledgementManager.piggybackAcksIfPresent(rmMsgCtx, storageManager); } if (transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); if (transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); senderBean = updateMessage(rmMsgCtx,senderBean,storageManager); if (senderBean == null) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, !continueSending"); if(transaction != null && transaction.isActive()) { transaction.rollback(); transaction = null; } return; } // Although not actually sent yet, update the send count to indicate an attempt if (senderBean.isReSend()) { senderBeanMgr.update(senderBean); } // sending the message boolean successfullySent = false; //try to redecorate the EPR if necessary if (log.isDebugEnabled()) log.debug("Redecorate EPR : " + msgCtx.getEnvelope().getHeader()); EndpointReference replyToEPR = msgCtx.getReplyTo(); if(replyToEPR!=null){ replyToEPR = SandeshaUtil.getEPRDecorator(msgCtx.getConfigurationContext()).decorateEndpointReference(replyToEPR); msgCtx.setReplyTo(replyToEPR); } // have to commit the transaction before sending. This may // get changed when WS-AT is available. if(transaction != null) { transaction.commit(); transaction = null; } msgCtx.getOptions().setTimeOutInMilliSeconds(1000000); boolean processResponseForFaults = false ; try { InvocationResponse response = InvocationResponse.CONTINUE; if(storageManager.requiresMessageSerialization()) { if(msgCtx.isPaused()) { if (log.isDebugEnabled()) log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setPaused(false); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); response = AxisEngine.resumeSend(msgCtx); } else { if (log.isDebugEnabled()) log.debug("Sending a message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); AxisEngine.send(msgCtx); // TODO check if this should return an invocation response } } else { ArrayList retransmittablePhases = (ArrayList) msgCtx.getProperty(Sandesha2Constants.RETRANSMITTABLE_PHASES); if (retransmittablePhases!=null) { msgCtx.setExecutionChain(retransmittablePhases); } else { ArrayList emptyExecutionChain = new ArrayList (); msgCtx.setExecutionChain(emptyExecutionChain); } msgCtx.setCurrentHandlerIndex(0); msgCtx.setCurrentPhaseIndex(0); msgCtx.setPaused(false); if (log.isDebugEnabled()) log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); response = AxisEngine.resumeSend(msgCtx); } if(log.isDebugEnabled()) log.debug("Engine resume returned " + response); if(response != InvocationResponse.SUSPEND) { if(t != null) { if(log.isDebugEnabled()) log.debug("Signalling transport in " + t); t.signalResponseReady(); } } successfullySent = true; } catch (AxisFault e) { //this is a possible SOAP 1.2 Fault. So letting it proceed. processResponseForFaults = true; recordError(e, rmMsgCtx, storageManager); } catch (Exception e) { String message = SandeshaMessageHelper.getMessage( SandeshaMessageKeys.sendMsgError, e.toString()); if (log.isDebugEnabled()) log.debug(message, e); recordError(e, rmMsgCtx, storageManager); } // Establish the transaction for post-send processing transaction = storageManager.getTransaction(); // update or delete only if the object is still present. SenderBean bean1 = senderBeanMgr .retrieve(senderBean.getMessageID()); if (bean1 != null) { if (senderBean.isReSend()) { bean1.setTimeToSend(senderBean.getTimeToSend()); senderBeanMgr.update(bean1); } else { senderBeanMgr.delete(bean1.getMessageID()); // removing the message from the storage. String messageStoredKey = bean1.getMessageContextRefKey(); storageManager.removeMessageContext(messageStoredKey); } } // Commit the transaction to release the SenderBean if (transaction!=null) transaction.commit(); transaction = null; if ((processResponseForFaults || successfullySent) && !msgCtx.isServerSide()) checkForSyncResponses(msgCtx); if ((rmMsgCtx.getMessageType() == Sandesha2Constants.MessageTypes.TERMINATE_SEQ) && (Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmMsgCtx.getRMNamespaceValue()))) { try { transaction = storageManager.getTransaction(); //terminate message sent using the SandeshaClient. Since the terminate message will simply get the //InFlow of the reference message get called which could be zero sized (OutOnly operations). // terminate sending side if this is the WSRM 1.0 spec. // If the WSRM versoion is 1.1 termination will happen in the terminate sequence response message. TerminateSequence terminateSequence = rmMsgCtx.getTerminateSequence(); String sequenceID = terminateSequence.getIdentifier().getIdentifier(); RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sequenceID); TerminateManager.terminateSendingSide(rmsBean, storageManager, false); if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; } finally { if(transaction != null && transaction.isActive()) { transaction.rollback(); transaction = null; } } } } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Caught exception", e); } finally { if (lock!=null && workId!=null) { lock.removeWork(workId); } if (transaction!=null && transaction.isActive()) { try { transaction.rollback(); } catch (SandeshaStorageException e) { if (log.isWarnEnabled()) log.warn("Caught exception rolling back transaction", e); } } } if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run"); } /** * Update the message before sending it. We adjust the retransmission intervals and send counts * for the message. If the message is an application message then we ensure that we have added * the Sequence header. */ private SenderBean updateMessage(RMMsgContext rmMsgContext, SenderBean senderBean, StorageManager storageManager) throws AxisFault { // Lock the message to enable retransmission update senderBean = storageManager.getSenderBeanMgr().retrieve(senderBean.getMessageID()); // Only continue if we find a SenderBean if (senderBean == null) return senderBean; int messageType = senderBean.getMessageType(); boolean continueSending = MessageRetransmissionAdjuster.adjustRetransmittion( rmMsgContext, senderBean, rmMsgContext.getConfigurationContext(), storageManager); if(!continueSending) return null; Identifier id = null; if(messageType == Sandesha2Constants.MessageTypes.APPLICATION || messageType == Sandesha2Constants.MessageTypes.LAST_MESSAGE) { String namespace = SpecSpecificConstants.getRMNamespaceValue(rmVersion); Sequence sequence = rmMsgContext.getSequence(); if(sequence == null) { sequence = new Sequence(namespace); MessageNumber msgNumber = new MessageNumber(namespace); msgNumber.setMessageNumber(senderBean.getMessageNumber()); sequence.setMessageNumber(msgNumber); if(senderBean.isLastMessage() && SpecSpecificConstants.isLastMessageIndicatorRequired(rmVersion)) { sequence.setLastMessage(new LastMessage(namespace)); } // We just create the id here, we will add the value in later id = new Identifier(namespace); sequence.setIdentifier(id); rmMsgContext.setSequence(sequence); } } else if(messageType == Sandesha2Constants.MessageTypes.TERMINATE_SEQ) { TerminateSequence terminate = rmMsgContext.getTerminateSequence(); id = terminate.getIdentifier(); } else if(messageType == Sandesha2Constants.MessageTypes.CLOSE_SEQUENCE) { CloseSequence close = rmMsgContext.getCloseSequence(); id = close.getIdentifier(); } else if(messageType == Sandesha2Constants.MessageTypes.ACK_REQUEST) { // The only time that we can have a message of this type is when we are sending a // stand-alone ack request, and in that case we only expect to find a single ack // request header in the message. Iterator ackRequests = rmMsgContext.getAckRequests(); AckRequested ackRequest = (AckRequested) ackRequests.next(); if (ackRequests.hasNext()) { throw new SandeshaException (SandeshaMessageHelper.getMessage(SandeshaMessageKeys.ackRequestMultipleParts)); } id = ackRequest.getIdentifier(); } // TODO consider adding an extra ack request, as we are about to send the message and we // know which sequence it is associated with. //if this is an sync WSRM 1.0 case we always have to add an ack boolean ackPresent = false; Iterator it = rmMsgContext.getSequenceAcknowledgements(); if (it.hasNext()) ackPresent = true; if (!ackPresent && rmMsgContext.getMessageContext().isServerSide() && (messageType==Sandesha2Constants.MessageTypes.APPLICATION || messageType==Sandesha2Constants.MessageTypes.APPLICATION || messageType==Sandesha2Constants.MessageTypes.UNKNOWN || messageType==Sandesha2Constants.MessageTypes.LAST_MESSAGE)) { String inboundSequenceId = senderBean.getInboundSequenceId(); if (inboundSequenceId==null) throw new SandeshaException ("InboundSequenceID is not set for the sequence:" + id); RMDBean incomingSequenceBean = SandeshaUtil.getRMDBeanFromSequenceId(storageManager, inboundSequenceId); if (incomingSequenceBean!=null) RMMsgCreator.addAckMessage(rmMsgContext, inboundSequenceId, incomingSequenceBean, false); } if(id != null && !senderBean.getSequenceID().equals(id.getIdentifier())) { id.setIndentifer(senderBean.getSequenceID()); // Write the changes back into the message context rmMsgContext.addSOAPEnvelope(); } else if(rmMsgContext.getProperty(RMMsgCreator.ACK_TO_BE_WRITTEN) != null){ rmMsgContext.addSOAPEnvelope(); } return senderBean; } private boolean isAckPiggybackableMsgType(int messageType) { if (log.isDebugEnabled()) log.debug("Enter: SenderWorker::isAckPiggybackableMsgType, " + messageType); boolean piggybackable = true; if (messageType == Sandesha2Constants.MessageTypes.ACK) piggybackable = false; if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::isAckPiggybackableMsgType, " + piggybackable); return piggybackable; } private void checkForSyncResponses(MessageContext msgCtx) { if (log.isDebugEnabled()) log.debug("Enter: SenderWorker::checkForSyncResponses, " + msgCtx.getEnvelope().getHeader()); try { // create the responseMessageContext MessageContext responseMessageContext = msgCtx.getOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); SOAPEnvelope resenvelope = null; if (responseMessageContext!=null) resenvelope = responseMessageContext.getEnvelope(); boolean transportInPresent = (msgCtx.getProperty(MessageContext.TRANSPORT_IN) != null); if (!transportInPresent && (responseMessageContext==null || responseMessageContext.getEnvelope()==null)) { if(log.isDebugEnabled()) log.debug("Exit: SenderWorker::checkForSyncResponses, no response present"); return; } //to find out weather the response was built by me. boolean syncResponseBuilt = false; if (responseMessageContext==null || responseMessageContext.getEnvelope()==null) { if (responseMessageContext==null) responseMessageContext = new MessageContext(); OperationContext requestMsgOpCtx = msgCtx.getOperationContext(); //copy any necessary properties SandeshaUtil.copyConfiguredProperties(msgCtx, responseMessageContext); // If the request operation context is Out-In then it's reasonable to assume // that the response is related to the request. //int mep = requestMsgOpCtx.getAxisOperation().getAxisSpecificMEPConstant(); //if(mep == WSDLConstants.MEP_CONSTANT_OUT_IN) { //this line causes issues in addressing //responseMessageContext.setOperationContext(requestMsgOpCtx); //} responseMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, requestMsgOpCtx .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING)); responseMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, requestMsgOpCtx .getProperty(Constants.Configuration.CONTENT_TYPE)); responseMessageContext.setProperty(HTTPConstants.MTOM_RECEIVED_CONTENT_TYPE, requestMsgOpCtx .getProperty(HTTPConstants.MTOM_RECEIVED_CONTENT_TYPE)); //If the response MsgCtx was not available Axis2 would hv put the transport info into a //HashMap, getting the data from it. HashMap transportInfoMap = (HashMap) msgCtx.getProperty(Constants.Configuration.TRANSPORT_INFO_MAP); if (transportInfoMap != null) { responseMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, transportInfoMap.get(Constants.Configuration.CONTENT_TYPE)); responseMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, transportInfoMap.get(Constants.Configuration.CHARACTER_SET_ENCODING)); } responseMessageContext.setConfigurationContext(msgCtx.getConfigurationContext()); responseMessageContext.setTransportIn(msgCtx.getTransportIn()); responseMessageContext.setTransportOut(msgCtx.getTransportOut()); responseMessageContext.setProperty(MessageContext.TRANSPORT_IN, msgCtx .getProperty(MessageContext.TRANSPORT_IN)); responseMessageContext.setServiceGroupContext(msgCtx.getServiceGroupContext()); responseMessageContext.setProperty(Sandesha2Constants.MessageContextProperties.MAKECONNECTION_ENTRY, msgCtx.getProperty(Sandesha2Constants.MessageContextProperties.MAKECONNECTION_ENTRY)); // If request is REST we assume the responseMessageContext is REST, // so set the variable responseMessageContext.setDoingREST(msgCtx.isDoingREST()); resenvelope = responseMessageContext.getEnvelope(); try { // MessageContext is modified in TransportUtils.createSOAPMessage(). It might be used by axis.engine or handler. // To catch the modification and pass it to engine or handler, resenvelope is created by responseMessageContext. if (resenvelope==null) { //We try to build the response out of the transport stream. resenvelope = TransportUtils.createSOAPMessage(responseMessageContext); responseMessageContext.setEnvelope(resenvelope); syncResponseBuilt = true; } } catch (AxisFault e) { //Cannot find a valid SOAP envelope. if (log.isDebugEnabled() ) { log.debug (SandeshaMessageHelper .getMessage(SandeshaMessageKeys.soapEnvNotSet)); log.debug ("Caught exception", e); } return; } //we will not be setting the operation context here since this msgs may not be an application reply. //we let other dispatchers find it. int messageType = MsgInitializer.initializeMessage(msgCtx).getMessageType(); RMMsgContext responseRMMessage = MsgInitializer.initializeMessage(responseMessageContext); int responseMessageType = responseRMMessage.getMessageType(); if(log.isDebugEnabled()) log.debug("inboundMsgType" + responseMessageType + "outgoing message type " + messageType); if (responseMessageType != Sandesha2Constants.MessageTypes.APPLICATION ) { if(log.isDebugEnabled()) log.debug("setting service ctx on msg as this is NOT an application response"); responseMessageContext.setServiceContext(msgCtx.getServiceContext()); } else{ //we cannot set service ctx for application response msgs since the srvc ctx will not match the op ctx, causing //problems with addressing if(log.isDebugEnabled()) log.debug("NOT setting service ctx for response type " + messageType + ", current srvc ctx =" + responseMessageContext.getServiceContext()); } //If addressing is disabled we will be adding this message simply as the application response of the request message. Boolean addressingDisabled = (Boolean) msgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES); if (addressingDisabled!=null && Boolean.TRUE.equals(addressingDisabled)) { // If the AxisOperation object doesn't have a message receiver, it means that this was // an out only op where we have added an ACK to the response. Set the requestMsgOpCtx to // be the RMIn OperationContext responseMsgOpCtx = requestMsgOpCtx; if (requestMsgOpCtx.getAxisOperation().getMessageReceiver() == null) { // Generate a new RM In Only operation ServiceContext serviceCtx = responseMessageContext.getServiceContext(); AxisOperation op = msgCtx.getAxisService().getOperation(Sandesha2Constants.RM_IN_ONLY_OPERATION); responseMsgOpCtx = OperationContextFactory.createOperationContext (op.getAxisSpecificMEPConstant(), op, serviceCtx); } responseMessageContext.setOperationContext(responseMsgOpCtx); } AxisOperation operation = msgCtx.getAxisOperation(); if (operation!=null && responseMessageContext.getAxisMessage()==null && !(operation instanceof OutOnlyAxisOperation)) responseMessageContext.setAxisMessage(operation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE)); if (responseRMMessage.getMessageType()==Sandesha2Constants.MessageTypes.ACK) { responseMessageContext.setAxisOperation(SpecSpecificConstants.getWSRMOperation (Sandesha2Constants.MessageTypes.ACK, responseRMMessage.getRMSpecVersion(), responseMessageContext.getAxisService())); responseMessageContext.setOperationContext(null); } } //if the syncResponseWas not built here and the client was not expecting a sync response. We will not try to execute //here. Doing so will cause a double invocation for a async message. if (msgCtx.getOptions().isUseSeparateListener()==true && !syncResponseBuilt) { return; } //setting the message as serverSide will let it go through the MessageReceiver (may be callback MR). responseMessageContext.setServerSide(true); if (responseMessageContext.getSoapAction()==null) { //if there is no SOAP action in the response message, Axis2 will wrongly identify it as a REST message //This happens because we set serverSide to True in a previous step. //So we have to add a empty SOAPAction here. responseMessageContext.setSoapAction(""); } InvocationResponse response = null; if (resenvelope!=null) { response = AxisEngine.receive(responseMessageContext); } if(!InvocationResponse.SUSPEND.equals(response)) { // Performance work - need to close the XMLStreamReader to prevent GC thrashing. SOAPEnvelope env = responseMessageContext.getEnvelope(); if(env!=null){ StAXBuilder sb = (StAXBuilder)responseMessageContext.getEnvelope().getBuilder(); if(sb!=null){ sb.close(); } } } } catch (Exception e) { String message = SandeshaMessageHelper.getMessage(SandeshaMessageKeys.noValidSyncResponse); if (log.isDebugEnabled()) log.debug(message, e); } if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::checkForSyncResponses"); } private void recordError (Exception e, RMMsgContext outRMMsg, StorageManager storageManager) throws SandeshaStorageException { // Store the Exception as a sequence property to enable the client to lookup the last // exception time and timestamp. Transaction transaction = null; try { // Get the internal sequence id from the context String internalSequenceId = (String)outRMMsg.getProperty(Sandesha2Constants.MessageContextProperties.INTERNAL_SEQUENCE_ID); if(internalSequenceId == null) internalSequenceId = senderBean.getInternalSequenceID(); if(internalSequenceId != null) { // Create a new Transaction transaction = storageManager.getTransaction(); RMSBean bean = SandeshaUtil.getRMSBeanFromInternalSequenceId(storageManager, internalSequenceId); if (bean != null) { bean.setLastSendError(e); bean.setLastSendErrorTimestamp(System.currentTimeMillis()); // Update the RMSBean storageManager.getRMSBeanMgr().update(bean); } // Commit the properties if(transaction != null) { transaction.commit(); transaction = null; } } } catch (Exception e1) { if (log.isErrorEnabled()) log.error(e1); } finally { if (transaction != null) { transaction.rollback(); transaction = null; } } } }
true
true
public void run () { if (log.isDebugEnabled()) log.debug("Enter: SenderWorker::run"); // If we are not the holder of the correct lock, then we have to stop if(lock != null && !lock.ownsLock(workId, this)) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, another worker holds the lock"); return; } Transaction transaction = null; try { StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(configurationContext, configurationContext.getAxisConfiguration()); SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr(); transaction = storageManager.getTransaction(); String key = senderBean.getMessageContextRefKey(); MessageContext msgCtx = null; RMMsgContext rmMsgCtx = null; if(messageToSend != null) { msgCtx = messageToSend.getMessageContext(); rmMsgCtx = messageToSend; } else { msgCtx = storageManager.retrieveMessageContext(key, configurationContext); if (msgCtx == null) { // This sender bean has already been processed if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; return; } rmMsgCtx = MsgInitializer.initializeMessage(msgCtx); } // sender will not send the message if following property is // set and not true. // But it will set if it is not set (null) // This is used to make sure that the mesage get passed the // Sandesha2TransportSender. String qualifiedForSending = (String) msgCtx.getProperty(Sandesha2Constants.QUALIFIED_FOR_SENDING); if (qualifiedForSending != null && !qualifiedForSending.equals(Sandesha2Constants.VALUE_TRUE)) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, !qualified for sending"); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } if (msgCtx == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.sendHasUnavailableMsgEntry)); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } // operation is the lowest level Sandesha2 should be attached ArrayList msgsNotToSend = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation()).getMsgTypesToDrop(); if (msgsNotToSend != null && msgsNotToSend.contains(new Integer(rmMsgCtx.getMessageType()))) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, message type to be dropped " + rmMsgCtx.getMessageType()); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } // If we are sending to the anonymous URI then we _must_ have a transport waiting, // or the message can't go anywhere. If there is nothing here then we leave the // message in the sender queue, and a MakeConnection (or a retransmitted request) // will hopefully pick it up soon. Boolean makeConnection = (Boolean) msgCtx.getProperty(Sandesha2Constants.MAKE_CONNECTION_RESPONSE); EndpointReference toEPR = msgCtx.getTo(); MessageContext inMsg = null; OperationContext op = msgCtx.getOperationContext(); RequestResponseTransport t = (RequestResponseTransport) msgCtx.getProperty(RequestResponseTransport.TRANSPORT_CONTROL); if (t==null) { if (op != null) inMsg = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMsg != null) t = (RequestResponseTransport) inMsg.getProperty(RequestResponseTransport.TRANSPORT_CONTROL); } // If we are anonymous, and this is not a makeConnection, then we must have a transport waiting if((toEPR==null || toEPR.hasAnonymousAddress()) && (makeConnection == null || !makeConnection.booleanValue()) && (t == null && !t.getStatus().equals(RequestResponseTransportStatus.WAITING))) { // Mark this sender bean so that we know that the transport is unavailable, if the // bean is still stored. SenderBean bean = senderBeanMgr.retrieve(senderBean.getMessageID()); if(bean != null && bean.isTransportAvailable()) { bean.setTransportAvailable(false); senderBeanMgr.update(bean); } // Commit the update if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, no response transport for anonymous message"); return; } int messageType = senderBean.getMessageType(); if (isAckPiggybackableMsgType(messageType)) { // Commit the update if(transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); // Piggyback ack messages based on the 'To' address of the message AcknowledgementManager.piggybackAcksIfPresent(rmMsgCtx, storageManager); } if (transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); if (transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); senderBean = updateMessage(rmMsgCtx,senderBean,storageManager); if (senderBean == null) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, !continueSending"); if(transaction != null && transaction.isActive()) { transaction.rollback(); transaction = null; } return; } // Although not actually sent yet, update the send count to indicate an attempt if (senderBean.isReSend()) { senderBeanMgr.update(senderBean); } // sending the message boolean successfullySent = false; //try to redecorate the EPR if necessary if (log.isDebugEnabled()) log.debug("Redecorate EPR : " + msgCtx.getEnvelope().getHeader()); EndpointReference replyToEPR = msgCtx.getReplyTo(); if(replyToEPR!=null){ replyToEPR = SandeshaUtil.getEPRDecorator(msgCtx.getConfigurationContext()).decorateEndpointReference(replyToEPR); msgCtx.setReplyTo(replyToEPR); } // have to commit the transaction before sending. This may // get changed when WS-AT is available. if(transaction != null) { transaction.commit(); transaction = null; } msgCtx.getOptions().setTimeOutInMilliSeconds(1000000); boolean processResponseForFaults = false ; try { InvocationResponse response = InvocationResponse.CONTINUE; if(storageManager.requiresMessageSerialization()) { if(msgCtx.isPaused()) { if (log.isDebugEnabled()) log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setPaused(false); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); response = AxisEngine.resumeSend(msgCtx); } else { if (log.isDebugEnabled()) log.debug("Sending a message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); AxisEngine.send(msgCtx); // TODO check if this should return an invocation response } } else { ArrayList retransmittablePhases = (ArrayList) msgCtx.getProperty(Sandesha2Constants.RETRANSMITTABLE_PHASES); if (retransmittablePhases!=null) { msgCtx.setExecutionChain(retransmittablePhases); } else { ArrayList emptyExecutionChain = new ArrayList (); msgCtx.setExecutionChain(emptyExecutionChain); } msgCtx.setCurrentHandlerIndex(0); msgCtx.setCurrentPhaseIndex(0); msgCtx.setPaused(false); if (log.isDebugEnabled()) log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); response = AxisEngine.resumeSend(msgCtx); } if(log.isDebugEnabled()) log.debug("Engine resume returned " + response); if(response != InvocationResponse.SUSPEND) { if(t != null) { if(log.isDebugEnabled()) log.debug("Signalling transport in " + t); t.signalResponseReady(); } } successfullySent = true; } catch (AxisFault e) { //this is a possible SOAP 1.2 Fault. So letting it proceed. processResponseForFaults = true; recordError(e, rmMsgCtx, storageManager); } catch (Exception e) { String message = SandeshaMessageHelper.getMessage( SandeshaMessageKeys.sendMsgError, e.toString()); if (log.isDebugEnabled()) log.debug(message, e); recordError(e, rmMsgCtx, storageManager); } // Establish the transaction for post-send processing transaction = storageManager.getTransaction(); // update or delete only if the object is still present. SenderBean bean1 = senderBeanMgr .retrieve(senderBean.getMessageID()); if (bean1 != null) { if (senderBean.isReSend()) { bean1.setTimeToSend(senderBean.getTimeToSend()); senderBeanMgr.update(bean1); } else { senderBeanMgr.delete(bean1.getMessageID()); // removing the message from the storage. String messageStoredKey = bean1.getMessageContextRefKey(); storageManager.removeMessageContext(messageStoredKey); } } // Commit the transaction to release the SenderBean if (transaction!=null) transaction.commit(); transaction = null; if ((processResponseForFaults || successfullySent) && !msgCtx.isServerSide()) checkForSyncResponses(msgCtx); if ((rmMsgCtx.getMessageType() == Sandesha2Constants.MessageTypes.TERMINATE_SEQ) && (Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmMsgCtx.getRMNamespaceValue()))) { try { transaction = storageManager.getTransaction(); //terminate message sent using the SandeshaClient. Since the terminate message will simply get the //InFlow of the reference message get called which could be zero sized (OutOnly operations). // terminate sending side if this is the WSRM 1.0 spec. // If the WSRM versoion is 1.1 termination will happen in the terminate sequence response message. TerminateSequence terminateSequence = rmMsgCtx.getTerminateSequence(); String sequenceID = terminateSequence.getIdentifier().getIdentifier(); RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sequenceID); TerminateManager.terminateSendingSide(rmsBean, storageManager, false); if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; } finally { if(transaction != null && transaction.isActive()) { transaction.rollback(); transaction = null; } } } } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Caught exception", e); } finally { if (lock!=null && workId!=null) { lock.removeWork(workId); } if (transaction!=null && transaction.isActive()) { try { transaction.rollback(); } catch (SandeshaStorageException e) { if (log.isWarnEnabled()) log.warn("Caught exception rolling back transaction", e); } } } if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run"); }
public void run () { if (log.isDebugEnabled()) log.debug("Enter: SenderWorker::run"); // If we are not the holder of the correct lock, then we have to stop if(lock != null && !lock.ownsLock(workId, this)) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, another worker holds the lock"); return; } Transaction transaction = null; try { StorageManager storageManager = SandeshaUtil.getSandeshaStorageManager(configurationContext, configurationContext.getAxisConfiguration()); SenderBeanMgr senderBeanMgr = storageManager.getSenderBeanMgr(); transaction = storageManager.getTransaction(); String key = senderBean.getMessageContextRefKey(); MessageContext msgCtx = null; RMMsgContext rmMsgCtx = null; if(messageToSend != null) { msgCtx = messageToSend.getMessageContext(); rmMsgCtx = messageToSend; } else { msgCtx = storageManager.retrieveMessageContext(key, configurationContext); if (msgCtx == null) { // This sender bean has already been processed if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; return; } rmMsgCtx = MsgInitializer.initializeMessage(msgCtx); } // sender will not send the message if following property is // set and not true. // But it will set if it is not set (null) // This is used to make sure that the mesage get passed the // Sandesha2TransportSender. String qualifiedForSending = (String) msgCtx.getProperty(Sandesha2Constants.QUALIFIED_FOR_SENDING); if (qualifiedForSending != null && !qualifiedForSending.equals(Sandesha2Constants.VALUE_TRUE)) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, !qualified for sending"); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } if (msgCtx == null) { if (log.isDebugEnabled()) log.debug(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.sendHasUnavailableMsgEntry)); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } // operation is the lowest level Sandesha2 should be attached ArrayList msgsNotToSend = SandeshaUtil.getPropertyBean(msgCtx.getAxisOperation()).getMsgTypesToDrop(); if (msgsNotToSend != null && msgsNotToSend.contains(new Integer(rmMsgCtx.getMessageType()))) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, message type to be dropped " + rmMsgCtx.getMessageType()); if(transaction != null && transaction.isActive()) { transaction.commit(); transaction = null; } return; } // If we are sending to the anonymous URI then we _must_ have a transport waiting, // or the message can't go anywhere. If there is nothing here then we leave the // message in the sender queue, and a MakeConnection (or a retransmitted request) // will hopefully pick it up soon. Boolean makeConnection = (Boolean) msgCtx.getProperty(Sandesha2Constants.MAKE_CONNECTION_RESPONSE); EndpointReference toEPR = msgCtx.getTo(); MessageContext inMsg = null; OperationContext op = msgCtx.getOperationContext(); RequestResponseTransport t = (RequestResponseTransport) msgCtx.getProperty(RequestResponseTransport.TRANSPORT_CONTROL); if (t==null) { if (op != null) inMsg = op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMsg != null) t = (RequestResponseTransport) inMsg.getProperty(RequestResponseTransport.TRANSPORT_CONTROL); } // If we are anonymous, and this is not a makeConnection, then we must have a transport waiting if((toEPR==null || toEPR.hasAnonymousAddress()) && (makeConnection == null || !makeConnection.booleanValue()) && (t == null || !t.getStatus().equals(RequestResponseTransportStatus.WAITING))) { // Mark this sender bean so that we know that the transport is unavailable, if the // bean is still stored. SenderBean bean = senderBeanMgr.retrieve(senderBean.getMessageID()); if(bean != null && bean.isTransportAvailable()) { bean.setTransportAvailable(false); senderBeanMgr.update(bean); } // Commit the update if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, no response transport for anonymous message"); return; } int messageType = senderBean.getMessageType(); if (isAckPiggybackableMsgType(messageType)) { // Commit the update if(transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); // Piggyback ack messages based on the 'To' address of the message AcknowledgementManager.piggybackAcksIfPresent(rmMsgCtx, storageManager); } if (transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); if (transaction != null && transaction.isActive()) transaction.commit(); transaction = storageManager.getTransaction(); senderBean = updateMessage(rmMsgCtx,senderBean,storageManager); if (senderBean == null) { if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run, !continueSending"); if(transaction != null && transaction.isActive()) { transaction.rollback(); transaction = null; } return; } // Although not actually sent yet, update the send count to indicate an attempt if (senderBean.isReSend()) { senderBeanMgr.update(senderBean); } // sending the message boolean successfullySent = false; //try to redecorate the EPR if necessary if (log.isDebugEnabled()) log.debug("Redecorate EPR : " + msgCtx.getEnvelope().getHeader()); EndpointReference replyToEPR = msgCtx.getReplyTo(); if(replyToEPR!=null){ replyToEPR = SandeshaUtil.getEPRDecorator(msgCtx.getConfigurationContext()).decorateEndpointReference(replyToEPR); msgCtx.setReplyTo(replyToEPR); } // have to commit the transaction before sending. This may // get changed when WS-AT is available. if(transaction != null) { transaction.commit(); transaction = null; } msgCtx.getOptions().setTimeOutInMilliSeconds(1000000); boolean processResponseForFaults = false ; try { InvocationResponse response = InvocationResponse.CONTINUE; if(storageManager.requiresMessageSerialization()) { if(msgCtx.isPaused()) { if (log.isDebugEnabled()) log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setPaused(false); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); response = AxisEngine.resumeSend(msgCtx); } else { if (log.isDebugEnabled()) log.debug("Sending a message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); AxisEngine.send(msgCtx); // TODO check if this should return an invocation response } } else { ArrayList retransmittablePhases = (ArrayList) msgCtx.getProperty(Sandesha2Constants.RETRANSMITTABLE_PHASES); if (retransmittablePhases!=null) { msgCtx.setExecutionChain(retransmittablePhases); } else { ArrayList emptyExecutionChain = new ArrayList (); msgCtx.setExecutionChain(emptyExecutionChain); } msgCtx.setCurrentHandlerIndex(0); msgCtx.setCurrentPhaseIndex(0); msgCtx.setPaused(false); if (log.isDebugEnabled()) log.debug("Resuming a send for message : " + msgCtx.getEnvelope().getHeader()); msgCtx.setProperty(MessageContext.TRANSPORT_NON_BLOCKING, Boolean.FALSE); response = AxisEngine.resumeSend(msgCtx); } if(log.isDebugEnabled()) log.debug("Engine resume returned " + response); if(response != InvocationResponse.SUSPEND) { if(t != null) { if(log.isDebugEnabled()) log.debug("Signalling transport in " + t); t.signalResponseReady(); } } successfullySent = true; } catch (AxisFault e) { //this is a possible SOAP 1.2 Fault. So letting it proceed. processResponseForFaults = true; recordError(e, rmMsgCtx, storageManager); } catch (Exception e) { String message = SandeshaMessageHelper.getMessage( SandeshaMessageKeys.sendMsgError, e.toString()); if (log.isDebugEnabled()) log.debug(message, e); recordError(e, rmMsgCtx, storageManager); } // Establish the transaction for post-send processing transaction = storageManager.getTransaction(); // update or delete only if the object is still present. SenderBean bean1 = senderBeanMgr .retrieve(senderBean.getMessageID()); if (bean1 != null) { if (senderBean.isReSend()) { bean1.setTimeToSend(senderBean.getTimeToSend()); senderBeanMgr.update(bean1); } else { senderBeanMgr.delete(bean1.getMessageID()); // removing the message from the storage. String messageStoredKey = bean1.getMessageContextRefKey(); storageManager.removeMessageContext(messageStoredKey); } } // Commit the transaction to release the SenderBean if (transaction!=null) transaction.commit(); transaction = null; if ((processResponseForFaults || successfullySent) && !msgCtx.isServerSide()) checkForSyncResponses(msgCtx); if ((rmMsgCtx.getMessageType() == Sandesha2Constants.MessageTypes.TERMINATE_SEQ) && (Sandesha2Constants.SPEC_2005_02.NS_URI.equals(rmMsgCtx.getRMNamespaceValue()))) { try { transaction = storageManager.getTransaction(); //terminate message sent using the SandeshaClient. Since the terminate message will simply get the //InFlow of the reference message get called which could be zero sized (OutOnly operations). // terminate sending side if this is the WSRM 1.0 spec. // If the WSRM versoion is 1.1 termination will happen in the terminate sequence response message. TerminateSequence terminateSequence = rmMsgCtx.getTerminateSequence(); String sequenceID = terminateSequence.getIdentifier().getIdentifier(); RMSBean rmsBean = SandeshaUtil.getRMSBeanFromSequenceId(storageManager, sequenceID); TerminateManager.terminateSendingSide(rmsBean, storageManager, false); if(transaction != null && transaction.isActive()) transaction.commit(); transaction = null; } finally { if(transaction != null && transaction.isActive()) { transaction.rollback(); transaction = null; } } } } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Caught exception", e); } finally { if (lock!=null && workId!=null) { lock.removeWork(workId); } if (transaction!=null && transaction.isActive()) { try { transaction.rollback(); } catch (SandeshaStorageException e) { if (log.isWarnEnabled()) log.warn("Caught exception rolling back transaction", e); } } } if (log.isDebugEnabled()) log.debug("Exit: SenderWorker::run"); }
diff --git a/TanitaScaleBlackBoxTest/src/main/java/ca/charland/tanita/PhysicRatingTest.java b/TanitaScaleBlackBoxTest/src/main/java/ca/charland/tanita/PhysicRatingTest.java index 047bbee..2114d17 100644 --- a/TanitaScaleBlackBoxTest/src/main/java/ca/charland/tanita/PhysicRatingTest.java +++ b/TanitaScaleBlackBoxTest/src/main/java/ca/charland/tanita/PhysicRatingTest.java @@ -1,44 +1,44 @@ package ca.charland.tanita; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import ca.charland.tanita.base.activity.manage.BaseAllPeopleListActivity; import com.jayway.android.robotium.solo.Solo; public class PhysicRatingTest extends ActivityInstrumentationTestCase2<PhysicRatingActivity>{ private Solo solo; public PhysicRatingTest() { super("ca.charland.tanita", PhysicRatingActivity.class); Intent i = new Intent(); i.putExtra(BaseAllPeopleListActivity.PERSON_ID, 5); setActivityIntent(i); } @Override public void setUp() throws Exception { //setUp() is run before a test case is started. //This is where the solo object is created. solo = new Solo(getInstrumentation(), getActivity()); } @Override public void tearDown() throws Exception { //tearDown() is run after a test case has finished. //finishOpenedActivities() will finish all the activities that have been opened during the test execution. solo.finishOpenedActivities(); } public void testGoingToNextScreen() throws Exception { solo.sleep(5000); solo.assertCurrentActivity("Expected the physic rating activity", "PhysicRatingActivity"); solo.enterText(0, "5"); solo.clickOnButton("Next"); solo.sleep(5000); - solo.assertCurrentActivity("Expected Add a new Person activity", "AddANewPersonActivity"); + solo.assertCurrentActivity("Expected Add a new Person activity", "FirstActivity"); } }
true
true
public void testGoingToNextScreen() throws Exception { solo.sleep(5000); solo.assertCurrentActivity("Expected the physic rating activity", "PhysicRatingActivity"); solo.enterText(0, "5"); solo.clickOnButton("Next"); solo.sleep(5000); solo.assertCurrentActivity("Expected Add a new Person activity", "AddANewPersonActivity"); }
public void testGoingToNextScreen() throws Exception { solo.sleep(5000); solo.assertCurrentActivity("Expected the physic rating activity", "PhysicRatingActivity"); solo.enterText(0, "5"); solo.clickOnButton("Next"); solo.sleep(5000); solo.assertCurrentActivity("Expected Add a new Person activity", "FirstActivity"); }
diff --git a/src/me/rotzloch/Classes/Reward.java b/src/me/rotzloch/Classes/Reward.java index 70f9769..335589c 100644 --- a/src/me/rotzloch/Classes/Reward.java +++ b/src/me/rotzloch/Classes/Reward.java @@ -1,103 +1,102 @@ package me.rotzloch.Classes; import java.util.Calendar; import org.bukkit.Location; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.inventory.ItemStack; public class Reward { private String _rewardString; private Location _rewardTPLocation; private int _rewardTimeLock; public Reward(SignChangeEvent ev, Player player) { if(ev.getLine(0).equalsIgnoreCase("[Reward]")) { if(!player.hasPermission("marocraft.reward.create")) { Helper.SendMessageNoPermission(ev.getPlayer()); ev.setCancelled(true); return; } if(ev.getLine(1).equals("") || ev.getLine(2).equals("") || ev.getLine(3).equals("")) { this.Help(ev.getPlayer()); ev.setCancelled(true); return; } String[] locArray = ev.getLine(3).split(" "); Double x = Double.parseDouble(locArray[0]); Double y = Double.parseDouble(locArray[1]); Double z = Double.parseDouble(locArray[2]); if(x == null || y == null || z == null) { this.Help(player); ev.setCancelled(true); return; } this._rewardString = ev.getLine(1); this._rewardTPLocation = new Location(player.getWorld(),x,y,z); this._rewardTimeLock = Integer.parseInt(ev.getLine(2)); } else { - ev.setCancelled(true); return; } } public Reward(Sign sign, Player player) { this._rewardString = sign.getLine(1); Double x = Double.parseDouble(sign.getLine(3).split(" ")[0]); Double y = Double.parseDouble(sign.getLine(3).split(" ")[1]); Double z = Double.parseDouble(sign.getLine(3).split(" ")[2]); this._rewardTPLocation = new Location(player.getWorld(),x,y,z); this._rewardTimeLock = Integer.parseInt(sign.getLine(2)); } public void Help(Player player) { player.sendMessage("�4Korrekte Anwendung:"); player.sendMessage("�d[Reward]"); player.sendMessage("�dItemId-Amount"); player.sendMessage("�dZeit in Sekunden"); player.sendMessage("�dx y z"); } public void GetReward(Player player) { RewardLock lock = Helper.RewardLocks(this.ID(), player.getName()); if(lock != null) { Helper.SendMessageError(player,"Diese Belohnung ist f�r dich noch gesperrt"); return; } if(player != null && this._rewardString != null && this._rewardTimeLock != -1) { String[] rewards = this._rewardString.split("-"); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, this._rewardTimeLock); RewardLock rewardLock = new RewardLock(player, calendar.getTimeInMillis(),this.ID()); if(rewards[1].equalsIgnoreCase("Maros")) { Helper.PayToTarget(null, player.getName(), Double.parseDouble(rewards[0])); player.teleport(this._rewardTPLocation); } else { String item = rewards[0]; String amount = rewards[1]; ItemStack stack = new ItemStack(Integer.parseInt(item)); stack.setAmount(Integer.parseInt(amount)); player.getInventory().addItem(stack); player.teleport(this._rewardTPLocation); } Helper.AddRewardLock(rewardLock); } else { Helper.SendMessageError(player, "Fehler"); } } public String ID() { String id = ""; id += "[REWARD]#"; id += this._rewardString + "#"; id += this._rewardTimeLock + "#"; id += this._rewardTPLocation.getX() + "-"+this._rewardTPLocation.getY() + "-"+ this._rewardTPLocation.getZ(); return id; } }
true
true
public Reward(SignChangeEvent ev, Player player) { if(ev.getLine(0).equalsIgnoreCase("[Reward]")) { if(!player.hasPermission("marocraft.reward.create")) { Helper.SendMessageNoPermission(ev.getPlayer()); ev.setCancelled(true); return; } if(ev.getLine(1).equals("") || ev.getLine(2).equals("") || ev.getLine(3).equals("")) { this.Help(ev.getPlayer()); ev.setCancelled(true); return; } String[] locArray = ev.getLine(3).split(" "); Double x = Double.parseDouble(locArray[0]); Double y = Double.parseDouble(locArray[1]); Double z = Double.parseDouble(locArray[2]); if(x == null || y == null || z == null) { this.Help(player); ev.setCancelled(true); return; } this._rewardString = ev.getLine(1); this._rewardTPLocation = new Location(player.getWorld(),x,y,z); this._rewardTimeLock = Integer.parseInt(ev.getLine(2)); } else { ev.setCancelled(true); return; } }
public Reward(SignChangeEvent ev, Player player) { if(ev.getLine(0).equalsIgnoreCase("[Reward]")) { if(!player.hasPermission("marocraft.reward.create")) { Helper.SendMessageNoPermission(ev.getPlayer()); ev.setCancelled(true); return; } if(ev.getLine(1).equals("") || ev.getLine(2).equals("") || ev.getLine(3).equals("")) { this.Help(ev.getPlayer()); ev.setCancelled(true); return; } String[] locArray = ev.getLine(3).split(" "); Double x = Double.parseDouble(locArray[0]); Double y = Double.parseDouble(locArray[1]); Double z = Double.parseDouble(locArray[2]); if(x == null || y == null || z == null) { this.Help(player); ev.setCancelled(true); return; } this._rewardString = ev.getLine(1); this._rewardTPLocation = new Location(player.getWorld(),x,y,z); this._rewardTimeLock = Integer.parseInt(ev.getLine(2)); } else { return; } }
diff --git a/src/core/org/luaj/vm/LuaState.java b/src/core/org/luaj/vm/LuaState.java index 49a48ef..c698a54 100644 --- a/src/core/org/luaj/vm/LuaState.java +++ b/src/core/org/luaj/vm/LuaState.java @@ -1,2545 +1,2545 @@ /******************************************************************************* * Copyright (c) 2007 LuaJ. 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.vm; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Stack; import org.luaj.lib.BaseLib; import org.luaj.lib.CoroutineLib; import org.luaj.lib.MathLib; import org.luaj.lib.PackageLib; import org.luaj.lib.StringLib; import org.luaj.lib.TableLib; /** * <hr> * <h3><a name="LuaState"><code>LuaState</code></a></h3> * * <pre> * typedef struct LuaState; * </pre> * * <p> * Opaque structure that keeps the whole state of a Lua interpreter. The Lua * library is fully reentrant: it has no global variables. All information about * a state is kept in this structure. * * * <p> * Here we list all functions and types from the C&nbsp;API in alphabetical * order. Each function has an indicator like this: <span class="apii">[-o, +p, * <em>x</em>]</span> * * <p> * The first field, <code>o</code>, is how many elements the function pops * from the stack. The second field, <code>p</code>, is how many elements the * function pushes onto the stack. (Any function always pushes its results after * popping its arguments.) A field in the form <code>x|y</code> means the * function may push (or pop) <code>x</code> or <code>y</code> elements, * depending on the situation; an interrogation mark '<code>?</code>' means * that we cannot know how many elements the function pops/pushes by looking * only at its arguments (e.g., they may depend on what is on the stack). The * third field, <code>x</code>, tells whether the function may throw errors: '<code>-</code>' * means the function never throws any error; '<code>m</code>' means the * function may throw an error only due to not enough memory; '<code>e</code>' * means the function may throw other kinds of errors; '<code>v</code>' * means the function may throw an error on purpose. * * */ public class LuaState extends Lua { /* thread status; 0 is OK */ private static final int LUA_YIELD = 1; private static final int LUA_ERRRUN = 2; private static final int LUA_ERRSYNTAX = 3; private static final int LUA_ERRMEM = 4; private static final int LUA_ERRERR = 5; private static final int LUA_MINSTACK = 20; private static final int LUA_MINCALLS = 10; public int base = 0; protected int top = 0; protected int nresults = -1; public LValue[] stack = new LValue[LUA_MINSTACK]; public int cc = -1; public CallInfo[] calls = new CallInfo[LUA_MINCALLS]; protected Stack upvals = new Stack(); protected LFunction panic; static LuaState mainState; public LTable _G; // main debug hook, overridden by DebugStackState protected void debugHooks(int pc) { } protected void debugAssert(boolean b) { } // ------------------- constructors --------------------- /** * Creates a new, independent LuaState instance. <span class="apii">[-0, +0, * <em>-</em>]</span> * * <p> * Returns <code>NULL</code> if cannot create the state (due to lack of * memory). The argument <code>f</code> is the allocator function; Lua * does all memory allocation for this state through this function. The * second argument, <code>ud</code>, is an opaque pointer that Lua simply * passes to the allocator in every call. */ protected LuaState() { _G = new LTable(); _G.put("_G", _G); mainState = this; } /** * Create a LuaState with a specific global environment. Used by LThread. * * @param globals the LTable to use as globals for this LuaState */ LuaState(LTable globals) { _G = globals; } /** * Performs the initialization. */ public void init() {} /** * Perform any shutdown/clean up tasks if needed */ public void shutdown() {} /** * Install the standard set of libraries used by most implementations: * BaseLib, CoroutineLib, MathLib, PackageLib, TableLib, StringLib */ public void installStandardLibs() { BaseLib.install(_G); CoroutineLib.install(_G); MathLib.install(_G); PackageLib.install(_G); TableLib.install(_G); StringLib.install(_G); } // ================ interfaces for performing calls /** * Create a call frame for a call that has been set up on * the stack. The first value on the stack must be a Closure, * and subsequent values are arguments to the closure. */ public void prepStackCall() { LClosure c = (LClosure) stack[base]; int resultbase = base; // Expand the stack if necessary checkstack( c.p.maxstacksize ); if ( ! c.p.is_vararg ) { base += 1; adjustTop( base+c.p.numparams ); } else { /* vararg function */ int npar = c.p.numparams; int narg = Math.max(0, top - base - 1); int nfix = Math.min(narg, npar); int nvar = Math.max(0, narg-nfix); // must copy args into position, add number parameter stack[top] = LInteger.valueOf(nvar); System.arraycopy(stack, base+1, stack, top+1, nfix); base = top + 1; top = base + nfix; adjustTop( base + npar ); } final int newcc = cc + 1; if ( newcc >= calls.length ) { CallInfo[] newcalls = new CallInfo[ calls.length * 2 ]; System.arraycopy( calls, 0, newcalls, 0, cc+1 ); calls = newcalls; } calls[newcc] = new CallInfo(c, base, top, resultbase, nresults); cc = newcc; stackClear( top, base + c.p.maxstacksize ); } /** * Execute bytecodes until the current call completes * or the vm yields. */ public void execute() { for ( int cb=cc; cc>=cb; ) exec(); } /** * Put the closure on the stack with arguments, * then perform the call. Leave return values * on the stack for later querying. * * @param c * @param values */ public void doCall( LClosure c, LValue[] args ) { settop(0); pushlvalue( c ); for ( int i=0, n=(args!=null? args.length: 0); i<n; i++ ) pushlvalue( args[i] ); prepStackCall(); execute(); base = (cc>=0? calls[cc].base: 0); } /** * Invoke a LFunction being called via prepStackCall() * @param javaFunction */ public void invokeJavaFunction(LFunction javaFunction) { int resultbase = base; int resultsneeded = nresults; ++base; int nactual = javaFunction.invoke(this); debugAssert(nactual>=0); debugAssert(top-nactual>=base); System.arraycopy(stack, top-nactual, stack, base=resultbase, nactual); settop( nactual ); if ( resultsneeded >= 0 ) settop( resultsneeded ); } // ================== error processing ================= /** * Calls a function. <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span> * * * <p> * To call a function you must use the following protocol: first, the * function to be called is pushed onto the stack; then, the arguments to * the function are pushed in direct order; that is, the first argument is * pushed first. Finally you call <a href="#lua_call"><code>lua_call</code></a>; * <code>nargs</code> is the number of arguments that you pushed onto the * stack. All arguments and the function value are popped from the stack * when the function is called. The function results are pushed onto the * stack when the function returns. The number of results is adjusted to * <code>nresults</code>, unless <code>nresults</code> is <a * name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>. In this case, * <em>all</em> results from the function are pushed. Lua takes care that * the returned values fit into the stack space. The function results are * pushed onto the stack in direct order (the first result is pushed first), * so that after the call the last result is on the top of the stack. * * * <p> * Any error inside the called function is propagated upwards (with a * <code>longjmp</code>). * * * <p> * The following example shows how the host program may do the equivalent to * this Lua code: * * <pre> * a = f(&quot;how&quot;, t.x, 14) * </pre> * * <p> * Here it is in&nbsp;C: * * <pre> * lua_getfield(L, LUA_GLOBALSINDEX, &quot;f&quot;); // function to be called * lua_pushstring(L, &quot;how&quot;); // 1st argument * lua_getfield(L, LUA_GLOBALSINDEX, &quot;t&quot;); // table to be indexed * lua_getfield(L, -1, &quot;x&quot;); // push result of t.x (2nd arg) * lua_remove(L, -2); // remove 't' from the stack * lua_pushinteger(L, 14); // 3rd argument * lua_call(L, 3, 1); // call 'f' with 3 arguments and 1 result * lua_setfield(L, LUA_GLOBALSINDEX, &quot;a&quot;); // set global 'a' * </pre> * * <p> * Note that the code above is "balanced": at its end, the stack is back to * its original configuration. This is considered good programming practice. */ public void call( int nargs, int nreturns ) { // save stack state int oldbase = base; // rb is base of new call frame int rb = this.base = top - 1 - nargs; // make or set up the call this.nresults = nreturns; if (this.stack[base].luaStackCall(this)) { // call was set up on the stack, // we still have to execute it execute(); } // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (nreturns >= 0) adjustTop(rb + nreturns); // restore base this.base = oldbase; } /** * Calls a function in protected mode. <span class="apii">[-(nargs + 1), * +(nresults|1), <em>-</em>]</span> * * * <p> * Both <code>nargs</code> and <code>nresults</code> have the same * meaning as in <a href="#lua_call"><code>lua_call</code></a>. If there * are no errors during the call, <a href="#lua_pcall"><code>lua_pcall</code></a> * behaves exactly like <a href="#lua_call"><code>lua_call</code></a>. * However, if there is any error, <a href="#lua_pcall"><code>lua_pcall</code></a> * catches it, pushes a single value on the stack (the error message), and * returns an error code. Like <a href="#lua_call"><code>lua_call</code></a>, * <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the * function and its arguments from the stack. * * * <p> * If <code>errfunc</code> is 0, then the error message returned on the * stack is exactly the original error message. Otherwise, * <code>errfunc</code> is the stack index of an * <em>error handler function</em>. (In the current implementation, this * index cannot be a pseudo-index.) In case of runtime errors, this function * will be called with the error message and its return value will be the * message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>. * * * <p> * Typically, the error handler function is used to add more debug * information to the error message, such as a stack traceback. Such * information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>, * since by then the stack has unwound. * * * <p> * The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns * 0 in case of success or one of the following error codes (defined in * <code>lua.h</code>): * * <ul> * * <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b> a * runtime error. </li> * * <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b> * memory allocation error. For such errors, Lua does not call the error * handler function. </li> * * <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b> * error while running the error handler function. </li> * * </ul> */ public int pcall( int nargs, int nreturns, int errfunc ) { // save stack state int oldtop = top; int oldbase = base; int oldcc = cc; try { // rb is base of new call frame int rb = this.base = top - 1 - nargs; // make or set up the call this.nresults = nreturns; if (this.stack[base].luaStackCall(this)) { // call was set up on the stack, // we still have to execute it execute(); } // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (nreturns >= 0) adjustTop(rb + nreturns); // restore base this.base = oldbase; return 0; } catch ( Throwable t ) { this.base = oldbase; this.cc = oldcc; closeUpVals(oldtop); /* close eventual pending closures */ String s = t.getMessage(); settop(0); pushstring( s!=null? s: t.toString() ); return (t instanceof OutOfMemoryError? LUA_ERRMEM: LUA_ERRRUN); } } /** * Loads a Lua chunk. <span class="apii">[-0, +1, <em>-</em>]</span> * * <p> * If there are no errors, <a href="#lua_load"><code>lua_load</code></a> * pushes the compiled chunk as a Lua function on top of the stack. * Otherwise, it pushes an error message. The return values of <a * href="#lua_load"><code>lua_load</code></a> are: * * <ul> * * <li><b>0:</b> no errors;</li> * * <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b> * syntax error during pre-compilation;</li> * * <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b> * memory allocation error.</li> * * </ul> * * <p> * This function only loads a chunk; it does not run it. * * * <p> * <a href="#lua_load"><code>lua_load</code></a> automatically detects * whether the chunk is text or binary, and loads it accordingly (see * program <code>luac</code>). * * * <p> * The <a href="#lua_load"><code>lua_load</code></a> function uses a * user-supplied <code>reader</code> function to read the chunk (see <a * href="#lua_Reader"><code>lua_Reader</code></a>). The * <code>data</code> argument is an opaque value passed to the reader * function. * * * <p> * The <code>chunkname</code> argument gives a name to the chunk, which is * used for error messages and in debug information (see <a * href="#3.8">&sect;3.8</a>). */ public int load( InputStream is, String chunkname ) { try { LPrototype p = LoadState.undump(this, is, chunkname ); pushlvalue( new LClosure( p, _G ) ); return 0; } catch ( Throwable t ) { pushstring( t.getMessage() ); return (t instanceof OutOfMemoryError? LUA_ERRMEM: LUA_ERRSYNTAX); } } // ================ execute instructions private LValue RKBC(LValue[] k, int bc) { return LuaState.ISK(bc) ? k[LuaState.INDEXK(bc)]: stack[base + bc]; } private LValue GETARG_RKB(LValue[] k, int i) { return RKBC(k, GETARG_B(i)); } private LValue GETARG_RKC(LValue[] k, int i) { return RKBC(k, GETARG_C(i)); } private void adjustTop(int newTop) { while (top < newTop) this.stack[top++] = LNil.NIL; top = newTop; } private final void stackClear(int startIndex, int endIndex) { for (; startIndex < endIndex; startIndex++) { stack[startIndex] = LNil.NIL; } } /** execute instructions up to a yield, return, or call */ public void exec() { if ( cc < 0 ) return; int i, a, b, c, o, n, cb; LValue rkb, rkc, nvarargs, key, val; LValue i0, step, idx, limit, init, table; boolean back, body; LPrototype proto; LClosure newClosure; // reload values from the current call frame // into local variables CallInfo ci = calls[cc]; LClosure cl = ci.closure; LPrototype p = cl.p; int[] code = p.code; LValue[] k = p.k; this.base = ci.base; // loop until a return instruction is processed, // or the vm yields while (true) { debugAssert( ci == calls[cc] ); // sync up top ci.top = top; // allow debug hooks a chance to operate debugHooks( ci.pc ); // advance program counter i = code[ci.pc++]; // get first opcode arg a = LuaState.GETARG_A(i); switch (LuaState.GET_OPCODE(i)) { case LuaState.OP_MOVE: { b = LuaState.GETARG_B(i); this.stack[base + a] = this.stack[base + b]; continue; } case LuaState.OP_LOADK: { b = LuaState.GETARG_Bx(i); this.stack[base + a] = k[b]; continue; } case LuaState.OP_LOADBOOL: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE); if (c != 0) ci.pc++; /* skip next instruction (if C) */ continue; } case LuaState.OP_LOADNIL: { b = LuaState.GETARG_B(i); do { this.stack[base + b] = LNil.NIL; } while ((--b) >= a); continue; } case LuaState.OP_GETUPVAL: { b = LuaState.GETARG_B(i); this.stack[base + a] = cl.upVals[b].getValue(); continue; } case LuaState.OP_GETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; table = cl.env; top = base + a; table.luaGetTable(this, table, key); continue; } case LuaState.OP_GETTABLE: { b = LuaState.GETARG_B(i); key = GETARG_RKC(k, i); table = this.stack[base + b]; top = base + a; table.luaGetTable(this, table, key); continue; } case LuaState.OP_SETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; val = this.stack[base + a]; table = cl.env; table.luaSetTable(this, table, key, val); continue; } case LuaState.OP_SETUPVAL: { b = LuaState.GETARG_B(i); cl.upVals[b].setValue( this.stack[base + a] ); continue; } case LuaState.OP_SETTABLE: { key = GETARG_RKB(k, i); val = GETARG_RKC(k, i); table = this.stack[base + a]; table.luaSetTable(this, table, key, val); continue; } case LuaState.OP_NEWTABLE: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = new LTable(b, c); continue; } case LuaState.OP_SELF: { rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); top = base + a; rkb.luaGetTable(this, rkb, rkc); this.stack[base + a + 1] = rkb; // StkId rb = RB(i); // setobjs2s(L, ra+1, rb); // Protect(luaV_gettable(L, rb, RKC(i), ra)); continue; } case LuaState.OP_ADD: case LuaState.OP_SUB: case LuaState.OP_MUL: case LuaState.OP_DIV: case LuaState.OP_MOD: case LuaState.OP_POW: { o = LuaState.GET_OPCODE(i); rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb); continue; } case LuaState.OP_UNM: { rkb = GETARG_RKB(k, i); this.stack[base + a] = rkb.luaUnaryMinus(); continue; } case LuaState.OP_NOT: { rkb = GETARG_RKB(k, i); this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE : LBoolean.FALSE); continue; } case LuaState.OP_LEN: { rkb = GETARG_RKB(k, i); this.stack[base + a] = LInteger.valueOf( rkb.luaLength() ); continue; } case LuaState.OP_CONCAT: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int numValues = c - b + 1; LString[] strings = new LString[numValues]; for (int j = b, l = 0; j <= c; j++, l++) { LString s = this.stack[base + j].luaAsString(); strings[l] = s; } this.stack[base + a] = LString.concat( strings ); continue; } case LuaState.OP_JMP: { ci.pc += LuaState.GETARG_sBx(i); continue; } case LuaState.OP_EQ: case LuaState.OP_LT: case LuaState.OP_LE: { o = LuaState.GET_OPCODE(i); rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); boolean test = rkc.luaBinCmpUnknown(o, rkb); if (test == (a == 0)) ci.pc++; continue; } case LuaState.OP_TEST: { c = LuaState.GETARG_C(i); if (this.stack[base + a].toJavaBoolean() != (c != 0)) ci.pc++; continue; } case LuaState.OP_TESTSET: { rkb = GETARG_RKB(k, i); c = LuaState.GETARG_C(i); if (rkb.toJavaBoolean() != (c != 0)) ci.pc++; else this.stack[base + a] = rkb; continue; } case LuaState.OP_CALL: { // ra is base of new call frame this.base += a; // number of args b = LuaState.GETARG_B(i); if (b != 0) // else use previous instruction set top top = base + b; // number of return values we need c = LuaState.GETARG_C(i); // make or set up the call this.nresults = c - 1; if (this.stack[base].luaStackCall(this)) return; // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (c > 0) adjustTop(base + c - 1); // restore base base = ci.base; continue; } case LuaState.OP_TAILCALL: { closeUpVals(base); // copy down the frame before calling! // number of args (including the function) b = LuaState.GETARG_B(i); if (b == 0) b = top - (base + a); // copy call + all args, discard current frame System.arraycopy(stack, base + a, stack, ci.resultbase, b); this.base = ci.resultbase; this.top = base + b; this.nresults = ci.nresults; --cc; // make or set up the call try { if (this.stack[base].luaStackCall(this)) { return; } } catch (LuaErrorException e) { // in case of lua error, we need to restore cc so that // the debug can get the correct location where the error // occured. cc++; throw e; } // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (this.nresults >= 0) adjustTop(base + nresults); // force restore of base, etc. return; } case LuaState.OP_RETURN: { // number of return vals to return b = LuaState.GETARG_B(i) - 1; if (b == -1) b = top - (base + a); // close open upvals closeUpVals( base ); // number to copy down System.arraycopy(stack, base + a, stack, ci.resultbase, b); top = ci.resultbase + b; // adjust results to what caller expected if (ci.nresults >= 0) adjustTop(ci.resultbase + ci.nresults); // pop the call stack --cc; // force a reload of the calling context return; } case LuaState.OP_FORLOOP: { i0 = this.stack[base + a]; step = this.stack[base + a + 2]; idx = step.luaBinOpUnknown(Lua.OP_ADD, i0); limit = this.stack[base + a + 1]; back = step.luaBinCmpInteger(Lua.OP_LT, 0); body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit .luaBinCmpUnknown(Lua.OP_LE, idx)); if (body) { this.stack[base + a] = idx; this.stack[base + a + 3] = idx; top = base + a + 3 + 1; ci.pc += LuaState.GETARG_sBx(i); } continue; } case LuaState.OP_FORPREP: { init = this.stack[base + a]; step = this.stack[base + a + 2]; this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init); b = LuaState.GETARG_sBx(i); ci.pc += b; continue; } case LuaState.OP_TFORLOOP: { cb = base + a + 3; /* call base */ base = cb; adjustTop( cb + 3 ); System.arraycopy(this.stack, cb-3, this.stack, cb, 3); // call the iterator c = LuaState.GETARG_C(i); this.nresults = c; if (this.stack[cb].luaStackCall(this)) execute(); base = ci.base; adjustTop( cb + c ); // test for continuation if (this.stack[cb] != LNil.NIL ) { // continue? this.stack[cb-1] = this.stack[cb]; // save control variable } else { ci.pc++; // skip over jump } continue; } case LuaState.OP_SETLIST: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int listBase = base + a; if (b == 0) { b = top - listBase - 1; } if (c == 0) { c = code[ci.pc++]; } table = this.stack[base + a]; for (int index = 1; index <= b; index++) { val = this.stack[listBase + index]; table.luaSetTable(this, table, LInteger.valueOf(index), val); } top = base + a - 1; continue; } case LuaState.OP_CLOSE: { closeUpVals( a ); // close upvals higher in the stack than position a continue; } case LuaState.OP_CLOSURE: { b = LuaState.GETARG_Bx(i); proto = cl.p.p[b]; - newClosure = new LClosure(proto, _G); + newClosure = new LClosure(proto, cl.env); for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) { i = code[ci.pc]; o = LuaState.GET_OPCODE(i); b = LuaState.GETARG_B(i); if (o == LuaState.OP_GETUPVAL) { newClosure.upVals[j] = cl.upVals[b]; } else if (o == LuaState.OP_MOVE) { newClosure.upVals[j] = findUpVal( proto.upvalues[j], base + b ); } else { throw new java.lang.IllegalArgumentException( "bad opcode: " + o); } } this.stack[base + a] = newClosure; continue; } case LuaState.OP_VARARG: { // figure out how many args to copy b = LuaState.GETARG_B(i) - 1; nvarargs = this.stack[base - 1]; n = nvarargs.toJavaInt(); if (b == LuaState.LUA_MULTRET) { b = n; // use entire varargs supplied } // copy args up to call stack area checkstack(a+b); for (int j = 0; j < b; j++) this.stack[base + a + j] = (j < n ? this.stack[base - n + j - 1] : LNil.NIL); top = base + a + b; continue; } } } } private UpVal findUpVal( LString upValName, int target ) { UpVal up; int i; for ( i = this.upvals.size() - 1; i >= 0; --i ) { up = (UpVal) this.upvals.elementAt( i ); if ( up.state == this && up.position == target ) { return up; } else if ( up.position < target ) { break; } } up = new UpVal( upValName, this, target ); this.upvals.insertElementAt( up, i + 1 ); return up; } private void closeUpVals( int limit ) { while ( !upvals.empty() && ( (UpVal) this.upvals.lastElement() ).close( limit ) ) { this.upvals.pop(); } } public CallInfo getStackFrame(int callStackDepth) { return calls[cc-callStackDepth]; } //=============================================================== // Lua Java API //=============================================================== private void notImplemented() { throw new LuaErrorException("AbstractStack: not yet implemented"); } /** * Sets a new panic function and returns the old one. <span * class="apii">[-0, +0, <em>-</em>]</span> * * * <p> * If an error happens outside any protected environment, Lua calls a * <em>panic function</em> and then calls <code>exit(EXIT_FAILURE)</code>, * thus exiting the host application. Your panic function may avoid this * exit by never returning (e.g., doing a long jump). * * * <p> * The panic function can access the error message at the top of the stack. */ public LFunction atpanic(LFunction panicf) { LFunction f = panic; panic = panicf; return f; } /** * Returns the current program counter for the given call frame. * @param ci -- A call frame * @return the current program counter for the given call frame. */ protected int getCurrentPc(CallInfo ci) { int pc = (ci != calls[cc] ? ci.pc - 1 : ci.pc); return pc; } protected String getSourceFileName(LString source) { String sourceStr = LoadState.getSourceName(source.toJavaString()); return getSourceFileName(sourceStr); } protected String getSourceFileName(String sourceStr) { if (!LoadState.SOURCE_BINARY_STRING.equals(sourceStr)) { sourceStr = sourceStr.replace('\\', '/'); } int index = sourceStr.lastIndexOf('/'); if (index != -1) { sourceStr = sourceStr.substring(index + 1); } return sourceStr; } /** * Get the file line number info for a particular call frame. * @param cindex index into call stack * @return */ protected String getFileLine(int cindex) { String source = "?"; String line = ""; if (cindex >= 0 && cindex <= cc) { CallInfo call = this.calls[cindex]; LPrototype p = call.closure.p; if (p != null && p.source != null) source = getSourceFileName(p.source); int pc = getCurrentPc(call); if (p.lineinfo != null && p.lineinfo.length > pc) line = ":" + String.valueOf(p.lineinfo[pc]); } return source + line; } public String getStackTrace() { StringBuffer buffer = new StringBuffer("Stack Trace:\n"); for (int i = cc; i >= 0; i--) { buffer.append(" "); buffer.append(getFileLine(i)); buffer.append("\n"); } return buffer.toString(); } /** * Raises an error. The message is pushed onto the stack and used as the error message. * It also adds at the beginning of the message the file name and the line number where * the error occurred, if this information is available. * * In the java implementation this throws a LuaErrorException * after filling line number information first when level > 0. */ public void error(String message, int level) { throw new LuaErrorException( this, message, level ); } /** * Raises an error with the default level. */ public void error(String message) { throw new LuaErrorException( this, message, 1 ); } /** * Generates a Lua error. <span class="apii">[-1, +0, <em>v</em>]</span> * * <p> * The error message (which can actually be a Lua value of any type) must be * on the stack top. This function does a long jump, and therefore never * returns. (see <a href="#luaL_error"><code>luaL_error</code></a>). * */ public void error() { throw new LuaErrorException( this, tostring(-1), 0); } /** * Dumps a function as a binary chunk. <span class="apii">[-0, +0, * <em>m</em>]</span> * * <p> * Receives a Lua function on the top of the stack and produces a binary * chunk that, if loaded again, results in a function equivalent to the one * dumped. As it produces parts of the chunk, <a href="#lua_dump"><code>lua_dump</code></a> * calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>) * with the given <code>data</code> to write them. * <p> * The value returned is the error code returned by the last call to the * writer; 0&nbsp;means no errors. * * * <p> * This function does not pop the Lua function from the stack. * */ public void dump() { notImplemented(); } /** * Pushes a new C&nbsp;closure onto the stack. <span class="apii">[-n, +1, * <em>m</em>]</span> * * * <p> * When a Java&nbsp;function is created, it is possible to associate some * values with it, thus creating a C&nbsp;closure (see <a * href="#3.4">&sect;3.4</a>); these values are then accessible to the * function whenever it is called. To associate values with a * C&nbsp;function, first these values should be pushed onto the stack (when * there are multiple values, the first value is pushed first). Then <a * href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> is called * to create and push the C&nbsp;function onto the stack, with the argument * <code>n</code> telling how many values should be associated with the * function. <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> * also pops these values from the stack. */ public void pushclosure(LFunction fn, int n) { notImplemented(); } /** * Calls the C&nbsp;function <code>func</code> in protected mode. <span * class="apii">[-0, +(0|1), <em>-</em>]</span> * * <p> * <code>func</code> starts with only one element in its stack, a light * userdata containing <code>ud</code>. In case of errors, <a * href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error * codes as <a href="#lua_pcall"><code>lua_pcall</code></a>, plus the * error object on the top of the stack; otherwise, it returns zero, and * does not change the stack. All values returned by <code>func</code> are * discarded. */ public int javapcall(LFunction func, Object ud) { this.pushjavafunction(func); this.pushlightuserdata(ud); return this.pcall(1, 0, 0); } /** * Format and push a string. <span class="apii">[-0, +1, <em>m</em>]</span> * * <p> * Pushes onto the stack a formatted string and returns a pointer to this * string. It is similar to the C&nbsp;function <code>sprintf</code>, but * has some important differences: * * <ul> * * <li> You do not have to allocate space for the result: the result is a * Lua string and Lua takes care of memory allocation (and deallocation, * through garbage collection). </li> * * <li> The conversion specifiers are quite restricted. There are no flags, * widths, or precisions. The conversion specifiers can only be '<code>%%</code>' * (inserts a '<code>%</code>' in the string), '<code>%s</code>' * (inserts a zero-terminated string, with no size restrictions), '<code>%f</code>' * (inserts a <a href="#lua_Number"><code>lua_Number</code></a>), '<code>%p</code>' * (inserts a pointer as a hexadecimal numeral), '<code>%d</code>' * (inserts an <code>int</code>), and '<code>%c</code>' (inserts an * <code>int</code> as a character). </li> * * </ul> */ public String pushfstring(String fmt, Object[] args) { notImplemented(); return null; } /** * Format and push a string. <span class="apii">[-0, +1, <em>m</em>]</span> * * <p> * Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, * except that it receives a <code>va_list</code> instead of a variable * number of arguments. */ public void pushvfstring(String format, Object[] args) { notImplemented(); } /** * Test if two objects are the same object. <span class="apii">[-0, +0, * <em>-</em>]</span> * * <p> * Returns 1 if the two values in acceptable indices <code>index1</code> * and <code>index2</code> are primitively equal (that is, without calling * metamethods). Otherwise returns&nbsp;0. Also returns&nbsp;0 if any of the * indices are non valid. */ public void rawequal(int index1, int index2) { notImplemented(); } /** * Pushes a value's environment table. <span class="apii">[-0, +1, * <em>-</em>]</span> * * <p> * Pushes onto the stack the environment table of the value at the given * index. */ public void getfenv(int index) { LValue f = topointer(index); pushlvalue( ((LClosure) f).env ); } /** * Set the environment for a value. <span class="apii">[-1, +0, <em>-</em>]</span> * * <p> * Pops a table from the stack and sets it as the new environment for the * value at the given index. If the value at the given index is neither a * function nor a thread nor a userdata, <a href="#lua_setfenv"><code>lua_setfenv</code></a> * returns 0. Otherwise it returns 1. */ public int setfenv(int index) { LTable t = totable(-1); LValue f = topointer(index); pop(1); return f.luaSetEnv(t); } /** * * Ensures that there are at least <code>extra</code> free stack slots in * the stack. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * It returns false if it cannot grow the stack to that size. This function * never shrinks the stack; if the stack is already larger than the new * size, it is left unchanged. * */ public void checkstack(int extra) { if ( top + extra >= stack.length ) { int n = Math.max( top + extra + LUA_MINSTACK, stack.length * 2 ); LValue[] s = new LValue[n]; System.arraycopy(stack, 0, s, 0, stack.length); stack = s; } } /** * Closes the given Lua state. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Destroys all objects in the given Lua state (calling the corresponding * garbage-collection metamethods, if any) and frees all dynamic memory used * by this state. On several platforms, you may not need to call this * function, because all resources are naturally released when the host * program ends. On the other hand, long-running programs, such as a daemon * or a web server, might need to release states as soon as they are not * needed, to avoid growing too large. */ public void close() { stack = new LValue[20]; base = top = 0; } /** * Concatenates the <code>n</code> values at the top of the stack. <span * class="apii">[-n, +1, <em>e</em>]</span> * * <p> * Concatenates the <code>n</code> values at the top of the stack, pops * them, and leaves the result at the top. If <code>n</code>&nbsp;is&nbsp;1, * the result is the single value on the stack (that is, the function does * nothing); if <code>n</code> is 0, the result is the empty string. * Concatenation is performed following the usual semantics of Lua (see <a * href="#2.5.4">&sect;2.5.4</a>). */ public void concat(int n) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); for ( int i=-n; i<0; i++ ) { LString ls = tolstring(i); baos.write(ls.m_bytes, ls.m_offset, ls.m_length); } pop(n); pushlvalue( new LString(baos.toByteArray())); } /** * Creates a new empty table and pushes it onto the stack. <span * class="apii">[-0, +1, <em>m</em>]</span> * * <p> * The new table has space pre-allocated for <code>narr</code> array * elements and <code>nrec</code> non-array elements. This pre-allocation * is useful when you know exactly how many elements the table will have. * Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>. */ public void createtable(int narr, int nrec) { stack[top++] = new LTable(narr, nrec); } /** * Tests if two items on the stack are equal. <span class="apii">[-0, +0, * <em>e</em>]</span> * * <p> * Returns 1 if the two values in acceptable indices <code>index1</code> * and <code>index2</code> are equal, following the semantics of the Lua * <code>==</code> operator (that is, may call metamethods). Otherwise * returns&nbsp;0. Also returns&nbsp;0 if any of the indices is non valid. * * */ public boolean equal(int index1, int index2) { return topointer(index2).luaBinOpUnknown(Lua.OP_EQ, topointer(index1)).toJavaBoolean(); } /** * Controls the garbage collector. <span class="apii">[-0, +0, <em>e</em>]</span> * * <p> * This function performs several tasks, according to the value of the * parameter <code>what</code>: * * <ul> * * <li><b><code>LUA_GCSTOP</code>:</b> stops the garbage collector. * </li> * * <li><b><code>LUA_GCRESTART</code>:</b> restarts the garbage * collector. </li> * * <li><b><code>LUA_GCCOLLECT</code>:</b> performs a full * garbage-collection cycle. </li> * * <li><b><code>LUA_GCCOUNT</code>:</b> returns the current amount of * memory (in Kbytes) in use by Lua. </li> * * <li><b><code>LUA_GCCOUNTB</code>:</b> returns the remainder of * dividing the current amount of bytes of memory in use by Lua by 1024. * </li> * * <li><b><code>LUA_GCSTEP</code>:</b> performs an incremental step of * garbage collection. The step "size" is controlled by <code>data</code> * (larger values mean more steps) in a non-specified way. If you want to * control the step size you must experimentally tune the value of * <code>data</code>. The function returns 1 if the step finished a * garbage-collection cycle. </li> * * <li><b><code>LUA_GCSETPAUSE</code>:</b> sets <code>data</code>/100 * as the new value for the <em>pause</em> of the collector (see <a * href="#2.10">&sect;2.10</a>). The function returns the previous value of * the pause. </li> * * <li><b><code>LUA_GCSETSTEPMUL</code>:</b> sets <code>data</code>/100 * as the new value for the <em>step multiplier</em> of the collector (see * <a href="#2.10">&sect;2.10</a>). The function returns the previous value * of the step multiplier. </li> * * </ul> */ public void gc(int what, int data) { notImplemented(); } /** * Dereference a tables field. <span class="apii">[-0, +1, <em>e</em>]</span> * * <p> * Pushes onto the stack the value <code>t[k]</code>, where * <code>t</code> is the value at the given valid index. As in Lua, this * function may trigger a metamethod for the "index" event (see <a * href="#2.8">&sect;2.8</a>). * */ public void getfield(int index, LString k) { LTable t = totable(index); t.luaGetTable(this, t, k); } /** * Look up a global value. <span class="apii">[-0, +1, <em>e</em>]</span> * * <p> * Pushes onto the stack the value of the global <code>name</code>. It is * defined as a macro: * * <pre> * #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s) * * </pre> */ public void getglobal(String s) { LTable t = this._G; // TODO: what if this triggers metatable ops // pushlvalue( t.luaGetTable(this, t, new LString(s))); t.luaGetTable(this, t, new LString(s)); } /** * Get a value's metatable. <span class="apii">[-0, +(0|1), <em>-</em>]</span> * * <p> * Pushes onto the stack the metatable of the value at the given acceptable * index. If the index is not valid, or if the value does not have a * metatable, the function returns false and pushes nothing on the stack. * * @return true if the metatable was pushed onto the stack, false otherwise */ public boolean getmetatable(int index) { LTable mt = topointer(index).luaGetMetatable(); if ( mt != null ) { pushlvalue( mt ); return true; } return false; } /** * Dereference a table's list element. <span class="apii">[-1, +1, * <em>e</em>]</span> * * <p> * Pushes onto the stack the value <code>t[k]</code>, where * <code>t</code> is the value at the given valid index and <code>k</code> * is the value at the top of the stack. * * <p> * This function pops the key from the stack (putting the resulting value in * its place). As in Lua, this function may trigger a metamethod for the * "index" event (see <a href="#2.8">&sect;2.8</a>). */ public void gettable(int index) { LValue t = totable(index); LValue k = poplvalue(); // todo: what if this triggers metatable ops // pushlvalue( t.luaGetTable(this, t, k) ); t.luaGetTable(this, t, k); } /** * Insert the top item somewhere in the stack. <span class="apii">[-1, +1, * <em>-</em>]</span> * * <p> * Moves the top element into the given valid index, shifting up the * elements above this index to open space. Cannot be called with a * pseudo-index, because a pseudo-index is not an actual stack position. * */ public void insert(int index) { int ai = index2adr(index); LValue v = stack[top-1]; System.arraycopy(stack, ai, stack, ai+1, top-ai-1); stack[ai] = v; } /** * Test if a value is boolean. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index has type boolean, * and 0&nbsp;otherwise. * */ public boolean isboolean(int index) { return type(index) == Lua.LUA_TBOOLEAN; } /** * Test if a value is a function. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns true if the value at the given acceptable index is a function * (either C or Lua), and false&nbsp;otherwise. * */ public boolean isfunction(int index) { return type(index) == Lua.LUA_TFUNCTION; } /** * Test if a value is a JavaFunction. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is a * C&nbsp;function, and 0&nbsp;otherwise. * */ public boolean isjavafunction(int index) { return topointer(index) instanceof LFunction; } /** * Test if a value is light user data <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is a light userdata, * and 0&nbsp;otherwise. */ public boolean islightuserdata(int index) { return false; } /** * Test if a value is nil <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is <b>nil</b>, and * 0&nbsp;otherwise. */ public boolean isnil(int index) { return topointer(index) == LNil.NIL; } /** * Test if a value is not valid <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the the given acceptable index is not valid (that is, it * refers to an element outside the current stack), and 0&nbsp;otherwise. */ public boolean isnone(int index) { return topointer(index) == null; } /** * Test if a value is nil or not valid <span class="apii">[-0, +0, * <em>-</em>]</span> * * <p> * Returns 1 if the the given acceptable index is not valid (that is, it * refers to an element outside the current stack) or if the value at this * index is <b>nil</b>, and 0&nbsp;otherwise. */ public boolean isnoneornil(int index) { Object v = topointer(index); return v == null || v == LNil.NIL; } /** * Test if a value is a number <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is a number or a * string convertible to a number, and 0&nbsp;otherwise. */ public boolean isnumber(int index) { return tolnumber(index) != LNil.NIL; } /** * Convert a value to an LNumber<span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns an LNumber if the value at the given acceptable index is a number or a * string convertible to a number, and LNil.NIL&nbsp;otherwise. */ public LValue tolnumber(int index) { return topointer(index).luaToNumber(); } /** * Test if a value is a string <span class="apii">[-0, +0, <em>m</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is a string or a * number (which is always convertible to a string), and 0&nbsp;otherwise. */ public boolean isstring(int index) { return type(index) == Lua.LUA_TSTRING; } /** * Test if a value is a table <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is a table, and * 0&nbsp;otherwise. */ public boolean istable(int index) { return type(index) == Lua.LUA_TTABLE; } /** * Test if a value is a thread <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is a thread, and * 0&nbsp;otherwise. */ public boolean isthread(int index) { return type(index) == Lua.LUA_TTHREAD; } /** * Test if a value is a userdata <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns 1 if the value at the given acceptable index is a userdata * (either full or light), and 0&nbsp;otherwise. */ public boolean isuserdata(int index) { return type(index) == Lua.LUA_TUSERDATA; } /** * Compare two values <span class="apii">[-0, +0, <em>e</em>]</span> * * <p> * Returns 1 if the value at acceptable index <code>index1</code> is * smaller than the value at acceptable index <code>index2</code>, * following the semantics of the Lua <code>&lt;</code> operator (that is, * may call metamethods). Otherwise returns&nbsp;0. Also returns&nbsp;0 if * any of the indices is non valid. */ public boolean lessthan(int index1, int index2) { return topointer(index2).luaBinOpUnknown(Lua.OP_LT, topointer(index1)).toJavaBoolean(); } /** * Create a table <span class="apii">[-0, +1, <em>m</em>]</span> * * <p> * Creates a new empty table and pushes it onto the stack. It is equivalent * to <code>lua_createtable(L, 0, 0)</code>. */ public void newtable() { stack[top++] = new LTable(); } /** * Create a thread <span class="apii">[-0, +1, <em>m</em>]</span> * * <p> * Creates a new thread, pushes it on the stack, and returns a pointer to a * <a href="#lua_State"><code>lua_State</code></a> that represents this * new thread. The new state returned by this function shares with the * original state all global objects (such as tables), but has an * independent execution stack. * * * <p> * There is no explicit function to close or to destroy a thread. Threads * are subject to garbage collection, like any Lua object. */ public void newthread() { notImplemented(); } /** * Create a userdata <span class="apii">[-0, +1, <em>m</em>]</span> * * <p> * This function allocates a new block of memory with the given size, pushes * onto the stack a new full userdata with the block address, and returns * this address. * * * <p> * Userdata represent C&nbsp;values in Lua. A <em>full userdata</em> * represents a block of memory. It is an object (like a table): you must * create it, it can have its own metatable, and you can detect when it is * being collected. A full userdata is only equal to itself (under raw * equality). * * * <p> * When Lua collects a full userdata with a <code>gc</code> metamethod, * Lua calls the metamethod and marks the userdata as finalized. When this * userdata is collected again then Lua frees its corresponding memory. */ public void newuserdata(Object o) { stack[top++] = new LUserData(o); } /** * Traverse to the next table item. <span class="apii">[-1, +(2|0), * <em>e</em>]</span> * * <p> * Pops a key from the stack, and pushes a key-value pair from the table at * the given index (the "next" pair after the given key). If there are no * more elements in the table, then <a href="#lua_next"><code>lua_next</code></a> * returns 0 (and pushes nothing). * * * <p> * A typical traversal looks like this: * * <pre> * // table is in the stack at index 't' * lua_pushnil(L); // first key * while (lua_next(L, t) != 0) { * // uses 'key' (at index -2) and 'value' (at index -1) * printf(&quot;%s - %s\n&quot;, lua_typename(L, lua_type(L, -2)), lua_typename(L, * lua_type(L, -1))); * // removes 'value'; keeps 'key' for next iteration * lua_pop(L, 1); * } * </pre> * * <p> * While traversing a table, do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> * directly on a key, unless you know that the key is actually a string. * Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> * <em>changes</em> the value at the given index; this confuses the next * call to <a href="#lua_next"><code>lua_next</code></a>. */ public int next(int index) { notImplemented(); return 0; } /** * Get the length of an object <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns the "length" of the value at the given acceptable index: for * strings, this is the string length; for tables, this is the result of the * length operator ('<code>#</code>'); for userdata, this is the size of * the block of memory allocated for the userdata; for other values, it * is&nbsp;0. */ public int objlen(int index) { return tostring(index).length(); } /** * Pops <code>n</code> elements from the stack. <span class="apii">[-n, * +0, <em>-</em>]</span> */ public void pop(int n) { for ( int i=0; i<n; i++ ) stack[--top] = null; } private LValue poplvalue() { LValue p = stack[--top]; stack[top] = null; return p; } /** * Push an LValue onto the stack. <span class="apii">[-0, +1, * <em>m</em>]</span> */ public void pushlvalue(LValue value) { if ( value == null ) throw new java.lang.IllegalArgumentException("stack values cannot be null"); try { stack[top] = value; } catch ( java.lang.ArrayIndexOutOfBoundsException aiobe ) { checkstack( LUA_MINSTACK ); stack[top] = value; } finally { ++top; } } /** * Pushes a boolean value with value <code>b</code> onto the stack. <span * class="apii">[-0, +1, <em>-</em>]</span> * */ public void pushboolean(boolean b) { pushlvalue( LBoolean.valueOf(b) ); } /** * Pushes a number with value <code>n</code> onto the stack. <span * class="apii">[-0, +1, <em>-</em>]</span> */ public void pushinteger(int n) { pushlvalue( LInteger.valueOf(n) ); } /** * Pushes a Java&nbsp;function onto the stack. <span class="apii">[-0, +1, * <em>m</em>]</span> * * <p> * This function receives a pointer to a C function and pushes onto the * stack a Lua value of type <code>function</code> that, when called, * invokes the corresponding C&nbsp;function. * * * <p> * Any function to be registered in Lua must follow the correct protocol to * receive its parameters and return its results (see <a * href="#lua_CFunction"><code>lua_CFunction</code></a>). * */ public void pushjavafunction(LFunction f) { pushlvalue( f ); } /** * Pushes a light userdata onto the stack. <span class="apii">[-0, +1, * <em>-</em>]</span> * * * <p> * Userdata represent C&nbsp;values in Lua. A <em>light userdata</em> * represents a pointer. It is a value (like a number): you do not create * it, it has no individual metatable, and it is not collected (as it was * never created). A light userdata is equal to "any" light userdata with * the same C&nbsp;address. */ public void pushlightuserdata(Object p) { notImplemented(); } /** * Push an LString onto the stack. <span class="apii">[-0, +1, * <em>m</em>]</span> */ public void pushlstring(LString s) { pushlvalue(s); } /** * Push string bytes onto the stack as a string. <span class="apii">[-0, +1, * <em>m</em>]</span> * * Pushes the string pointed to by <code>s</code> with size * <code>len</code> onto the stack. Lua makes (or reuses) an internal copy * of the given string, so the memory at <code>s</code> can be freed or * reused immediately after the function returns. The string can contain * embedded zeros. */ public void pushlstring(byte[] bytes, int offset, int length) { pushlvalue(new LString(bytes, offset, length)); } /** * Push string bytes onto the stack as a string. <span class="apii">[-0, +1, * <em>m</em>]</span> * * Pushes the bytes in byteArray onto the stack as a lua string. */ public void pushlstring(byte[] byteArray) { pushlstring(byteArray, 0, byteArray.length); } /** * Pushes a nil value onto the stack. <span class="apii">[-0, +1, <em>-</em>]</span> * */ public void pushnil() { pushlvalue(LNil.NIL); } /** * Pushes a number with value <code>d</code> onto the stack. <span * class="apii">[-0, +1, <em>-</em>]</span> * */ public void pushnumber(double d) { pushlvalue(new LDouble(d)); } /** * Push a String onto the stack. <span class="apii">[-0, +1, <em>m</em>]</span> * * <p> * Pushes the String <code>s</code> onto the stack. Lua makes (or reuses) * an internal copy of the given string, so the memory at <code>s</code> * can be freed or reused immediately after the function returns. The string * cannot contain embedded zeros; it is assumed to end at the first zero. */ public void pushstring(String s) { if ( s == null ) pushnil(); else pushlstring( LString.valueOf(s) ); } /** * Push a thread onto the stack. <span class="apii">[-0, +1, <em>-</em>]</span> * * Pushes the thread represented by <code>L</code> onto the stack. Returns * 1 if this thread is the main thread of its state. */ public void pushthread() { notImplemented(); } /** * Push a value from the stack onto the stack. <span class="apii">[-0, +1, * <em>-</em>]</span> * * <p> * Pushes a copy of the element at the given valid index onto the stack. */ public void pushvalue(int index) { pushlvalue(topointer(index)); } /** * Do a table get without metadata calls. <span class="apii">[-1, +1, * <em>-</em>]</span> * * <p> * Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but * does a raw access (i.e., without metamethods). */ public void rawget(int index) { pushlvalue( totable(index).get(poplvalue()) ); } /** * Do a integer-key table get without metadata calls. <span * class="apii">[-0, +1, <em>-</em>]</span> * * <p> * Pushes onto the stack the value <code>t[n]</code>, where * <code>t</code> is the value at the given valid index. The access is * raw; that is, it does not invoke metamethods. */ public void rawgeti(int index, int n) { pushlvalue( totable(index).get(n) ); } /** * Do a table set without metadata calls. <span class="apii">[-2, +0, * <em>m</em>]</span> * * <p> * Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but * does a raw assignment (i.e., without metamethods). */ public void rawset(int index) { LTable t = totable(index); LValue v = poplvalue(); LValue k = poplvalue(); t.put(k,v); } /** * Do a integer-key table set without metadata calls. <span * class="apii">[-1, +0, <em>m</em>]</span> * * <p> * Does the equivalent of <code>t[n] = v</code>, where <code>t</code> * is the value at the given valid index and <code>v</code> is the value * at the top of the stack. * * * <p> * This function pops the value from the stack. The assignment is raw; that * is, it does not invoke metamethods. */ public void rawseti(int index, int n) { LTable t = totable(index); LValue v = poplvalue(); t.put(n,v); } /** * Register a LFunction with a specific name. <span class="apii">[-0, +0, * <em>m</em>]</span> * * <p> * Sets the function <code>f</code> as the new value of global * <code>name</code>. It is defined as a macro: * * <pre> * #define lua_register(L,n,f) \ * (lua_pushcfunction(L, f), lua_setglobal(L, n)) * * </pre> */ public void register(String name, LFunction f) { pushjavafunction(f); setglobal(name); } /** * Remove an element from the stack. <span class="apii">[-1, +0, <em>-</em>]</span> * * <p> * Removes the element at the given valid index, shifting down the elements * above this index to fill the gap. Cannot be called with a pseudo-index, * because a pseudo-index is not an actual stack position. */ public void remove(int index) { int ai = index2adr(index); System.arraycopy(stack, ai+1, stack, ai, top-ai-1); --top; } /** * Replace an element on the stack. <span class="apii">[-1, +0, <em>-</em>]</span> * * <p> * Moves the top element into the given position (and pops it), without * shifting any element (therefore replacing the value at the given * position). */ public void replace(int index) { int ai = index2adr(index); stack[ai] = poplvalue(); } /** * Starts and resumes a coroutine in a given thread. <span class="apii">[-?, * +?, <em>-</em>]</span> * * * <p> * To start a coroutine, you first create a new thread (see <a * href="#lua_newthread"><code>lua_newthread</code></a>); then you push * onto its stack the main function plus any arguments; then you call <a * href="#lua_resume"><code>lua_resume</code></a>, with * <code>narg</code> being the number of arguments. This call returns when * the coroutine suspends or finishes its execution. When it returns, the * stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>, * or all values returned by the body function. <a href="#lua_resume"><code>lua_resume</code></a> * returns <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the * coroutine yields, 0 if the coroutine finishes its execution without * errors, or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>). * In case of errors, the stack is not unwound, so you can use the debug API * over it. The error message is on the top of the stack. To restart a * coroutine, you put on its stack only the values to be passed as results * from <code>yield</code>, and then call <a href="#lua_resume"><code>lua_resume</code></a>. */ public void resume(int narg) { notImplemented(); } /** * Set the value of a table field. <span class="apii">[-1, +0, <em>e</em>]</span> * * <p> * Does the equivalent to <code>t[k] = v</code>, where <code>t</code> * is the value at the given valid index and <code>v</code> is the value * at the top of the stack. * * * <p> * This function pops the value from the stack. As in Lua, this function may * trigger a metamethod for the "newindex" event (see <a * href="#2.8">&sect;2.8</a>). */ public void setfield(int index, LString k) { LTable t = totable(index); LValue v = poplvalue(); t.luaSetTable(this, t, k, v); } /** * Set the value of a global variable. <span class="apii">[-1, +0, * <em>e</em>]</span> * * <p> * Pops a value from the stack and sets it as the new value of global * <code>name</code>. It is defined as a macro: * * <pre> * #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s) * * </pre> */ public void setglobal(String name) { LTable g = this._G; LValue v = poplvalue(); g.luaSetTable(this, g, new LString(name), v); } /** * Set the metatable of a value. <span class="apii">[-1, +0, <em>-</em>]</span> * * <p> * Pops a table from the stack and sets it as the new metatable for the * value at the given acceptable index. */ public void setmetatable(int index) { LTable t = totable(index); LValue v = poplvalue(); t.luaSetMetatable(v); } /** * Set the value of a table for a key. <span class="apii">[-2, +0, * <em>e</em>]</span> * * <p> * Does the equivalent to <code>t[k] = v</code>, where <code>t</code> * is the value at the given valid index, <code>v</code> is the value at * the top of the stack, and <code>k</code> is the value just below the * top. * * * <p> * This function pops both the key and the value from the stack. As in Lua, * this function may trigger a metamethod for the "newindex" event (see <a * href="#2.8">&sect;2.8</a>). */ public void settable(int index) { LTable t = totable(index); LValue v = poplvalue(); LValue k = poplvalue(); t.luaSetTable(this, t, k, v); } /** * Returns the status of the thread <code>L</code>. <span * class="apii">[-0, +0, <em>-</em>]</span> * * * * <p> * The status can be 0 for a normal thread, an error code if the thread * finished its execution with an error, or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> * if the thread is suspended. * */ public void status() { notImplemented(); } /** * Get a thread value from the stack. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Converts the value at the given acceptable index to a Lua thread * (represented as <code>lua_State*</code>). This value must be a thread; * otherwise, the function returns <code>NULL</code>. */ public LuaState tothread(int index) { notImplemented(); return null; } /** * Get a value as a boolean. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Converts the Lua value at the given acceptable index to a C&nbsp;boolean * value (0&nbsp;or&nbsp;1). Like all tests in Lua, <a * href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for * any Lua value different from <b>false</b> and <b>nil</b>; otherwise it * returns 0. It also returns 0 when called with a non-valid index. (If you * want to accept only actual boolean values, use <a href="#lua_isboolean"><code>lua_isboolean</code></a> * to test the value's type.) * */ public boolean toboolean(int index) { return topointer(index).toJavaBoolean(); } /** * Get a value as an int. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Converts the Lua value at the given acceptable index to the signed * integral type <a href="#lua_Integer"><code>lua_Integer</code></a>. * The Lua value must be a number or a string convertible to a number (see * <a href="#2.2.1">&sect;2.2.1</a>); otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> * returns&nbsp;0. * * * <p> * If the number is not an integer, it is truncated in some non-specified * way. */ public int tointeger(int index) { return topointer(index).toJavaInt(); } /** * Get a value as a JavaFunction. * <hr> * <h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3> * <p> * <span class="apii">[-0, +0, <em>-</em>]</span> * * <pre> * lua_CFunction lua_tocfunction (lua_State *L, int index); * </pre> * * <p> * Converts a value at the given acceptable index to a C&nbsp;function. That * value must be a C&nbsp;function; otherwise, returns <code>NULL</code>. */ public LFunction tojavafunction(int index) { return (LFunction) topointer(index); } /** * Gets the value of a string as byte array. <span class="apii">[-0, +0, * <em>m</em>]</span> * * <p> * Converts the Lua value at the given acceptable index to a C&nbsp;string. * If <code>len</code> is not <code>NULL</code>, it also sets * <code>*len</code> with the string length. The Lua value must be a * string or a number; otherwise, the function returns <code>NULL</code>. * If the value is a number, then <a href="#lua_tolstring"><code>lua_tolstring</code></a> * also <em>changes the actual value in the stack to a string</em>. (This * change confuses <a href="#lua_next"><code>lua_next</code></a> when <a * href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to * keys during a table traversal.) * * * <p> * <a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a * fully aligned pointer to a string inside the Lua state. This string * always has a zero ('<code>\0</code>') after its last character (as * in&nbsp;C), but may contain other zeros in its body. Because Lua has * garbage collection, there is no guarantee that the pointer returned by <a * href="#lua_tolstring"><code>lua_tolstring</code></a> will be valid * after the corresponding value is removed from the stack. */ public LString tolstring(int index) { return topointer(index).luaAsString(); } /** * Convert a value to a double. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Converts the Lua value at the given acceptable index to the C&nbsp;type * <a href="#lua_Number"><code>lua_Number</code></a> (see <a * href="#lua_Number"><code>lua_Number</code></a>). The Lua value must * be a number or a string convertible to a number (see <a * href="#2.2.1">&sect;2.2.1</a>); otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> * returns&nbsp;0. * */ public double tonumber(int index) { return topointer(index).toJavaDouble(); } /** * Returns the index of the top element in the stack. <span * class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Because indices start at&nbsp;1, this result is equal to the number of * elements in the stack (and so 0&nbsp;means an empty stack). */ public int gettop() { return top - base; } /** * Set the top of the stack. <span class="apii">[-?, +?, <em>-</em>]</span> * * <p> * Accepts any acceptable index, or&nbsp;0, and sets the stack top to this * index. If the new top is larger than the old one, then the new elements * are filled with <b>nil</b>. If <code>index</code> is&nbsp;0, then all * stack elements are removed. */ public void settop(int nt) { int ant = nt>=0? base+nt: top+nt; if ( ant < base ) throw new IllegalArgumentException("index out of bounds: "+ant ); while ( top < ant ) stack[top++] = LNil.NIL; while ( top > ant ) stack[--top] = null; } /** * Set the top to the base. Equivalent to settop(0) */ public void resettop() { debugAssert( top >= base ); while ( top > base ) stack[--top] = null; } private int index2adr(int index) { // TODO: upvalues? globals? environment? int ai = index>0? base+index-1: top+index; if ( ai < base ) throw new IllegalArgumentException("index out of bounds: "+ai ); return ai; } /** * Get the raw Object at a stack location. <span class="apii">[-0, +0, * <em>-</em>]</span> * * <p> * Converts the value at the given acceptable index to a generic * C&nbsp;pointer (<code>void*</code>). The value may be a userdata, a * table, a thread, or a function; otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> * returns <code>NULL</code>. Different objects will give different * pointers. There is no way to convert the pointer back to its original * value. * * * <p> * Typically this function is used only for debug information. */ public LValue topointer(int index) { int ai = index2adr(index); if ( ai >= top ) return LNil.NIL; return stack[ai]; } /** * Get a stack value as a String. <span class="apii">[-0, +0, <em>m</em>]</span> * * <p> * Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> * with <code>len</code> equal to <code>NULL</code>. */ public String tostring(int index) { return topointer(index).toJavaString(); } /** * Get a value from the stack as a lua table. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Converts the value at the given acceptable index to a Lua table * This value must be a table otherwise, the function returns <code>NIL</code>. */ public LTable totable(int index) { return (LTable) topointer(index); } /** * Get the Object from a userdata value. <span class="apii">[-0, +0, * <em>-</em>]</span> * * <p> * If the value at the given acceptable index is a full userdata, returns * its block address. If the value is a light userdata, returns its pointer. * Otherwise, returns <code>NULL</code>. * */ public Object touserdata(int index) { LValue v = topointer(index); if ( v.luaGetType() != Lua.LUA_TUSERDATA ) return null; return ((LUserData)v).m_instance; } /** * Get the type of a value. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns the type of the value in the given acceptable index, or * <code>LUA_TNONE</code> for a non-valid index (that is, an index to an * "empty" stack position). The types returned by <a href="#lua_type"><code>lua_type</code></a> * are coded by the following constants defined in <code>lua.h</code>: * <code>LUA_TNIL</code>, <code>LUA_TNUMBER</code>, * <code>LUA_TBOOLEAN</code>, <code>LUA_TSTRING</code>, * <code>LUA_TTABLE</code>, <code>LUA_TFUNCTION</code>, * <code>LUA_TUSERDATA</code>, <code>LUA_TTHREAD</code>, and * <code>LUA_TLIGHTUSERDATA</code>. */ public int type(int index) { return topointer(index).luaGetType(); } /** * Get the type name for a value. <span class="apii">[-0, +0, <em>-</em>]</span> * * <p> * Returns the name of the type encoded by the value <code>tp</code>, * which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>. */ public String typename(int index) { return topointer(index).luaGetTypeName().toJavaString(); } /** * Exchange values between threads. <span class="apii">[-?, +?, <em>-</em>]</span> * * <p> * Exchange values between different threads of the <em>same</em> global * state. * * * <p> * This function pops <code>n</code> values from the stack * <code>from</code>, and pushes them onto the stack <code>to</code>. */ public void xmove(LuaState to, int n) { if ( n > 0 ) { to.checkstack(n); LuaState ss = (LuaState)to; System.arraycopy(stack, top-n, ss.stack, ss.top, n); ss.top += n; } } /** * Yields a coroutine. <span class="apii">[-?, +?, <em>-</em>]</span> * * * <p> * This function should only be called as the return expression of a * C&nbsp;function, as follows: * * <pre> * return lua_yield(L, nresults); * </pre> * * <p> * When a C&nbsp;function calls <a href="#lua_yield"><code>lua_yield</code></a> * in that way, the running coroutine suspends its execution, and the call * to <a href="#lua_resume"><code>lua_resume</code></a> that started * this coroutine returns. The parameter <code>nresults</code> is the * number of values from the stack that are passed as results to <a * href="#lua_resume"><code>lua_resume</code></a>. * */ public void yield(int nresults) { notImplemented(); } // ============================= conversion to and from Java boxed types ==================== /** * Push a Java Boolean value, or nil if the value is null. * @param b Boolean value to convert, or null to to nil. */ public void pushboolean(Boolean b) { if ( b == null ) pushnil(); else pushboolean( b.booleanValue() ); } /** * Push a Java Byte value, or nil if the value is null. * @param b Byte value to convert, or null to to nil. */ public void pushinteger(Byte b) { if ( b == null ) pushnil(); else pushinteger( b.byteValue() ); } /** * Push a Java Character value, or nil if the value is null. * @param c Character value to convert, or null to to nil. */ public void pushinteger(Character c) { if ( c == null ) pushnil(); else pushinteger( c.charValue() ); } /** * Push a Java Double as a double, or nil if the value is null. * @param d Double value to convert, or null to to nil. */ public void pushnumber(Double d) { if ( d == null ) pushnil(); else pushnumber( d.doubleValue() ); } /** * Push a Java Float value, or nil if the value is null. * @param f Float value to convert, or null to to nil. */ public void pushnumber(Float f) { if ( f == null ) pushnil(); else pushnumber( f.doubleValue() ); } /** * Push a Java Integer value, or nil if the value is null. * @param i Integer value to convert, or null to to nil. */ public void pushinteger(Integer i) { if ( i == null ) pushnil(); else pushinteger( i.intValue() ); } /** * Push a Java Short value, or nil if the value is null. * @param s Short value to convert, or null to to nil. */ public void pushinteger(Short s) { if ( s == null ) pushnil(); else pushinteger( s.shortValue() ); } /** * Push a Java Long value, or nil if the value is null. * @param l Long value to convert, or null to to nil. */ public void pushnumber(Long l) { if ( l == null ) pushnil(); else pushnumber( l.doubleValue() ); } /** * Push a Java Object as userdata, or nil if the value is null. * @param o Object value to push, or null to to nil. */ public void pushuserdata( Object o ) { if ( o == null ) pushnil(); else newuserdata( o ); } /** * Convert a value to a Java Boolean value, or null if the value is nil. * @param index index of the parameter to convert. * @return Boolean value at the index, or null if the value was not a boolean. */ public Boolean toboxedboolean(int index) { return topointer(index).toJavaBoxedBoolean(); } /** * Convert a value to a Java Byte value, or null if the value is not a number. * @param index index of the parameter to convert. * @return Byte value at the index, or null if the value was not a number. */ public Byte toboxedbyte(int index) { return topointer(index).toJavaBoxedByte(); } /** * Convert a value to a Java Double value, or null if the value is not a number. * @param index index of the parameter to convert. * @return Double value at the index, or null if the value was not a number. */ public Double toboxeddouble(int index) { return topointer(index).toJavaBoxedDouble(); } /** * Convert a value to a Java Float value, or null if the value is not a number. * @param index index of the parameter to convert. * @return Float value at the index, or null if the value was not a boolean. */ public Float toboxedfloat(int index) { return topointer(index).toJavaBoxedFloat(); } /** * Convert a value to a Java Integer value, or null if the value is not a number. * @param index index of the parameter to convert. * @return Integer value at the index, or null if the value was not a number. */ public Integer toboxedinteger(int index) { return topointer(index).toJavaBoxedInteger(); } /** * Convert a value to a Java Long value, or null if the value is nil. * @param index index of the parameter to convert. * @return Long value at the index, or null if the value was not a number. */ public Long toboxedlong(int index) { return topointer(index).toJavaBoxedLong(); } /** * Method to indicate a vm internal error has occurred. * Generally, this is not recoverable, so we convert to * a lua error during production so that the code may recover. */ public static void vmerror(String description) { throw new LuaErrorException( "internal error: "+description ); } }
true
true
public void exec() { if ( cc < 0 ) return; int i, a, b, c, o, n, cb; LValue rkb, rkc, nvarargs, key, val; LValue i0, step, idx, limit, init, table; boolean back, body; LPrototype proto; LClosure newClosure; // reload values from the current call frame // into local variables CallInfo ci = calls[cc]; LClosure cl = ci.closure; LPrototype p = cl.p; int[] code = p.code; LValue[] k = p.k; this.base = ci.base; // loop until a return instruction is processed, // or the vm yields while (true) { debugAssert( ci == calls[cc] ); // sync up top ci.top = top; // allow debug hooks a chance to operate debugHooks( ci.pc ); // advance program counter i = code[ci.pc++]; // get first opcode arg a = LuaState.GETARG_A(i); switch (LuaState.GET_OPCODE(i)) { case LuaState.OP_MOVE: { b = LuaState.GETARG_B(i); this.stack[base + a] = this.stack[base + b]; continue; } case LuaState.OP_LOADK: { b = LuaState.GETARG_Bx(i); this.stack[base + a] = k[b]; continue; } case LuaState.OP_LOADBOOL: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE); if (c != 0) ci.pc++; /* skip next instruction (if C) */ continue; } case LuaState.OP_LOADNIL: { b = LuaState.GETARG_B(i); do { this.stack[base + b] = LNil.NIL; } while ((--b) >= a); continue; } case LuaState.OP_GETUPVAL: { b = LuaState.GETARG_B(i); this.stack[base + a] = cl.upVals[b].getValue(); continue; } case LuaState.OP_GETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; table = cl.env; top = base + a; table.luaGetTable(this, table, key); continue; } case LuaState.OP_GETTABLE: { b = LuaState.GETARG_B(i); key = GETARG_RKC(k, i); table = this.stack[base + b]; top = base + a; table.luaGetTable(this, table, key); continue; } case LuaState.OP_SETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; val = this.stack[base + a]; table = cl.env; table.luaSetTable(this, table, key, val); continue; } case LuaState.OP_SETUPVAL: { b = LuaState.GETARG_B(i); cl.upVals[b].setValue( this.stack[base + a] ); continue; } case LuaState.OP_SETTABLE: { key = GETARG_RKB(k, i); val = GETARG_RKC(k, i); table = this.stack[base + a]; table.luaSetTable(this, table, key, val); continue; } case LuaState.OP_NEWTABLE: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = new LTable(b, c); continue; } case LuaState.OP_SELF: { rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); top = base + a; rkb.luaGetTable(this, rkb, rkc); this.stack[base + a + 1] = rkb; // StkId rb = RB(i); // setobjs2s(L, ra+1, rb); // Protect(luaV_gettable(L, rb, RKC(i), ra)); continue; } case LuaState.OP_ADD: case LuaState.OP_SUB: case LuaState.OP_MUL: case LuaState.OP_DIV: case LuaState.OP_MOD: case LuaState.OP_POW: { o = LuaState.GET_OPCODE(i); rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb); continue; } case LuaState.OP_UNM: { rkb = GETARG_RKB(k, i); this.stack[base + a] = rkb.luaUnaryMinus(); continue; } case LuaState.OP_NOT: { rkb = GETARG_RKB(k, i); this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE : LBoolean.FALSE); continue; } case LuaState.OP_LEN: { rkb = GETARG_RKB(k, i); this.stack[base + a] = LInteger.valueOf( rkb.luaLength() ); continue; } case LuaState.OP_CONCAT: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int numValues = c - b + 1; LString[] strings = new LString[numValues]; for (int j = b, l = 0; j <= c; j++, l++) { LString s = this.stack[base + j].luaAsString(); strings[l] = s; } this.stack[base + a] = LString.concat( strings ); continue; } case LuaState.OP_JMP: { ci.pc += LuaState.GETARG_sBx(i); continue; } case LuaState.OP_EQ: case LuaState.OP_LT: case LuaState.OP_LE: { o = LuaState.GET_OPCODE(i); rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); boolean test = rkc.luaBinCmpUnknown(o, rkb); if (test == (a == 0)) ci.pc++; continue; } case LuaState.OP_TEST: { c = LuaState.GETARG_C(i); if (this.stack[base + a].toJavaBoolean() != (c != 0)) ci.pc++; continue; } case LuaState.OP_TESTSET: { rkb = GETARG_RKB(k, i); c = LuaState.GETARG_C(i); if (rkb.toJavaBoolean() != (c != 0)) ci.pc++; else this.stack[base + a] = rkb; continue; } case LuaState.OP_CALL: { // ra is base of new call frame this.base += a; // number of args b = LuaState.GETARG_B(i); if (b != 0) // else use previous instruction set top top = base + b; // number of return values we need c = LuaState.GETARG_C(i); // make or set up the call this.nresults = c - 1; if (this.stack[base].luaStackCall(this)) return; // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (c > 0) adjustTop(base + c - 1); // restore base base = ci.base; continue; } case LuaState.OP_TAILCALL: { closeUpVals(base); // copy down the frame before calling! // number of args (including the function) b = LuaState.GETARG_B(i); if (b == 0) b = top - (base + a); // copy call + all args, discard current frame System.arraycopy(stack, base + a, stack, ci.resultbase, b); this.base = ci.resultbase; this.top = base + b; this.nresults = ci.nresults; --cc; // make or set up the call try { if (this.stack[base].luaStackCall(this)) { return; } } catch (LuaErrorException e) { // in case of lua error, we need to restore cc so that // the debug can get the correct location where the error // occured. cc++; throw e; } // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (this.nresults >= 0) adjustTop(base + nresults); // force restore of base, etc. return; } case LuaState.OP_RETURN: { // number of return vals to return b = LuaState.GETARG_B(i) - 1; if (b == -1) b = top - (base + a); // close open upvals closeUpVals( base ); // number to copy down System.arraycopy(stack, base + a, stack, ci.resultbase, b); top = ci.resultbase + b; // adjust results to what caller expected if (ci.nresults >= 0) adjustTop(ci.resultbase + ci.nresults); // pop the call stack --cc; // force a reload of the calling context return; } case LuaState.OP_FORLOOP: { i0 = this.stack[base + a]; step = this.stack[base + a + 2]; idx = step.luaBinOpUnknown(Lua.OP_ADD, i0); limit = this.stack[base + a + 1]; back = step.luaBinCmpInteger(Lua.OP_LT, 0); body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit .luaBinCmpUnknown(Lua.OP_LE, idx)); if (body) { this.stack[base + a] = idx; this.stack[base + a + 3] = idx; top = base + a + 3 + 1; ci.pc += LuaState.GETARG_sBx(i); } continue; } case LuaState.OP_FORPREP: { init = this.stack[base + a]; step = this.stack[base + a + 2]; this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init); b = LuaState.GETARG_sBx(i); ci.pc += b; continue; } case LuaState.OP_TFORLOOP: { cb = base + a + 3; /* call base */ base = cb; adjustTop( cb + 3 ); System.arraycopy(this.stack, cb-3, this.stack, cb, 3); // call the iterator c = LuaState.GETARG_C(i); this.nresults = c; if (this.stack[cb].luaStackCall(this)) execute(); base = ci.base; adjustTop( cb + c ); // test for continuation if (this.stack[cb] != LNil.NIL ) { // continue? this.stack[cb-1] = this.stack[cb]; // save control variable } else { ci.pc++; // skip over jump } continue; } case LuaState.OP_SETLIST: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int listBase = base + a; if (b == 0) { b = top - listBase - 1; } if (c == 0) { c = code[ci.pc++]; } table = this.stack[base + a]; for (int index = 1; index <= b; index++) { val = this.stack[listBase + index]; table.luaSetTable(this, table, LInteger.valueOf(index), val); } top = base + a - 1; continue; } case LuaState.OP_CLOSE: { closeUpVals( a ); // close upvals higher in the stack than position a continue; } case LuaState.OP_CLOSURE: { b = LuaState.GETARG_Bx(i); proto = cl.p.p[b]; newClosure = new LClosure(proto, _G); for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) { i = code[ci.pc]; o = LuaState.GET_OPCODE(i); b = LuaState.GETARG_B(i); if (o == LuaState.OP_GETUPVAL) { newClosure.upVals[j] = cl.upVals[b]; } else if (o == LuaState.OP_MOVE) { newClosure.upVals[j] = findUpVal( proto.upvalues[j], base + b ); } else { throw new java.lang.IllegalArgumentException( "bad opcode: " + o); } } this.stack[base + a] = newClosure; continue; } case LuaState.OP_VARARG: { // figure out how many args to copy b = LuaState.GETARG_B(i) - 1; nvarargs = this.stack[base - 1]; n = nvarargs.toJavaInt(); if (b == LuaState.LUA_MULTRET) { b = n; // use entire varargs supplied } // copy args up to call stack area checkstack(a+b); for (int j = 0; j < b; j++) this.stack[base + a + j] = (j < n ? this.stack[base - n + j - 1] : LNil.NIL); top = base + a + b; continue; } } } }
public void exec() { if ( cc < 0 ) return; int i, a, b, c, o, n, cb; LValue rkb, rkc, nvarargs, key, val; LValue i0, step, idx, limit, init, table; boolean back, body; LPrototype proto; LClosure newClosure; // reload values from the current call frame // into local variables CallInfo ci = calls[cc]; LClosure cl = ci.closure; LPrototype p = cl.p; int[] code = p.code; LValue[] k = p.k; this.base = ci.base; // loop until a return instruction is processed, // or the vm yields while (true) { debugAssert( ci == calls[cc] ); // sync up top ci.top = top; // allow debug hooks a chance to operate debugHooks( ci.pc ); // advance program counter i = code[ci.pc++]; // get first opcode arg a = LuaState.GETARG_A(i); switch (LuaState.GET_OPCODE(i)) { case LuaState.OP_MOVE: { b = LuaState.GETARG_B(i); this.stack[base + a] = this.stack[base + b]; continue; } case LuaState.OP_LOADK: { b = LuaState.GETARG_Bx(i); this.stack[base + a] = k[b]; continue; } case LuaState.OP_LOADBOOL: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = (b != 0 ? LBoolean.TRUE : LBoolean.FALSE); if (c != 0) ci.pc++; /* skip next instruction (if C) */ continue; } case LuaState.OP_LOADNIL: { b = LuaState.GETARG_B(i); do { this.stack[base + b] = LNil.NIL; } while ((--b) >= a); continue; } case LuaState.OP_GETUPVAL: { b = LuaState.GETARG_B(i); this.stack[base + a] = cl.upVals[b].getValue(); continue; } case LuaState.OP_GETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; table = cl.env; top = base + a; table.luaGetTable(this, table, key); continue; } case LuaState.OP_GETTABLE: { b = LuaState.GETARG_B(i); key = GETARG_RKC(k, i); table = this.stack[base + b]; top = base + a; table.luaGetTable(this, table, key); continue; } case LuaState.OP_SETGLOBAL: { b = LuaState.GETARG_Bx(i); key = k[b]; val = this.stack[base + a]; table = cl.env; table.luaSetTable(this, table, key, val); continue; } case LuaState.OP_SETUPVAL: { b = LuaState.GETARG_B(i); cl.upVals[b].setValue( this.stack[base + a] ); continue; } case LuaState.OP_SETTABLE: { key = GETARG_RKB(k, i); val = GETARG_RKC(k, i); table = this.stack[base + a]; table.luaSetTable(this, table, key, val); continue; } case LuaState.OP_NEWTABLE: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); this.stack[base + a] = new LTable(b, c); continue; } case LuaState.OP_SELF: { rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); top = base + a; rkb.luaGetTable(this, rkb, rkc); this.stack[base + a + 1] = rkb; // StkId rb = RB(i); // setobjs2s(L, ra+1, rb); // Protect(luaV_gettable(L, rb, RKC(i), ra)); continue; } case LuaState.OP_ADD: case LuaState.OP_SUB: case LuaState.OP_MUL: case LuaState.OP_DIV: case LuaState.OP_MOD: case LuaState.OP_POW: { o = LuaState.GET_OPCODE(i); rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); this.stack[base + a] = rkc.luaBinOpUnknown(o, rkb); continue; } case LuaState.OP_UNM: { rkb = GETARG_RKB(k, i); this.stack[base + a] = rkb.luaUnaryMinus(); continue; } case LuaState.OP_NOT: { rkb = GETARG_RKB(k, i); this.stack[base + a] = (!rkb.toJavaBoolean() ? LBoolean.TRUE : LBoolean.FALSE); continue; } case LuaState.OP_LEN: { rkb = GETARG_RKB(k, i); this.stack[base + a] = LInteger.valueOf( rkb.luaLength() ); continue; } case LuaState.OP_CONCAT: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int numValues = c - b + 1; LString[] strings = new LString[numValues]; for (int j = b, l = 0; j <= c; j++, l++) { LString s = this.stack[base + j].luaAsString(); strings[l] = s; } this.stack[base + a] = LString.concat( strings ); continue; } case LuaState.OP_JMP: { ci.pc += LuaState.GETARG_sBx(i); continue; } case LuaState.OP_EQ: case LuaState.OP_LT: case LuaState.OP_LE: { o = LuaState.GET_OPCODE(i); rkb = GETARG_RKB(k, i); rkc = GETARG_RKC(k, i); boolean test = rkc.luaBinCmpUnknown(o, rkb); if (test == (a == 0)) ci.pc++; continue; } case LuaState.OP_TEST: { c = LuaState.GETARG_C(i); if (this.stack[base + a].toJavaBoolean() != (c != 0)) ci.pc++; continue; } case LuaState.OP_TESTSET: { rkb = GETARG_RKB(k, i); c = LuaState.GETARG_C(i); if (rkb.toJavaBoolean() != (c != 0)) ci.pc++; else this.stack[base + a] = rkb; continue; } case LuaState.OP_CALL: { // ra is base of new call frame this.base += a; // number of args b = LuaState.GETARG_B(i); if (b != 0) // else use previous instruction set top top = base + b; // number of return values we need c = LuaState.GETARG_C(i); // make or set up the call this.nresults = c - 1; if (this.stack[base].luaStackCall(this)) return; // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (c > 0) adjustTop(base + c - 1); // restore base base = ci.base; continue; } case LuaState.OP_TAILCALL: { closeUpVals(base); // copy down the frame before calling! // number of args (including the function) b = LuaState.GETARG_B(i); if (b == 0) b = top - (base + a); // copy call + all args, discard current frame System.arraycopy(stack, base + a, stack, ci.resultbase, b); this.base = ci.resultbase; this.top = base + b; this.nresults = ci.nresults; --cc; // make or set up the call try { if (this.stack[base].luaStackCall(this)) { return; } } catch (LuaErrorException e) { // in case of lua error, we need to restore cc so that // the debug can get the correct location where the error // occured. cc++; throw e; } // adjustTop only for case when call was completed // and number of args > 0. If call completed but // c == 0, leave top to point to end of results if (this.nresults >= 0) adjustTop(base + nresults); // force restore of base, etc. return; } case LuaState.OP_RETURN: { // number of return vals to return b = LuaState.GETARG_B(i) - 1; if (b == -1) b = top - (base + a); // close open upvals closeUpVals( base ); // number to copy down System.arraycopy(stack, base + a, stack, ci.resultbase, b); top = ci.resultbase + b; // adjust results to what caller expected if (ci.nresults >= 0) adjustTop(ci.resultbase + ci.nresults); // pop the call stack --cc; // force a reload of the calling context return; } case LuaState.OP_FORLOOP: { i0 = this.stack[base + a]; step = this.stack[base + a + 2]; idx = step.luaBinOpUnknown(Lua.OP_ADD, i0); limit = this.stack[base + a + 1]; back = step.luaBinCmpInteger(Lua.OP_LT, 0); body = (back ? idx.luaBinCmpUnknown(Lua.OP_LE, limit) : limit .luaBinCmpUnknown(Lua.OP_LE, idx)); if (body) { this.stack[base + a] = idx; this.stack[base + a + 3] = idx; top = base + a + 3 + 1; ci.pc += LuaState.GETARG_sBx(i); } continue; } case LuaState.OP_FORPREP: { init = this.stack[base + a]; step = this.stack[base + a + 2]; this.stack[base + a] = step.luaBinOpUnknown(Lua.OP_SUB, init); b = LuaState.GETARG_sBx(i); ci.pc += b; continue; } case LuaState.OP_TFORLOOP: { cb = base + a + 3; /* call base */ base = cb; adjustTop( cb + 3 ); System.arraycopy(this.stack, cb-3, this.stack, cb, 3); // call the iterator c = LuaState.GETARG_C(i); this.nresults = c; if (this.stack[cb].luaStackCall(this)) execute(); base = ci.base; adjustTop( cb + c ); // test for continuation if (this.stack[cb] != LNil.NIL ) { // continue? this.stack[cb-1] = this.stack[cb]; // save control variable } else { ci.pc++; // skip over jump } continue; } case LuaState.OP_SETLIST: { b = LuaState.GETARG_B(i); c = LuaState.GETARG_C(i); int listBase = base + a; if (b == 0) { b = top - listBase - 1; } if (c == 0) { c = code[ci.pc++]; } table = this.stack[base + a]; for (int index = 1; index <= b; index++) { val = this.stack[listBase + index]; table.luaSetTable(this, table, LInteger.valueOf(index), val); } top = base + a - 1; continue; } case LuaState.OP_CLOSE: { closeUpVals( a ); // close upvals higher in the stack than position a continue; } case LuaState.OP_CLOSURE: { b = LuaState.GETARG_Bx(i); proto = cl.p.p[b]; newClosure = new LClosure(proto, cl.env); for (int j = 0; j < newClosure.upVals.length; j++, ci.pc++) { i = code[ci.pc]; o = LuaState.GET_OPCODE(i); b = LuaState.GETARG_B(i); if (o == LuaState.OP_GETUPVAL) { newClosure.upVals[j] = cl.upVals[b]; } else if (o == LuaState.OP_MOVE) { newClosure.upVals[j] = findUpVal( proto.upvalues[j], base + b ); } else { throw new java.lang.IllegalArgumentException( "bad opcode: " + o); } } this.stack[base + a] = newClosure; continue; } case LuaState.OP_VARARG: { // figure out how many args to copy b = LuaState.GETARG_B(i) - 1; nvarargs = this.stack[base - 1]; n = nvarargs.toJavaInt(); if (b == LuaState.LUA_MULTRET) { b = n; // use entire varargs supplied } // copy args up to call stack area checkstack(a+b); for (int j = 0; j < b; j++) this.stack[base + a + j] = (j < n ? this.stack[base - n + j - 1] : LNil.NIL); top = base + a + b; continue; } } } }
diff --git a/scm-plugin-backend/src/test/java/sonia/scm/plugin/rest/url/GithubCompareUrlBuilderTest.java b/scm-plugin-backend/src/test/java/sonia/scm/plugin/rest/url/GithubCompareUrlBuilderTest.java index fec0cc43c..1c4bd4a46 100644 --- a/scm-plugin-backend/src/test/java/sonia/scm/plugin/rest/url/GithubCompareUrlBuilderTest.java +++ b/scm-plugin-backend/src/test/java/sonia/scm/plugin/rest/url/GithubCompareUrlBuilderTest.java @@ -1,79 +1,79 @@ /** * Copyright (c) 2010, Sebastian Sdorra * 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. Neither the name of SCM-Manager; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.plugin.rest.url; //~--- non-JDK imports -------------------------------------------------------- import org.junit.Test; import static org.junit.Assert.*; /** * * @author Sebastian Sdorra */ public class GithubCompareUrlBuilderTest { /** * Method description * */ @Test public void createCompareUrlTest() { GithubCompareUrlBuilder g = new GithubCompareUrlBuilder(); String url = g.createCompareUrl("https://github.com/sdorra/scm-manager", "1.8", "1.9"); - assertEquals("https://github.com/sdorra/scm-manager/compare/1.8...1.9", + assertEquals("https://github.com/sdorra/scm-manager/compare/1.9...1.8", url); } //~--- get methods ---------------------------------------------------------- /** * Method description * */ @Test public void isCompareableTest() { GithubCompareUrlBuilder g = new GithubCompareUrlBuilder(); assertTrue(g.isCompareable("https://github.com.org/sdorra/scm-manager")); assertFalse(g.isCompareable("https://google.com")); assertFalse(g.isCompareable("https://bitbucket.org/sdorra/scm-manager")); } }
true
true
public void createCompareUrlTest() { GithubCompareUrlBuilder g = new GithubCompareUrlBuilder(); String url = g.createCompareUrl("https://github.com/sdorra/scm-manager", "1.8", "1.9"); assertEquals("https://github.com/sdorra/scm-manager/compare/1.8...1.9", url); }
public void createCompareUrlTest() { GithubCompareUrlBuilder g = new GithubCompareUrlBuilder(); String url = g.createCompareUrl("https://github.com/sdorra/scm-manager", "1.8", "1.9"); assertEquals("https://github.com/sdorra/scm-manager/compare/1.9...1.8", url); }
diff --git a/java/src/playn/java/JavaNet.java b/java/src/playn/java/JavaNet.java index 6cc3272e..f9d6388e 100644 --- a/java/src/playn/java/JavaNet.java +++ b/java/src/playn/java/JavaNet.java @@ -1,94 +1,94 @@ /** * Copyright 2010 The PlayN Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package playn.java; import playn.core.Net; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class JavaNet implements Net { private static final int BUF_SIZE = 4096; public void get(String urlStr, Callback callback) { // TODO: Make this non-blocking so that it doesn't differ from the html // version's behavior. try { URL url = new URL(canonicalizeUrl(urlStr)); InputStream stream = url.openStream(); InputStreamReader reader = new InputStreamReader(stream); callback.success(readFully(reader)); } catch (MalformedURLException e) { callback.failure(e); } catch (IOException e) { callback.failure(e); } } public void post(String urlStr, String data, Callback callback) { // TODO: Make this non-blocking so that it doesn't differ from the html // version's behavior. try { URL url = new URL(canonicalizeUrl(urlStr)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); conn.connect(); conn.getOutputStream().write(data.getBytes("UTF-8")); conn.getOutputStream().close(); - readFully(new InputStreamReader(conn.getInputStream())); + callback.success(readFully(new InputStreamReader(conn.getInputStream()))); conn.disconnect(); } catch (MalformedURLException e) { callback.failure(e); } catch (IOException e) { callback.failure(e); } } // Super-simple url-cleanup: assumes it either starts with "http", or that // it's an absolute path on the current server. private String canonicalizeUrl(String url) { if (!url.startsWith("http")) { return "http://" + server() + url; } return url; } // TODO: Make this specifyable somewhere. private String server() { return "127.0.0.1:8080"; } private String readFully(Reader reader) throws IOException { StringBuffer result = new StringBuffer(); char[] buf = new char[BUF_SIZE]; while (-1 != reader.read(buf)) { result.append(buf); } return result.toString(); } }
true
true
public void post(String urlStr, String data, Callback callback) { // TODO: Make this non-blocking so that it doesn't differ from the html // version's behavior. try { URL url = new URL(canonicalizeUrl(urlStr)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); conn.connect(); conn.getOutputStream().write(data.getBytes("UTF-8")); conn.getOutputStream().close(); readFully(new InputStreamReader(conn.getInputStream())); conn.disconnect(); } catch (MalformedURLException e) { callback.failure(e); } catch (IOException e) { callback.failure(e); } }
public void post(String urlStr, String data, Callback callback) { // TODO: Make this non-blocking so that it doesn't differ from the html // version's behavior. try { URL url = new URL(canonicalizeUrl(urlStr)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); conn.connect(); conn.getOutputStream().write(data.getBytes("UTF-8")); conn.getOutputStream().close(); callback.success(readFully(new InputStreamReader(conn.getInputStream()))); conn.disconnect(); } catch (MalformedURLException e) { callback.failure(e); } catch (IOException e) { callback.failure(e); } }
diff --git a/src/frontend/org/voltdb/RealVoltDB.java b/src/frontend/org/voltdb/RealVoltDB.java index 49939b78d..0c5feaecb 100644 --- a/src/frontend/org/voltdb/RealVoltDB.java +++ b/src/frontend/org/voltdb/RealVoltDB.java @@ -1,1927 +1,1928 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2012 VoltDB Inc. * * VoltDB 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. * * VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.lang.management.ManagementFactory; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URLDecoder; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.zookeeper_voltpatches.CreateMode; import org.apache.zookeeper_voltpatches.KeeperException; import org.apache.zookeeper_voltpatches.ZooDefs.Ids; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltdb.VoltDB.START_ACTION; import org.voltdb.agreement.AgreementSite; import org.voltdb.agreement.ZKUtil; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.Database; import org.voltdb.catalog.Site; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcedureCallback; import org.voltdb.compiler.AsyncCompilerAgent; import org.voltdb.compiler.deploymentfile.DeploymentType; import org.voltdb.compiler.deploymentfile.HeartbeatType; import org.voltdb.compiler.deploymentfile.UsersType; import org.voltdb.dtxn.SimpleDtxnInitiator; import org.voltdb.dtxn.TransactionInitiator; import org.voltdb.export.ExportManager; import org.voltdb.fault.FaultDistributor; import org.voltdb.fault.FaultDistributorInterface; import org.voltdb.fault.NodeFailureFault; import org.voltdb.fault.VoltFault.FaultType; import org.voltdb.licensetool.LicenseApi; import org.voltdb.logging.Level; import org.voltdb.logging.VoltLogger; import org.voltdb.messaging.HostMessenger; import org.voltdb.messaging.Messenger; import org.voltdb.network.VoltNetwork; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.HTTPAdminListener; import org.voltdb.utils.LogKeys; import org.voltdb.utils.MiscUtils; import org.voltdb.utils.PlatformProperties; import org.voltdb.utils.ResponseSampler; import org.voltdb.utils.SystemStatsCollector; import org.voltdb.utils.VoltSampler; public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback { private static final VoltLogger log = new VoltLogger(VoltDB.class.getName()); private static final VoltLogger hostLog = new VoltLogger("HOST"); private static final VoltLogger recoveryLog = new VoltLogger("RECOVERY"); static class RejoinCallback implements ProcedureCallback { ClientResponse response; @Override public synchronized void clientCallback(ClientResponse clientResponse) throws Exception { response = clientResponse; if (response.getStatus() != ClientResponse.SUCCESS) { hostLog.fatal(response.getStatusString()); VoltDB.crashLocalVoltDB(response.getStatusString(), false, null); } VoltTable results[] = clientResponse.getResults(); if (results.length > 0) { VoltTable errors = results[0]; while (errors.advanceRow()) { hostLog.fatal("Host " + errors.getLong(0) + " error: " + errors.getString(1)); } VoltDB.crashLocalVoltDB("No additional info.", false, null); } this.notify(); } public synchronized ClientResponse waitForResponse(int timeout) throws InterruptedException { final long start = System.currentTimeMillis(); while (response == null) { this.wait(timeout); long finish = System.currentTimeMillis(); if (finish - start >= timeout) { return null; } } return response; } } public VoltDB.Configuration m_config = new VoltDB.Configuration(); CatalogContext m_catalogContext; private String m_buildString; private static final String m_defaultVersionString = "2.2.1"; private String m_versionString = m_defaultVersionString; // fields accessed via the singleton HostMessenger m_messenger = null; final ArrayList<ClientInterface> m_clientInterfaces = new ArrayList<ClientInterface>(); final ArrayList<SimpleDtxnInitiator> m_dtxns = new ArrayList<SimpleDtxnInitiator>(); private Map<Integer, ExecutionSite> m_localSites; VoltNetwork m_network = null; AgreementSite m_agreementSite; HTTPAdminListener m_adminListener; private Map<Integer, Thread> m_siteThreads; private ArrayList<ExecutionSiteRunner> m_runners; private ExecutionSite m_currentThreadSite; private StatsAgent m_statsAgent = new StatsAgent(); private AsyncCompilerAgent m_asyncCompilerAgent = new AsyncCompilerAgent(); public AsyncCompilerAgent getAsyncCompilerAgent() { return m_asyncCompilerAgent; } FaultDistributor m_faultManager; Object m_instanceId[]; private PartitionCountStats m_partitionCountStats = null; private IOStats m_ioStats = null; private MemoryStats m_memoryStats = null; private StatsManager m_statsManager = null; ZooKeeper m_zk; private SnapshotCompletionMonitor m_snapshotCompletionMonitor; int m_myHostId; long m_depCRC = -1; String m_serializedCatalog; String m_httpPortExtraLogMessage = null; boolean m_jsonEnabled; CountDownLatch m_hasCatalog; DeploymentType m_deployment; final HashSet<Integer> m_downHosts = new HashSet<Integer>(); final Set<Integer> m_downNonExecSites = new HashSet<Integer>(); //For command log only, will also mark self as faulted final Set<Integer> m_downSites = new HashSet<Integer>(); // Should the execution sites be started in recovery mode // (used for joining a node to an existing cluster) // If CL is enabled this will be set to true // by the CL when the truncation snapshot completes // and this node is viable for replay volatile boolean m_recovering = false; boolean m_replicationActive = false; //Only restrict recovery completion during test static Semaphore m_testBlockRecoveryCompletion = new Semaphore(Integer.MAX_VALUE); private boolean m_executionSitesRecovered = false; private boolean m_agreementSiteRecovered = false; private long m_executionSiteRecoveryFinish; private long m_executionSiteRecoveryTransferred; // the id of the host that is the leader, or the restore planner // says has the catalog int m_hostIdWithStartupCatalog; String m_pathToStartupCatalog; // Synchronize initialize and shutdown. private final Object m_startAndStopLock = new Object(); // Synchronize updates of catalog contexts with context accessors. private final Object m_catalogUpdateLock = new Object(); // add a random number to the sampler output to make it likely to be unique for this process. private final VoltSampler m_sampler = new VoltSampler(10, "sample" + String.valueOf(new Random().nextInt() % 10000) + ".txt"); private final AtomicBoolean m_hasStartedSampler = new AtomicBoolean(false); final VoltDBNodeFailureFaultHandler m_faultHandler = new VoltDBNodeFailureFaultHandler(this); RestoreAgent m_restoreAgent = null; private volatile boolean m_isRunning = false; @Override public boolean recovering() { return m_recovering; } private final long m_recoveryStartTime = System.currentTimeMillis(); CommandLog m_commandLog; private volatile OperationMode m_mode = OperationMode.INITIALIZING; private OperationMode m_startMode = null; private ReplicationRole m_replicationRole = null; volatile String m_localMetadata = ""; final Map<Integer, String> m_clusterMetadata = Collections.synchronizedMap(new HashMap<Integer, String>()); private ExecutorService m_computationService; // methods accessed via the singleton @Override public void startSampler() { if (m_hasStartedSampler.compareAndSet(false, true)) { m_sampler.start(); } } HeartbeatThread heartbeatThread; private ScheduledThreadPoolExecutor m_periodicWorkThread; // The configured license api: use to decide enterprise/cvommunity edition feature enablement LicenseApi m_licenseApi; @Override public LicenseApi getLicenseApi() { return m_licenseApi; } /** * Initialize all the global components, then initialize all the m_sites. */ @Override public void initialize(VoltDB.Configuration config) { // set the mode first thing m_mode = OperationMode.INITIALIZING; synchronized(m_startAndStopLock) { hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null); m_config = config; // set a bunch of things to null/empty/new for tests // which reusue the process m_clientInterfaces.clear(); m_dtxns.clear(); m_agreementSite = null; m_adminListener = null; m_commandLog = new DummyCommandLog(); m_deployment = null; m_messenger = null; m_statsAgent = new StatsAgent(); m_asyncCompilerAgent = new AsyncCompilerAgent(); m_faultManager = null; m_instanceId = null; m_zk = null; m_snapshotCompletionMonitor = null; m_catalogContext = null; m_partitionCountStats = null; m_ioStats = null; m_memoryStats = null; m_statsManager = null; m_restoreAgent = null; m_hasCatalog = new CountDownLatch(1); m_hostIdWithStartupCatalog = 0; m_pathToStartupCatalog = m_config.m_pathToCatalog; + m_replicationRole = m_config.m_replicationRole; m_replicationActive = false; m_computationService = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), new ThreadFactory() { private int threadIndex = 0; @Override public synchronized Thread newThread(Runnable r) { Thread t = new Thread(null, r, "Computation service thread - " + threadIndex++, 131072); t.setDaemon(true); return t; } }); // determine if this is a rejoining node // (used for license check and later the actual rejoin) boolean isRejoin = config.m_rejoinToHostAndPort != null; // Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported try { System.setOut(new PrintStream(System.out, true, "UTF-8")); System.setErr(new PrintStream(System.err, true, "UTF-8")); } catch (UnsupportedEncodingException e) { hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting."); System.exit(-1); } // check that this is a 64 bit VM if (System.getProperty("java.vm.name").contains("64") == false) { hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting."); System.exit(-1); } m_snapshotCompletionMonitor = new SnapshotCompletionMonitor(); readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition"); // start up the response sampler if asked to by setting the env var // VOLTDB_RESPONSE_SAMPLE_PATH to a valid path ResponseSampler.initializeIfEnabled(); readDeploymentAndCreateStarterCatalogContext(); // Create the thread pool here. It's needed by buildClusterMesh() final int availableProcessors = Runtime.getRuntime().availableProcessors(); int poolSize = 1; if (availableProcessors > 4) { poolSize = 2; } m_periodicWorkThread = MiscUtils.getScheduledThreadPoolExecutor("Periodic Work", poolSize, 1024 * 128); buildClusterMesh(isRejoin); m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense); if (m_licenseApi == null) { VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " + "See previous log message for details.", false, null); } // do the many init tasks in the Inits class Inits inits = new Inits(this, 1); inits.doInitializationWork(); // set up site structure m_localSites = Collections.synchronizedMap(new HashMap<Integer, ExecutionSite>()); m_siteThreads = Collections.synchronizedMap(new HashMap<Integer, Thread>()); m_runners = new ArrayList<ExecutionSiteRunner>(); if (config.m_backend.isIPC) { int eeCount = 0; for (Site site : m_catalogContext.siteTracker.getUpSites()) { if (site.getIsexec() && m_myHostId == Integer.parseInt(site.getHost().getTypeName())) { eeCount++; } } if (config.m_ipcPorts.size() != eeCount) { hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() + " backend ports when " + eeCount + " are required"); System.exit(-1); } } collectLocalNetworkMetadata(); m_clusterMetadata.put(m_messenger.getHostId(), getLocalMetadata()); /* * Create execution sites runners (and threads) for all exec sites except the first one. * This allows the sites to be set up in the thread that will end up running them. * Cache the first Site from the catalog and only do the setup once the other threads have been started. */ Site siteForThisThread = null; m_currentThreadSite = null; for (Site site : m_catalogContext.siteTracker.getUpSites()) { int sitesHostId = Integer.parseInt(site.getHost().getTypeName()); int siteId = Integer.parseInt(site.getTypeName()); // start a local site if (sitesHostId == m_myHostId) { if (site.getIsexec()) { if (siteForThisThread == null) { siteForThisThread = site; } else { ExecutionSiteRunner runner = new ExecutionSiteRunner( siteId, m_catalogContext, m_serializedCatalog, m_recovering, m_replicationActive, m_downHosts, hostLog); m_runners.add(runner); Thread runnerThread = new Thread(runner, "Site " + siteId); runnerThread.start(); log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { siteId }, null); m_siteThreads.put(siteId, runnerThread); } } } } /* * Now that the runners have been started and are doing setup of the other sites in parallel * this thread can set up its own execution site. */ int siteId = Integer.parseInt(siteForThisThread.getTypeName()); ExecutionSite siteObj = new ExecutionSite(VoltDB.instance(), VoltDB.instance().getMessenger().createMailbox( siteId, VoltDB.DTXN_MAILBOX_ID, true), siteId, m_serializedCatalog, null, m_recovering, m_replicationActive, m_downHosts, m_catalogContext.m_transactionId); m_localSites.put(Integer.parseInt(siteForThisThread.getTypeName()), siteObj); m_currentThreadSite = siteObj; /* * Stop and wait for the runners to finish setting up and then put * the constructed ExecutionSites in the local site map. */ for (ExecutionSiteRunner runner : m_runners) { synchronized (runner) { if (!runner.m_isSiteCreated) { try { runner.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } m_localSites.put(runner.m_siteId, runner.m_siteObj); } } // Create the client interface int portOffset = 0; for (Site site : m_catalogContext.siteTracker.getUpSites()) { int sitesHostId = Integer.parseInt(site.getHost().getTypeName()); int currSiteId = Integer.parseInt(site.getTypeName()); // create DTXN and CI for each local non-EE site if ((sitesHostId == m_myHostId) && (site.getIsexec() == false)) { SimpleDtxnInitiator initiator = new SimpleDtxnInitiator( m_catalogContext, m_messenger, m_myHostId, currSiteId, site.getInitiatorid(), m_config.m_timestampTestingSalt); ClientInterface ci = ClientInterface.create(m_network, m_messenger, m_catalogContext, m_replicationRole, initiator, m_catalogContext.numberOfNodes, currSiteId, site.getInitiatorid(), config.m_port + portOffset, config.m_adminPort + portOffset, m_config.m_timestampTestingSalt); portOffset += 2; m_clientInterfaces.add(ci); m_dtxns.add(initiator); } } m_partitionCountStats = new PartitionCountStats( m_catalogContext.numberOfPartitions); m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT, 0, m_partitionCountStats); m_ioStats = new IOStats(); m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS, 0, m_ioStats); m_memoryStats = new MemoryStats(); m_statsAgent.registerStatsSource(SysProcSelector.MEMORY, 0, m_memoryStats); // Create the statistics manager and register it to JMX registry m_statsManager = null; try { final Class<?> statsManagerClass = Class.forName("org.voltdb.management.JMXStatsManager"); m_statsManager = (StatsManager)statsManagerClass.newInstance(); m_statsManager.initialize(new ArrayList<Integer>(m_localSites.keySet())); } catch (Exception e) {} // in most cases, this work will already be done in inits code, // but not for rejoin, so double-make-sure it's done here startNetworkAndCreateZKClient(); try { m_snapshotCompletionMonitor.init(m_zk); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e); } if (m_commandLog != null && isRejoin) { m_commandLog.initForRejoin( m_catalogContext, Long.MIN_VALUE, m_messenger.getDiscoveredFaultSequenceNumber(), m_downSites); } // tell other booting nodes that this node is ready. Primary purpose is to publish a hostname m_messenger.sendReadyMessage(); // only needs to be done if this is an initial cluster startup, not a rejoin if (config.m_rejoinToHostAndPort == null) { // wait for all nodes to be ready m_messenger.waitForAllHostsToBeReady(); } heartbeatThread = new HeartbeatThread(m_clientInterfaces); heartbeatThread.start(); schedulePeriodicWorks(); // print out a bunch of useful system info logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled); int k = m_catalogContext.numberOfExecSites / m_catalogContext.numberOfPartitions; if (k == 1) { hostLog.warn("Running without redundancy (k=0) is not recommended for production use."); } assert(m_clientInterfaces.size() > 0); ClientInterface ci = m_clientInterfaces.get(0); ci.initializeSnapshotDaemon(); // set additional restore agent stuff TransactionInitiator initiator = m_dtxns.get(0); if (m_restoreAgent != null) { m_restoreAgent.setCatalogContext(m_catalogContext); m_restoreAgent.setInitiator(initiator); } } } /** * Schedule all the periodic works */ private void schedulePeriodicWorks() { // JMX stats broadcast scheduleWork(new Runnable() { @Override public void run() { m_statsManager.sendNotification(); } }, 0, StatsManager.POLL_INTERVAL, TimeUnit.MILLISECONDS); // small stats samples scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(false, false); } }, 0, 5, TimeUnit.SECONDS); // medium stats samples scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, false); } }, 0, 1, TimeUnit.MINUTES); // large stats samples scheduleWork(new Runnable() { @Override public void run() { SystemStatsCollector.asyncSampleSystemNow(true, true); } }, 0, 6, TimeUnit.MINUTES); } void readDeploymentAndCreateStarterCatalogContext() { m_deployment = CatalogUtil.parseDeployment(m_config.m_pathToDeployment); // wasn't a valid xml deployment file if (m_deployment == null) { VoltDB.crashLocalVoltDB("Not a valid XML deployment file at URL: " + m_config.m_pathToDeployment, false, null); } // note the heatbeats are specified in seconds in xml, but ms internally HeartbeatType hbt = m_deployment.getHeartbeat(); if (hbt != null) m_config.m_deadHostTimeoutMS = hbt.getTimeout() * 1000; // create a dummy catalog to load deployment info into Catalog catalog = new Catalog(); Cluster cluster = catalog.getClusters().add("cluster"); Database db = cluster.getDatabases().add("database"); // create groups as needed for users if (m_deployment.getUsers() != null) { for (UsersType.User user : m_deployment.getUsers().getUser()) { String groupsCSV = user.getGroups(); String[] groups = groupsCSV.split(","); for (String group : groups) { if (db.getGroups().get(group) == null) { db.getGroups().add(group); } } } } long depCRC = CatalogUtil.compileDeploymentAndGetCRC(catalog, m_deployment, true, true); assert(depCRC != -1); m_catalogContext = new CatalogContext(0, catalog, null, depCRC, 0, -1); } void collectLocalNetworkMetadata() { boolean threw = false; JSONStringer stringer = new JSONStringer(); try { stringer.object(); stringer.key("interfaces").array(); /* * If no interface was specified, do a ton of work * to identify all ipv4 or ipv6 interfaces and * marshal them into JSON. Always put the ipv4 address first * so that the export client will use it */ if (m_config.m_externalInterface.equals("")) { LinkedList<NetworkInterface> interfaces = new LinkedList<NetworkInterface>(); try { Enumeration<NetworkInterface> intfEnum = NetworkInterface.getNetworkInterfaces(); while (intfEnum.hasMoreElements()) { NetworkInterface intf = intfEnum.nextElement(); if (intf.isLoopback() || !intf.isUp()) { continue; } interfaces.offer(intf); } } catch (SocketException e) { throw new RuntimeException(e); } if (interfaces.isEmpty()) { stringer.value("localhost"); } else { boolean addedIp = false; while (!interfaces.isEmpty()) { NetworkInterface intf = interfaces.poll(); Enumeration<InetAddress> inetAddrs = intf.getInetAddresses(); Inet6Address inet6addr = null; Inet4Address inet4addr = null; while (inetAddrs.hasMoreElements()) { InetAddress addr = inetAddrs.nextElement(); if (addr instanceof Inet6Address) { inet6addr = (Inet6Address)addr; if (inet6addr.isLinkLocalAddress()) { inet6addr = null; } } else if (addr instanceof Inet4Address) { inet4addr = (Inet4Address)addr; } } if (inet4addr != null) { stringer.value(inet4addr.getHostAddress()); addedIp = true; } if (inet6addr != null) { stringer.value(inet6addr.getHostAddress()); addedIp = true; } } if (!addedIp) { stringer.value("localhost"); } } } else { stringer.value(m_config.m_externalInterface); } } catch (Exception e) { threw = true; hostLog.warn("Error while collecting data about local network interfaces", e); } try { if (threw) { stringer = new JSONStringer(); stringer.object(); stringer.key("interfaces").array(); stringer.value("localhost"); stringer.endArray(); } else { stringer.endArray(); } stringer.key("clientPort").value(m_config.m_port); stringer.key("adminPort").value(m_config.m_adminPort); stringer.key("httpPort").value(m_config.m_httpPort); stringer.key("drPort").value(m_config.m_drAgentPortStart); stringer.endObject(); JSONObject obj = new JSONObject(stringer.toString()); // possibly atomic swap from null to realz m_localMetadata = obj.toString(4); } catch (Exception e) { hostLog.warn("Failed to collect data about lcoal network interfaces", e); } } void startNetworkAndCreateZKClient() { // don't set this up twice if (m_zk != null) return; // Start running the socket handlers hostLog.l7dlog(Level.INFO, LogKeys.host_VoltDB_StartingNetwork.name(), new Object[] { m_network.threadPoolSize }, null); m_network.start(); try { m_agreementSite.waitForRecovery(); m_zk = org.voltdb.agreement.ZKUtil.getClient(m_config.m_zkInterface, 60 * 1000); if (m_zk == null) { throw new Exception("Timed out trying to connect local ZooKeeper instance"); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to create a ZK client", true, e); } } void buildClusterMesh(boolean isRejoin) { // start the fault manager first m_faultManager = new FaultDistributor(this); // Install a handler for NODE_FAILURE faults to update the catalog // This should be the first handler to run when a node fails m_faultManager.registerFaultHandler(NodeFailureFault.NODE_FAILURE_CATALOG, m_faultHandler, FaultType.NODE_FAILURE); if (!m_faultManager.testPartitionDetectionDirectory( m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"))) { VoltDB.crashLocalVoltDB("No additional info", false, null); } // Prepare the network socket manager for work m_network = new VoltNetwork(m_periodicWorkThread); String leaderAddress = m_config.m_leader; int numberOfNodes = m_deployment.getCluster().getHostcount(); long depCRC = CatalogUtil.getDeploymentCRC(m_config.m_pathToDeployment); if (!isRejoin) { // Create the intra-cluster mesh InetAddress leader = null; try { leader = InetAddress.getByName(leaderAddress); } catch (UnknownHostException ex) { hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_CouldNotRetrieveLeaderAddress.name(), new Object[] { leaderAddress }, null); VoltDB.crashLocalVoltDB("No additional info", false, null); } // ensure at least one host (catalog compiler should check this too if (numberOfNodes <= 0) { hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_InvalidHostCount.name(), new Object[] { numberOfNodes }, null); VoltDB.crashLocalVoltDB("No additional info", false, null); } hostLog.l7dlog( Level.TRACE, LogKeys.host_VoltDB_CreatingVoltDB.name(), new Object[] { numberOfNodes, leader }, null); hostLog.info(String.format("Beginning inter-node communication on port %d.", m_config.m_internalPort)); m_messenger = new HostMessenger(m_network, leader, numberOfNodes, 0, depCRC, hostLog); Object retval[] = m_messenger.waitForGroupJoin(); m_instanceId = new Object[] { retval[0], retval[1] }; } else { // rejoin case m_downHosts.addAll(rejoinExistingMesh(numberOfNodes, depCRC)); } // Use the host messenger's hostId. m_myHostId = m_messenger.getHostId(); if (isRejoin) { /** * Whatever hosts were reported as being down on rejoin should * be reported to the fault manager so that the fault can be distributed. * The execution sites were informed on construction so they don't have * to go through the agreement process. */ for (Integer downHost : m_downHosts) { m_downNonExecSites.addAll(m_catalogContext.siteTracker.getNonExecSitesForHost(downHost)); m_downSites.addAll(m_catalogContext.siteTracker.getNonExecSitesForHost(downHost)); m_faultManager.reportFault( new NodeFailureFault( downHost, m_catalogContext.siteTracker.getNonExecSitesForHost(downHost), "UNKNOWN")); } try { m_faultHandler.m_waitForFaultReported.acquire(m_downHosts.size()); } catch (InterruptedException e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } ExecutionSite.recoveringSiteCount.set( m_catalogContext.siteTracker.getLiveExecutionSitesForHost(m_messenger.getHostId()).size()); m_downSites.addAll(m_catalogContext.siteTracker.getAllSitesForHost(m_messenger.getHostId())); } m_catalogContext.m_transactionId = m_messenger.getDiscoveredCatalogTxnId(); assert(m_messenger.getDiscoveredCatalogTxnId() != 0); } HashSet<Integer> rejoinExistingMesh(int numberOfNodes, long deploymentCRC) { // sensible defaults (sorta) String rejoinHostCredentialString = null; String rejoinHostAddressString = null; //Client interface port of node that will receive @Rejoin invocation int rejoinPort = m_config.m_port; String rejoinHost = null; String rejoinUser = null; String rejoinPass = null; // this will cause the ExecutionSites to start in recovering mode m_recovering = true; // split a "user:pass@host:port" string into "user:pass" and "host:port" int atSignIndex = m_config.m_rejoinToHostAndPort.indexOf('@'); if (atSignIndex == -1) { rejoinHostAddressString = m_config.m_rejoinToHostAndPort; } else { rejoinHostCredentialString = m_config.m_rejoinToHostAndPort.substring(0, atSignIndex).trim(); rejoinHostAddressString = m_config.m_rejoinToHostAndPort.substring(atSignIndex + 1).trim(); } int colonIndex = -1; // split a "user:pass" string into "user" and "pass" if (rejoinHostCredentialString != null) { colonIndex = rejoinHostCredentialString.indexOf(':'); if (colonIndex == -1) { rejoinUser = rejoinHostCredentialString.trim(); System.out.print("password: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { rejoinPass = br.readLine(); } catch (IOException e) { hostLog.error("Unable to read passord for rejoining credentials from console."); System.exit(-1); } } else { rejoinUser = rejoinHostCredentialString.substring(0, colonIndex).trim(); rejoinPass = rejoinHostCredentialString.substring(colonIndex + 1).trim(); } } // split a "host:port" string into "host" and "port" colonIndex = rejoinHostAddressString.indexOf(':'); if (colonIndex == -1) { rejoinHost = rejoinHostAddressString.trim(); // note rejoinPort has a default } else { rejoinHost = rejoinHostAddressString.substring(0, colonIndex).trim(); rejoinPort = Integer.parseInt(rejoinHostAddressString.substring(colonIndex + 1).trim()); } hostLog.info(String.format("Inter-node communication will use port %d.", m_config.m_internalPort)); ServerSocketChannel listener = null; try { listener = ServerSocketChannel.open(); listener.socket().bind(new InetSocketAddress(m_config.m_internalPort)); } catch (IOException e) { hostLog.error("Problem opening listening rejoin socket: " + e.getMessage()); System.exit(-1); } m_messenger = new HostMessenger(m_network, listener, numberOfNodes, 0, deploymentCRC, hostLog); // make empty strings null if ((rejoinUser != null) && (rejoinUser.length() == 0)) rejoinUser = null; if ((rejoinPass != null) && (rejoinPass.length() == 0)) rejoinPass = null; // URL Decode so usernames/passwords can contain weird stuff try { if (rejoinUser != null) rejoinUser = URLDecoder.decode(rejoinUser, "UTF-8"); if (rejoinPass != null) rejoinPass = URLDecoder.decode(rejoinPass, "UTF-8"); } catch (UnsupportedEncodingException e) { hostLog.error("Problem URL-decoding credentials for rejoin authentication: " + e.getMessage()); System.exit(-1); } ClientConfig clientConfig = new ClientConfig(rejoinUser, rejoinPass); Client client = ClientFactory.createClient(clientConfig); ClientResponse response = null; RejoinCallback rcb = new RejoinCallback() { }; try { client.createConnection(rejoinHost, rejoinPort); InetSocketAddress inetsockaddr = new InetSocketAddress(rejoinHost, rejoinPort); SocketChannel socket = SocketChannel.open(inetsockaddr); String ip_addr = socket.socket().getLocalAddress().getHostAddress(); socket.close(); m_config.m_selectedRejoinInterface = m_config.m_internalInterface.isEmpty() ? ip_addr : m_config.m_internalInterface; client.callProcedure( rcb, "@Rejoin", m_config.m_selectedRejoinInterface, m_config.m_internalPort); } catch (Exception e) { VoltDB.crashLocalVoltDB("Problem connecting client to " + m_config.m_selectedRejoinInterface + ":" + m_config.m_internalPort + ". " + e.getMessage(), false, e); } Object retval[] = m_messenger.waitForGroupJoin(60 * 1000); m_instanceId = new Object[] { retval[0], retval[1] }; @SuppressWarnings("unchecked") HashSet<Integer> downHosts = (HashSet<Integer>)retval[2]; hostLog.info("Down hosts are " + downHosts.toString()); try { //Callback validates response asynchronously. Just wait for the response before continuing. //Timeout because a failure might result in the response not coming. response = rcb.waitForResponse(3000); if (response == null) { VoltDB.crashLocalVoltDB("Recovering node timed out rejoining", false, null); } } catch (InterruptedException e) { VoltDB.crashLocalVoltDB("Interrupted while attempting to rejoin cluster", false, e); } return downHosts; } void logDebuggingInfo(int adminPort, int httpPort, String httpPortExtraLogMessage, boolean jsonEnabled) { String startAction = m_config.m_startAction.toString(); String startActionLog = "Database start action is " + (startAction.substring(0, 1).toUpperCase() + startAction.substring(1).toLowerCase()) + "."; if (m_config.m_startAction == START_ACTION.START) { startActionLog += " Will create a new database if there is nothing to recover from."; } hostLog.info(startActionLog); // print out awesome network stuff hostLog.info(String.format("Listening for native wire protocol clients on port %d.", m_config.m_port)); hostLog.info(String.format("Listening for admin wire protocol clients on port %d.", adminPort)); if (m_startMode == OperationMode.PAUSED) { hostLog.info(String.format("Started in admin mode. Clients on port %d will be rejected in admin mode.", m_config.m_port)); } if (m_replicationRole == ReplicationRole.REPLICA) { hostLog.info("Started as " + m_replicationRole.toString().toLowerCase() + " cluster. " + "Clients can only call read-only procedures."); } if (httpPortExtraLogMessage != null) { hostLog.info(httpPortExtraLogMessage); } if (httpPort != -1) { hostLog.info(String.format("Local machine HTTP monitoring is listening on port %d.", httpPort)); } else { hostLog.info(String.format("Local machine HTTP monitoring is disabled.")); } if (jsonEnabled) { hostLog.info(String.format("Json API over HTTP enabled at path /api/1.0/, listening on port %d.", httpPort)); } else { hostLog.info("Json API disabled."); } // replay command line args that we can see List<String> iargs = ManagementFactory.getRuntimeMXBean().getInputArguments(); StringBuilder sb = new StringBuilder("Available JVM arguments:"); for (String iarg : iargs) sb.append(" ").append(iarg); if (iargs.size() > 0) hostLog.info(sb.toString()); else hostLog.info("No JVM command line args known."); // java heap size long javamaxheapmem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax(); javamaxheapmem /= (1024 * 1024); hostLog.info(String.format("Maximum usable Java heap set to %d mb.", javamaxheapmem)); m_catalogContext.logDebuggingInfoFromCatalog(); // print out a bunch of useful system info PlatformProperties pp = PlatformProperties.getPlatformProperties(); String[] lines = pp.toLogLines().split("\n"); for (String line : lines) { hostLog.info(line.trim()); } /* * Publish our cluster metadata, and then retrieve the metadata * for the rest of the cluster */ try { m_zk.create( "/cluster_metadata", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new ZKUtil.StringCallback(), null); m_zk.create( "/cluster_metadata/" + m_messenger.getHostId(), getLocalMetadata().getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new ZKUtil.StringCallback(), null); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error creating \"/cluster_metadata\" node in ZK", true, e); } /* * Spin and attempt to retrieve cluster metadata for all nodes in the cluster. */ HashSet<Integer> metadataToRetrieve = new HashSet<Integer>(m_catalogContext.siteTracker.getAllLiveHosts()); metadataToRetrieve.remove(m_messenger.getHostId()); while (!metadataToRetrieve.isEmpty()) { Map<Integer, ZKUtil.ByteArrayCallback> callbacks = new HashMap<Integer, ZKUtil.ByteArrayCallback>(); for (Integer hostId : metadataToRetrieve) { ZKUtil.ByteArrayCallback cb = new ZKUtil.ByteArrayCallback(); m_zk.getData("/cluster_metadata/" + hostId, false, cb, null); callbacks.put(hostId, cb); } for (Map.Entry<Integer, ZKUtil.ByteArrayCallback> entry : callbacks.entrySet()) { try { ZKUtil.ByteArrayCallback cb = entry.getValue(); Integer hostId = entry.getKey(); m_clusterMetadata.put(hostId, new String(cb.getData(), "UTF-8")); metadataToRetrieve.remove(hostId); } catch (KeeperException.NoNodeException e) {} catch (Exception e) { VoltDB.crashLocalVoltDB("Error retrieving cluster metadata", true, e); } } } // print out cluster membership hostLog.info("About to list cluster interfaces for all nodes with format [ip1 ip2 ... ipN] client-port:admin-port:http-port"); for (int hostId : m_catalogContext.siteTracker.getAllLiveHosts()) { if (hostId == m_messenger.getHostId()) { hostLog.info( String.format( " Host id: %d with interfaces: %s [SELF]", hostId, MiscUtils.formatHostMetadataFromJSON(getLocalMetadata()))); } else { String hostMeta = m_clusterMetadata.get(hostId); hostLog.info( String.format( " Host id: %d with interfaces: %s [PEER]", hostId, MiscUtils.formatHostMetadataFromJSON(hostMeta))); } } } @Override public void writeNetworkCatalogToTmp(byte[] catalogBytes) { hostLog.debug("Got a catalog!"); hostLog.debug(String.format("Got %d catalog bytes", catalogBytes.length)); String prefix = String.format("catalog-host%d-", m_myHostId); try { File catalogFile = File.createTempFile(prefix, ".jar"); catalogFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(catalogFile); fos.write(catalogBytes); fos.flush(); fos.close(); m_config.m_pathToCatalog = catalogFile.getCanonicalPath(); } catch (IOException e) { VoltDB.crashGlobalVoltDB("Failed to write a temp catalog.", true, e); } // anyone waiting for a catalog can now zoom zoom m_hasCatalog.countDown(); } public static String[] extractBuildInfo() { StringBuilder sb = new StringBuilder(64); String buildString = "VoltDB"; String versionString = m_defaultVersionString; byte b = -1; try { InputStream buildstringStream = ClassLoader.getSystemResourceAsStream("buildstring.txt"); if (buildstringStream == null) { throw new RuntimeException("Unreadable or missing buildstring.txt file."); } while ((b = (byte) buildstringStream.read()) != -1) { sb.append((char)b); } sb.append("\n"); String parts[] = sb.toString().split(" ", 2); if (parts.length != 2) { throw new RuntimeException("Invalid buildstring.txt file."); } versionString = parts[0].trim(); buildString = parts[1].trim(); } catch (Exception ignored) { try { InputStream buildstringStream = new FileInputStream("version.txt"); while ((b = (byte) buildstringStream.read()) != -1) { sb.append((char)b); } versionString = sb.toString().trim(); } catch (Exception ignored2) { log.l7dlog( Level.ERROR, LogKeys.org_voltdb_VoltDB_FailedToRetrieveBuildString.name(), null); } } return new String[] { versionString, buildString }; } @Override public void readBuildInfo(String editionTag) { String buildInfo[] = extractBuildInfo(); m_versionString = buildInfo[0]; m_buildString = buildInfo[1]; hostLog.info(String.format("Build: %s %s %s", m_versionString, m_buildString, editionTag)); } /** * Start all the site's event loops. That's it. */ @Override public void run() { // start the separate EE threads for (ExecutionSiteRunner r : m_runners) { synchronized (r) { assert(r.m_isSiteCreated) : "Site should already have been created by ExecutionSiteRunner"; r.notifyAll(); } } if (m_restoreAgent != null) { // start restore process m_restoreAgent.restore(); } else { onRestoreCompletion(Long.MIN_VALUE); } // start one site in the current thread Thread.currentThread().setName("ExecutionSiteAndVoltDB"); m_isRunning = true; try { m_currentThreadSite.run(); } catch (Throwable t) { String errmsg = "ExecutionSite: " + m_currentThreadSite.m_siteId + " encountered an " + "unexpected error and will die, taking this VoltDB node down."; VoltDB.crashLocalVoltDB(errmsg, true, t); } } /** * Try to shut everything down so they system is ready to call * initialize again. * @param mainSiteThread The thread that m_inititalized the VoltDB or * null if called from that thread. */ @Override public void shutdown(Thread mainSiteThread) throws InterruptedException { synchronized(m_startAndStopLock) { m_mode = OperationMode.SHUTTINGDOWN; m_executionSitesRecovered = false; m_agreementSiteRecovered = false; m_snapshotCompletionMonitor.shutdown(); m_periodicWorkThread.shutdown(); heartbeatThread.interrupt(); heartbeatThread.join(); // Things are going pear-shaped, tell the fault distributor to // shut its fat mouth m_faultManager.shutDown(); if (m_hasStartedSampler.get()) { m_sampler.setShouldStop(); m_sampler.join(); } // shutdown the web monitoring / json if (m_adminListener != null) m_adminListener.stop(); // shut down the client interface for (ClientInterface ci : m_clientInterfaces) { ci.shutdown(); } // shut down Export and its connectors. ExportManager.instance().shutdown(); // tell all m_sites to stop their runloops if (m_localSites != null) { for (ExecutionSite site : m_localSites.values()) site.startShutdown(); } // try to join all threads but the main one // probably want to check if one of these is the current thread if (m_siteThreads != null) { for (Thread siteThread : m_siteThreads.values()) { if (Thread.currentThread().equals(siteThread) == false) { // don't interrupt here. the site will start shutdown when // it sees the shutdown flag set. siteThread.join(); } } } // try to join the main thread (possibly this one) if (mainSiteThread != null) { if (Thread.currentThread().equals(mainSiteThread) == false) { // don't interrupt here. the site will start shutdown when // it sees the shutdown flag set. mainSiteThread.join(); } } // help the gc along m_localSites = null; m_currentThreadSite = null; m_siteThreads = null; m_runners = null; Thread t = new Thread() { @Override public void run() { try { m_zk.close(); } catch (InterruptedException e) { } } }; t.start(); m_agreementSite.shutdown(); t.join(); m_agreementSite = null; // shut down the network/messaging stuff // Close the host messenger first, which should close down all of // the ForeignHost sockets cleanly if (m_messenger != null) { m_messenger.shutdown(); } if (m_network != null) { //Synchronized so the interruption won't interrupt the network thread //while it is waiting for the executor service to shutdown m_network.shutdown(); } m_messenger = null; m_network = null; //Also for test code that expects a fresh stats agent if (m_statsAgent != null) { m_statsAgent.shutdown(); m_statsAgent = null; } if (m_asyncCompilerAgent != null) { m_asyncCompilerAgent.shutdown(); m_asyncCompilerAgent = null; } // The network iterates this list. Clear it after network's done. m_clientInterfaces.clear(); ExportManager.instance().shutdown(); m_computationService.shutdown(); m_computationService.awaitTermination(1, TimeUnit.DAYS); m_computationService = null; // probably unnecessary System.gc(); m_isRunning = false; } } /** Last transaction ID at which the rejoin commit took place. * Also, use the intrinsic lock to safeguard access from multiple * execution site threads */ private static Long lastNodeRejoinPrepare_txnId = 0L; @Override public synchronized String doRejoinPrepare( long currentTxnId, int rejoinHostId, String rejoiningHostname, int portToConnect, Set<Integer> liveHosts) { // another site already did this work. if (currentTxnId == lastNodeRejoinPrepare_txnId) { return null; } else if (currentTxnId < lastNodeRejoinPrepare_txnId) { throw new RuntimeException("Trying to rejoin (prepare) with an old transaction."); } // get the contents of the catalog for the rejoining node byte[] catalogBytes = null; try { catalogBytes = m_catalogContext.getCatalogJarBytes(); } catch (IOException e) { throw new RuntimeException(e); } // connect to the joining node, build a foreign host InetSocketAddress addr = new InetSocketAddress(rejoiningHostname, portToConnect); String ipAddr = addr.getAddress().toString(); recoveryLog.info("Rejoining node with host id: " + rejoinHostId + ", hostname: " + ipAddr + " at txnid: " + currentTxnId); lastNodeRejoinPrepare_txnId = currentTxnId; HostMessenger messenger = getHostMessenger(); // connect to the joining node, build a foreign host try { messenger.rejoinForeignHostPrepare(rejoinHostId, addr, 0, m_catalogContext.deploymentCRC, liveHosts, m_commandLog.getFaultSequenceNumber(), m_catalogContext.catalogVersion, m_catalogContext.m_transactionId, catalogBytes); return null; } catch (Exception e) { //e.printStackTrace(); return e.getMessage() == null ? e.getClass().getName() : e.getMessage(); } } /** Last transaction ID at which the rejoin commit took place. * Also, use the intrinsic lock to safeguard access from multiple * execution site threads */ private static Long lastNodeRejoinFinish_txnId = 0L; @Override public synchronized String doRejoinCommitOrRollback(long currentTxnId, boolean commit) { if (m_recovering) { VoltDB.crashLocalVoltDB("Concurrent rejoins are not supported", false, null); } // another site already did this work. if (currentTxnId == lastNodeRejoinFinish_txnId) { return null; } else if (currentTxnId < lastNodeRejoinFinish_txnId) { throw new RuntimeException("Trying to rejoin (commit/rollback) with an old transaction."); } recoveryLog.info("Rejoining commit node with txnid: " + currentTxnId + " lastNodeRejoinFinish_txnId: " + lastNodeRejoinFinish_txnId); HostMessenger messenger = getHostMessenger(); if (commit) { // put the foreign host into the set of active ones HostMessenger.JoiningNodeInfo joinNodeInfo = messenger.rejoinForeignHostCommit(); m_faultManager.reportFaultCleared( new NodeFailureFault( joinNodeInfo.hostId, m_catalogContext.siteTracker.getNonExecSitesForHost(joinNodeInfo.hostId), joinNodeInfo.hostName)); try { m_faultHandler.m_waitForFaultClear.acquire(); } catch (InterruptedException e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e);//shouldn't happen } ArrayList<Integer> rejoiningSiteIds = new ArrayList<Integer>(); ArrayList<Integer> rejoiningExecSiteIds = new ArrayList<Integer>(); Cluster cluster = m_catalogContext.catalog.getClusters().get("cluster"); for (Site site : cluster.getSites()) { int siteId = Integer.parseInt(site.getTypeName()); int hostId = Integer.parseInt(site.getHost().getTypeName()); if (hostId == joinNodeInfo.hostId) { assert(site.getIsup() == false); rejoiningSiteIds.add(siteId); if (site.getIsexec() == true) { rejoiningExecSiteIds.add(siteId); } } } assert(rejoiningSiteIds.size() > 0); // get a string list of all the new sites StringBuilder newIds = new StringBuilder(); for (int siteId : rejoiningSiteIds) { newIds.append(siteId).append(","); } // trim the last comma newIds.setLength(newIds.length() - 1); // change the catalog to reflect this change hostLog.info("Host joined, host id: " + joinNodeInfo.hostId + " hostname: " + joinNodeInfo.hostName); hostLog.info(" Adding sites to cluster: " + newIds); StringBuilder sb = new StringBuilder(); for (int siteId : rejoiningSiteIds) { sb.append("set "); String site_path = VoltDB.instance().getCatalogContext().catalog. getClusters().get("cluster").getSites(). get(Integer.toString(siteId)).getPath(); sb.append(site_path).append(" ").append("isUp true"); sb.append("\n"); } String catalogDiffCommands = sb.toString(); clusterUpdate(catalogDiffCommands); // update the SafteyState in the initiators for (SimpleDtxnInitiator dtxn : m_dtxns) { dtxn.notifyExecutionSiteRejoin(rejoiningExecSiteIds); } //Notify the export manager the cluster topology has changed ExportManager.instance().notifyOfClusterTopologyChange(); } else { // clean up any connections made messenger.rejoinForeignHostRollback(); } recoveryLog.info("Setting lastNodeRejoinFinish_txnId to: " + currentTxnId); lastNodeRejoinFinish_txnId = currentTxnId; return null; } /** Last transaction ID at which the logging config updated. * Also, use the intrinsic lock to safeguard access from multiple * execution site threads */ private static Long lastLogUpdate_txnId = 0L; @Override public void logUpdate(String xmlConfig, long currentTxnId) { synchronized(lastLogUpdate_txnId) { // another site already did this work. if (currentTxnId == lastLogUpdate_txnId) { return; } else if (currentTxnId < lastLogUpdate_txnId) { throw new RuntimeException("Trying to update logging config with an old transaction."); } System.out.println("Updating RealVoltDB logging config from txnid: " + lastLogUpdate_txnId + " to " + currentTxnId); lastLogUpdate_txnId = currentTxnId; VoltLogger.configure(xmlConfig); } } /** Struct to associate a context with a counter of served sites */ private static class ContextTracker { ContextTracker(CatalogContext context) { m_dispensedSites = 1; m_context = context; } long m_dispensedSites; CatalogContext m_context; } /** Associate transaction ids to contexts */ private final HashMap<Long, ContextTracker>m_txnIdToContextTracker = new HashMap<Long, ContextTracker>(); @Override public CatalogContext catalogUpdate( String diffCommands, byte[] newCatalogBytes, int expectedCatalogVersion, long currentTxnId, long deploymentCRC) { synchronized(m_catalogUpdateLock) { // A site is catching up with catalog updates if (currentTxnId <= m_catalogContext.m_transactionId && !m_txnIdToContextTracker.isEmpty()) { ContextTracker contextTracker = m_txnIdToContextTracker.get(currentTxnId); // This 'dispensed' concept is a little crazy fragile. Maybe it would be better // to keep a rolling N catalogs? Or perhaps to keep catalogs for N minutes? Open // to opinions here. contextTracker.m_dispensedSites++; int ttlsites = m_catalogContext.siteTracker.getLiveExecutionSitesForHost(m_messenger.getHostId()).size(); if (contextTracker.m_dispensedSites == ttlsites) { m_txnIdToContextTracker.remove(currentTxnId); } return contextTracker.m_context; } else if (m_catalogContext.catalogVersion != expectedCatalogVersion) { throw new RuntimeException("Trying to update main catalog context with diff " + "commands generated for an out-of date catalog. Expected catalog version: " + expectedCatalogVersion + " does not match actual version: " + m_catalogContext.catalogVersion); } // 0. A new catalog! Update the global context and the context tracker m_catalogContext = m_catalogContext.update(currentTxnId, newCatalogBytes, diffCommands, true, deploymentCRC); m_txnIdToContextTracker.put(currentTxnId, new ContextTracker(m_catalogContext)); m_catalogContext.logDebuggingInfoFromCatalog(); // 1. update the export manager. ExportManager.instance().updateCatalog(m_catalogContext); // 2. update client interface (asynchronously) // CI in turn updates the planner thread. for (ClientInterface ci : m_clientInterfaces) { ci.notifyOfCatalogUpdate(); } // 3. update HTTPClientInterface (asynchronously) // This purges cached connection state so that access with // stale auth info is prevented. if (m_adminListener != null) { m_adminListener.notifyOfCatalogUpdate(); } return m_catalogContext; } } @Override public void clusterUpdate(String diffCommands) { synchronized(m_catalogUpdateLock) { //Reuse the txn id since this doesn't change schema/procs/export m_catalogContext = m_catalogContext.update(m_catalogContext.m_transactionId, null, diffCommands, false, -1); } for (ClientInterface ci : m_clientInterfaces) { ci.notifyOfCatalogUpdate(); } } @Override public ZooKeeper getZK() { return m_zk; } @Override public VoltDB.Configuration getConfig() { return m_config; } @Override public String getBuildString() { return m_buildString; } @Override public String getVersionString() { return m_versionString; } @Override public Messenger getMessenger() { return m_messenger; } @Override public HostMessenger getHostMessenger() { return m_messenger; } @Override public ArrayList<ClientInterface> getClientInterfaces() { return m_clientInterfaces; } @Override public Map<Integer, ExecutionSite> getLocalSites() { return m_localSites; } @Override public VoltNetwork getNetwork() { return m_network; } @Override public StatsAgent getStatsAgent() { return m_statsAgent; } @Override public MemoryStats getMemoryStatsSource() { return m_memoryStats; } @Override public FaultDistributorInterface getFaultDistributor() { return m_faultManager; } @Override public CatalogContext getCatalogContext() { synchronized(m_catalogUpdateLock) { return m_catalogContext; } } /** * Tells if the VoltDB is running. m_isRunning needs to be set to true * when the run() method is called, and set to false when shutting down. * * @return true if the VoltDB is running. */ @Override public boolean isRunning() { return m_isRunning; } /** * Debugging function - creates a record of the current state of the system. * @param out PrintStream to write report to. */ public void createRuntimeReport(PrintStream out) { // This function may be running in its own thread. out.print("MIME-Version: 1.0\n"); out.print("Content-type: multipart/mixed; boundary=\"reportsection\""); out.print("\n\n--reportsection\nContent-Type: text/plain\n\nClientInterface Report\n"); for (ClientInterface ci : getClientInterfaces()) { out.print(ci.toString() + "\n"); } out.print("\n\n--reportsection\nContent-Type: text/plain\n\nLocalSite Report\n"); for(ExecutionSite es : getLocalSites().values()) { out.print(es.toString() + "\n"); } out.print("\n\n--reportsection--"); } @Override public boolean ignoreCrash() { return false; } @Override public Object[] getInstanceId() { return m_instanceId; } @Override public BackendTarget getBackendTargetType() { return m_config.m_backend; } @Override public synchronized void onExecutionSiteRecoveryCompletion(long transferred) { m_executionSiteRecoveryFinish = System.currentTimeMillis(); m_executionSiteRecoveryTransferred = transferred; m_executionSitesRecovered = true; onRecoveryCompletion(); } private void onRecoveryCompletion() { if (!m_executionSitesRecovered || !m_agreementSiteRecovered) { return; } try { m_testBlockRecoveryCompletion.acquire(); } catch (InterruptedException e) {} final long delta = ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000); final long megabytes = m_executionSiteRecoveryTransferred / (1024 * 1024); final double megabytesPerSecond = megabytes / ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000.0); for (ClientInterface intf : getClientInterfaces()) { intf.mayActivateSnapshotDaemon(); } hostLog.info( "Node data recovery completed after " + delta + " seconds with " + megabytes + " megabytes transferred at a rate of " + megabytesPerSecond + " megabytes/sec"); try { boolean logRecoveryCompleted = false; try { m_zk.create("/unfaulted_hosts", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException e) {} if (getCommandLog().getClass().getName().equals("org.voltdb.CommandLogImpl")) { try { m_zk.create("/request_truncation_snapshot", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException e) {} } else { logRecoveryCompleted = true; } ByteBuffer txnIdBuffer = ByteBuffer.allocate(8); txnIdBuffer.putLong(TransactionIdManager.makeIdFromComponents(System.currentTimeMillis(), 0, 1)); m_zk.create( "/unfaulted_hosts/" + m_messenger.getHostId(), txnIdBuffer.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); if (logRecoveryCompleted) { m_recovering = false; hostLog.info("Node recovery completed"); } } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to log host recovery completion to ZK", true, e); } hostLog.info("Logging host recovery completion to ZK"); } @Override public CommandLog getCommandLog() { return m_commandLog; } @Override public OperationMode getMode() { return m_mode; } @Override public void setMode(OperationMode mode) { if (m_mode != mode) { if (mode == OperationMode.PAUSED) { hostLog.info("Server is entering admin mode and pausing."); } else if (m_mode == OperationMode.PAUSED) { hostLog.info("Server is exiting admin mode and resuming operation."); } } m_mode = mode; } @Override public void setStartMode(OperationMode mode) { m_startMode = mode; } @Override public OperationMode getStartMode() { return m_startMode; } @Override public void setReplicationRole(ReplicationRole role) { if (m_replicationRole == null) { m_replicationRole = role; } else if (role != ReplicationRole.REPLICA && m_replicationRole == ReplicationRole.REPLICA) { hostLog.info("Promoting replication role from replica to master."); m_replicationRole = role; for (ClientInterface ci : m_clientInterfaces) { ci.setReplicationRole(m_replicationRole); } } } @Override public ReplicationRole getReplicationRole() { return m_replicationRole; } /** * Get the metadata map for the wholes cluster. * Note: this may include failed nodes so check for live ones * and filter this if needed. * * Metadata is currently a JSON object */ @Override public Map<Integer, String> getClusterMetadataMap() { return m_clusterMetadata; } /** * Metadata is a JSON object */ @Override public String getLocalMetadata() { return m_localMetadata; } @Override public void onRestoreCompletion(long txnId) { /* * Command log is already initialized if this is a rejoin */ if ((m_commandLog != null) && (m_commandLog.needsInitialization())) { // Initialize command logger m_commandLog.init(m_catalogContext, txnId); } /* * Enable the initiator to send normal heartbeats and accept client * connections */ for (SimpleDtxnInitiator dtxn : m_dtxns) { dtxn.setSendHeartbeats(true); } for (ClientInterface ci : m_clientInterfaces) { try { ci.startAcceptingConnections(); } catch (IOException e) { hostLog.l7dlog(Level.FATAL, LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(), e); VoltDB.crashLocalVoltDB("No additional info", false, null); } } // Start listening on the DR ports prepareReplication(); if (m_startMode != null) { m_mode = m_startMode; } else { // Shouldn't be here, but to be safe m_mode = OperationMode.RUNNING; } hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_ServerCompletedInitialization.name(), null); } @Override public synchronized void onAgreementSiteRecoveryCompletion() { m_agreementSiteRecovered = true; onRecoveryCompletion(); } @Override public AgreementSite getAgreementSite() { return m_agreementSite; } @Override public SnapshotCompletionMonitor getSnapshotCompletionMonitor() { return m_snapshotCompletionMonitor; } @Override public synchronized void recoveryComplete() { m_recovering = false; hostLog.info("Node recovery completed"); } @Override public ScheduledFuture<?> scheduleWork(Runnable work, long initialDelay, long delay, TimeUnit unit) { if (delay > 0) { return m_periodicWorkThread.scheduleWithFixedDelay(work, initialDelay, delay, unit); } else { return m_periodicWorkThread.schedule(work, initialDelay, unit); } } @Override public ExecutorService getComputationService() { return m_computationService; } private void prepareReplication() { if (m_localSites != null && !m_localSites.isEmpty()) { // get any site and start the DR server, it's static ExecutionSite site = m_localSites.values().iterator().next(); site.getPartitionDRGateway().start(); } } @Override public void setReplicationActive(boolean active) { if (m_replicationActive != active) { m_replicationActive = active; if (m_localSites != null) { for (ExecutionSite s : m_localSites.values()) { s.getPartitionDRGateway().setActive(active); } } } } @Override public boolean getReplicationActive() { return m_replicationActive; } }
true
true
public void initialize(VoltDB.Configuration config) { // set the mode first thing m_mode = OperationMode.INITIALIZING; synchronized(m_startAndStopLock) { hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null); m_config = config; // set a bunch of things to null/empty/new for tests // which reusue the process m_clientInterfaces.clear(); m_dtxns.clear(); m_agreementSite = null; m_adminListener = null; m_commandLog = new DummyCommandLog(); m_deployment = null; m_messenger = null; m_statsAgent = new StatsAgent(); m_asyncCompilerAgent = new AsyncCompilerAgent(); m_faultManager = null; m_instanceId = null; m_zk = null; m_snapshotCompletionMonitor = null; m_catalogContext = null; m_partitionCountStats = null; m_ioStats = null; m_memoryStats = null; m_statsManager = null; m_restoreAgent = null; m_hasCatalog = new CountDownLatch(1); m_hostIdWithStartupCatalog = 0; m_pathToStartupCatalog = m_config.m_pathToCatalog; m_replicationActive = false; m_computationService = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), new ThreadFactory() { private int threadIndex = 0; @Override public synchronized Thread newThread(Runnable r) { Thread t = new Thread(null, r, "Computation service thread - " + threadIndex++, 131072); t.setDaemon(true); return t; } }); // determine if this is a rejoining node // (used for license check and later the actual rejoin) boolean isRejoin = config.m_rejoinToHostAndPort != null; // Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported try { System.setOut(new PrintStream(System.out, true, "UTF-8")); System.setErr(new PrintStream(System.err, true, "UTF-8")); } catch (UnsupportedEncodingException e) { hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting."); System.exit(-1); } // check that this is a 64 bit VM if (System.getProperty("java.vm.name").contains("64") == false) { hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting."); System.exit(-1); } m_snapshotCompletionMonitor = new SnapshotCompletionMonitor(); readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition"); // start up the response sampler if asked to by setting the env var // VOLTDB_RESPONSE_SAMPLE_PATH to a valid path ResponseSampler.initializeIfEnabled(); readDeploymentAndCreateStarterCatalogContext(); // Create the thread pool here. It's needed by buildClusterMesh() final int availableProcessors = Runtime.getRuntime().availableProcessors(); int poolSize = 1; if (availableProcessors > 4) { poolSize = 2; } m_periodicWorkThread = MiscUtils.getScheduledThreadPoolExecutor("Periodic Work", poolSize, 1024 * 128); buildClusterMesh(isRejoin); m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense); if (m_licenseApi == null) { VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " + "See previous log message for details.", false, null); } // do the many init tasks in the Inits class Inits inits = new Inits(this, 1); inits.doInitializationWork(); // set up site structure m_localSites = Collections.synchronizedMap(new HashMap<Integer, ExecutionSite>()); m_siteThreads = Collections.synchronizedMap(new HashMap<Integer, Thread>()); m_runners = new ArrayList<ExecutionSiteRunner>(); if (config.m_backend.isIPC) { int eeCount = 0; for (Site site : m_catalogContext.siteTracker.getUpSites()) { if (site.getIsexec() && m_myHostId == Integer.parseInt(site.getHost().getTypeName())) { eeCount++; } } if (config.m_ipcPorts.size() != eeCount) { hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() + " backend ports when " + eeCount + " are required"); System.exit(-1); } } collectLocalNetworkMetadata(); m_clusterMetadata.put(m_messenger.getHostId(), getLocalMetadata()); /* * Create execution sites runners (and threads) for all exec sites except the first one. * This allows the sites to be set up in the thread that will end up running them. * Cache the first Site from the catalog and only do the setup once the other threads have been started. */ Site siteForThisThread = null; m_currentThreadSite = null; for (Site site : m_catalogContext.siteTracker.getUpSites()) { int sitesHostId = Integer.parseInt(site.getHost().getTypeName()); int siteId = Integer.parseInt(site.getTypeName()); // start a local site if (sitesHostId == m_myHostId) { if (site.getIsexec()) { if (siteForThisThread == null) { siteForThisThread = site; } else { ExecutionSiteRunner runner = new ExecutionSiteRunner( siteId, m_catalogContext, m_serializedCatalog, m_recovering, m_replicationActive, m_downHosts, hostLog); m_runners.add(runner); Thread runnerThread = new Thread(runner, "Site " + siteId); runnerThread.start(); log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { siteId }, null); m_siteThreads.put(siteId, runnerThread); } } } } /* * Now that the runners have been started and are doing setup of the other sites in parallel * this thread can set up its own execution site. */ int siteId = Integer.parseInt(siteForThisThread.getTypeName()); ExecutionSite siteObj = new ExecutionSite(VoltDB.instance(), VoltDB.instance().getMessenger().createMailbox( siteId, VoltDB.DTXN_MAILBOX_ID, true), siteId, m_serializedCatalog, null, m_recovering, m_replicationActive, m_downHosts, m_catalogContext.m_transactionId); m_localSites.put(Integer.parseInt(siteForThisThread.getTypeName()), siteObj); m_currentThreadSite = siteObj; /* * Stop and wait for the runners to finish setting up and then put * the constructed ExecutionSites in the local site map. */ for (ExecutionSiteRunner runner : m_runners) { synchronized (runner) { if (!runner.m_isSiteCreated) { try { runner.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } m_localSites.put(runner.m_siteId, runner.m_siteObj); } } // Create the client interface int portOffset = 0; for (Site site : m_catalogContext.siteTracker.getUpSites()) { int sitesHostId = Integer.parseInt(site.getHost().getTypeName()); int currSiteId = Integer.parseInt(site.getTypeName()); // create DTXN and CI for each local non-EE site if ((sitesHostId == m_myHostId) && (site.getIsexec() == false)) { SimpleDtxnInitiator initiator = new SimpleDtxnInitiator( m_catalogContext, m_messenger, m_myHostId, currSiteId, site.getInitiatorid(), m_config.m_timestampTestingSalt); ClientInterface ci = ClientInterface.create(m_network, m_messenger, m_catalogContext, m_replicationRole, initiator, m_catalogContext.numberOfNodes, currSiteId, site.getInitiatorid(), config.m_port + portOffset, config.m_adminPort + portOffset, m_config.m_timestampTestingSalt); portOffset += 2; m_clientInterfaces.add(ci); m_dtxns.add(initiator); } } m_partitionCountStats = new PartitionCountStats( m_catalogContext.numberOfPartitions); m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT, 0, m_partitionCountStats); m_ioStats = new IOStats(); m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS, 0, m_ioStats); m_memoryStats = new MemoryStats(); m_statsAgent.registerStatsSource(SysProcSelector.MEMORY, 0, m_memoryStats); // Create the statistics manager and register it to JMX registry m_statsManager = null; try { final Class<?> statsManagerClass = Class.forName("org.voltdb.management.JMXStatsManager"); m_statsManager = (StatsManager)statsManagerClass.newInstance(); m_statsManager.initialize(new ArrayList<Integer>(m_localSites.keySet())); } catch (Exception e) {} // in most cases, this work will already be done in inits code, // but not for rejoin, so double-make-sure it's done here startNetworkAndCreateZKClient(); try { m_snapshotCompletionMonitor.init(m_zk); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e); } if (m_commandLog != null && isRejoin) { m_commandLog.initForRejoin( m_catalogContext, Long.MIN_VALUE, m_messenger.getDiscoveredFaultSequenceNumber(), m_downSites); } // tell other booting nodes that this node is ready. Primary purpose is to publish a hostname m_messenger.sendReadyMessage(); // only needs to be done if this is an initial cluster startup, not a rejoin if (config.m_rejoinToHostAndPort == null) { // wait for all nodes to be ready m_messenger.waitForAllHostsToBeReady(); } heartbeatThread = new HeartbeatThread(m_clientInterfaces); heartbeatThread.start(); schedulePeriodicWorks(); // print out a bunch of useful system info logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled); int k = m_catalogContext.numberOfExecSites / m_catalogContext.numberOfPartitions; if (k == 1) { hostLog.warn("Running without redundancy (k=0) is not recommended for production use."); } assert(m_clientInterfaces.size() > 0); ClientInterface ci = m_clientInterfaces.get(0); ci.initializeSnapshotDaemon(); // set additional restore agent stuff TransactionInitiator initiator = m_dtxns.get(0); if (m_restoreAgent != null) { m_restoreAgent.setCatalogContext(m_catalogContext); m_restoreAgent.setInitiator(initiator); } } }
public void initialize(VoltDB.Configuration config) { // set the mode first thing m_mode = OperationMode.INITIALIZING; synchronized(m_startAndStopLock) { hostLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null); m_config = config; // set a bunch of things to null/empty/new for tests // which reusue the process m_clientInterfaces.clear(); m_dtxns.clear(); m_agreementSite = null; m_adminListener = null; m_commandLog = new DummyCommandLog(); m_deployment = null; m_messenger = null; m_statsAgent = new StatsAgent(); m_asyncCompilerAgent = new AsyncCompilerAgent(); m_faultManager = null; m_instanceId = null; m_zk = null; m_snapshotCompletionMonitor = null; m_catalogContext = null; m_partitionCountStats = null; m_ioStats = null; m_memoryStats = null; m_statsManager = null; m_restoreAgent = null; m_hasCatalog = new CountDownLatch(1); m_hostIdWithStartupCatalog = 0; m_pathToStartupCatalog = m_config.m_pathToCatalog; m_replicationRole = m_config.m_replicationRole; m_replicationActive = false; m_computationService = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), new ThreadFactory() { private int threadIndex = 0; @Override public synchronized Thread newThread(Runnable r) { Thread t = new Thread(null, r, "Computation service thread - " + threadIndex++, 131072); t.setDaemon(true); return t; } }); // determine if this is a rejoining node // (used for license check and later the actual rejoin) boolean isRejoin = config.m_rejoinToHostAndPort != null; // Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported try { System.setOut(new PrintStream(System.out, true, "UTF-8")); System.setErr(new PrintStream(System.err, true, "UTF-8")); } catch (UnsupportedEncodingException e) { hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting."); System.exit(-1); } // check that this is a 64 bit VM if (System.getProperty("java.vm.name").contains("64") == false) { hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting."); System.exit(-1); } m_snapshotCompletionMonitor = new SnapshotCompletionMonitor(); readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition"); // start up the response sampler if asked to by setting the env var // VOLTDB_RESPONSE_SAMPLE_PATH to a valid path ResponseSampler.initializeIfEnabled(); readDeploymentAndCreateStarterCatalogContext(); // Create the thread pool here. It's needed by buildClusterMesh() final int availableProcessors = Runtime.getRuntime().availableProcessors(); int poolSize = 1; if (availableProcessors > 4) { poolSize = 2; } m_periodicWorkThread = MiscUtils.getScheduledThreadPoolExecutor("Periodic Work", poolSize, 1024 * 128); buildClusterMesh(isRejoin); m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense); if (m_licenseApi == null) { VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " + "See previous log message for details.", false, null); } // do the many init tasks in the Inits class Inits inits = new Inits(this, 1); inits.doInitializationWork(); // set up site structure m_localSites = Collections.synchronizedMap(new HashMap<Integer, ExecutionSite>()); m_siteThreads = Collections.synchronizedMap(new HashMap<Integer, Thread>()); m_runners = new ArrayList<ExecutionSiteRunner>(); if (config.m_backend.isIPC) { int eeCount = 0; for (Site site : m_catalogContext.siteTracker.getUpSites()) { if (site.getIsexec() && m_myHostId == Integer.parseInt(site.getHost().getTypeName())) { eeCount++; } } if (config.m_ipcPorts.size() != eeCount) { hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() + " backend ports when " + eeCount + " are required"); System.exit(-1); } } collectLocalNetworkMetadata(); m_clusterMetadata.put(m_messenger.getHostId(), getLocalMetadata()); /* * Create execution sites runners (and threads) for all exec sites except the first one. * This allows the sites to be set up in the thread that will end up running them. * Cache the first Site from the catalog and only do the setup once the other threads have been started. */ Site siteForThisThread = null; m_currentThreadSite = null; for (Site site : m_catalogContext.siteTracker.getUpSites()) { int sitesHostId = Integer.parseInt(site.getHost().getTypeName()); int siteId = Integer.parseInt(site.getTypeName()); // start a local site if (sitesHostId == m_myHostId) { if (site.getIsexec()) { if (siteForThisThread == null) { siteForThisThread = site; } else { ExecutionSiteRunner runner = new ExecutionSiteRunner( siteId, m_catalogContext, m_serializedCatalog, m_recovering, m_replicationActive, m_downHosts, hostLog); m_runners.add(runner); Thread runnerThread = new Thread(runner, "Site " + siteId); runnerThread.start(); log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { siteId }, null); m_siteThreads.put(siteId, runnerThread); } } } } /* * Now that the runners have been started and are doing setup of the other sites in parallel * this thread can set up its own execution site. */ int siteId = Integer.parseInt(siteForThisThread.getTypeName()); ExecutionSite siteObj = new ExecutionSite(VoltDB.instance(), VoltDB.instance().getMessenger().createMailbox( siteId, VoltDB.DTXN_MAILBOX_ID, true), siteId, m_serializedCatalog, null, m_recovering, m_replicationActive, m_downHosts, m_catalogContext.m_transactionId); m_localSites.put(Integer.parseInt(siteForThisThread.getTypeName()), siteObj); m_currentThreadSite = siteObj; /* * Stop and wait for the runners to finish setting up and then put * the constructed ExecutionSites in the local site map. */ for (ExecutionSiteRunner runner : m_runners) { synchronized (runner) { if (!runner.m_isSiteCreated) { try { runner.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } m_localSites.put(runner.m_siteId, runner.m_siteObj); } } // Create the client interface int portOffset = 0; for (Site site : m_catalogContext.siteTracker.getUpSites()) { int sitesHostId = Integer.parseInt(site.getHost().getTypeName()); int currSiteId = Integer.parseInt(site.getTypeName()); // create DTXN and CI for each local non-EE site if ((sitesHostId == m_myHostId) && (site.getIsexec() == false)) { SimpleDtxnInitiator initiator = new SimpleDtxnInitiator( m_catalogContext, m_messenger, m_myHostId, currSiteId, site.getInitiatorid(), m_config.m_timestampTestingSalt); ClientInterface ci = ClientInterface.create(m_network, m_messenger, m_catalogContext, m_replicationRole, initiator, m_catalogContext.numberOfNodes, currSiteId, site.getInitiatorid(), config.m_port + portOffset, config.m_adminPort + portOffset, m_config.m_timestampTestingSalt); portOffset += 2; m_clientInterfaces.add(ci); m_dtxns.add(initiator); } } m_partitionCountStats = new PartitionCountStats( m_catalogContext.numberOfPartitions); m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT, 0, m_partitionCountStats); m_ioStats = new IOStats(); m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS, 0, m_ioStats); m_memoryStats = new MemoryStats(); m_statsAgent.registerStatsSource(SysProcSelector.MEMORY, 0, m_memoryStats); // Create the statistics manager and register it to JMX registry m_statsManager = null; try { final Class<?> statsManagerClass = Class.forName("org.voltdb.management.JMXStatsManager"); m_statsManager = (StatsManager)statsManagerClass.newInstance(); m_statsManager.initialize(new ArrayList<Integer>(m_localSites.keySet())); } catch (Exception e) {} // in most cases, this work will already be done in inits code, // but not for rejoin, so double-make-sure it's done here startNetworkAndCreateZKClient(); try { m_snapshotCompletionMonitor.init(m_zk); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e); } if (m_commandLog != null && isRejoin) { m_commandLog.initForRejoin( m_catalogContext, Long.MIN_VALUE, m_messenger.getDiscoveredFaultSequenceNumber(), m_downSites); } // tell other booting nodes that this node is ready. Primary purpose is to publish a hostname m_messenger.sendReadyMessage(); // only needs to be done if this is an initial cluster startup, not a rejoin if (config.m_rejoinToHostAndPort == null) { // wait for all nodes to be ready m_messenger.waitForAllHostsToBeReady(); } heartbeatThread = new HeartbeatThread(m_clientInterfaces); heartbeatThread.start(); schedulePeriodicWorks(); // print out a bunch of useful system info logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled); int k = m_catalogContext.numberOfExecSites / m_catalogContext.numberOfPartitions; if (k == 1) { hostLog.warn("Running without redundancy (k=0) is not recommended for production use."); } assert(m_clientInterfaces.size() > 0); ClientInterface ci = m_clientInterfaces.get(0); ci.initializeSnapshotDaemon(); // set additional restore agent stuff TransactionInitiator initiator = m_dtxns.get(0); if (m_restoreAgent != null) { m_restoreAgent.setCatalogContext(m_catalogContext); m_restoreAgent.setInitiator(initiator); } } }
diff --git a/illamapedit/src/illarion/mapedit/gui/ZoomBand.java b/illamapedit/src/illarion/mapedit/gui/ZoomBand.java index 8a165e62..4268ada0 100644 --- a/illamapedit/src/illarion/mapedit/gui/ZoomBand.java +++ b/illamapedit/src/illarion/mapedit/gui/ZoomBand.java @@ -1,87 +1,87 @@ /* * This file is part of the Illarion Mapeditor. * * Copyright © 2012 - Illarion e.V. * * The Illarion Mapeditor is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Illarion Mapeditor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Illarion Mapeditor. If not, see <http://www.gnu.org/licenses/>. */ package illarion.mapedit.gui; import illarion.mapedit.Lang; import illarion.mapedit.events.map.ZoomEvent; import illarion.mapedit.resource.loaders.ImageLoader; import org.bushe.swing.event.EventBus; import org.pushingpixels.flamingo.api.common.JCommandButton; import org.pushingpixels.flamingo.api.ribbon.JRibbonBand; import org.pushingpixels.flamingo.api.ribbon.RibbonElementPriority; import org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies; import org.pushingpixels.flamingo.api.ribbon.resize.RibbonBandResizePolicy; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; /** * @author Tim */ public class ZoomBand extends JRibbonBand { public static final float ZOOM_STEP = .1f; public ZoomBand() { super(Lang.getMsg("gui.zoomband.Name"), ImageLoader.getResizableIcon("viewmag")); final JCommandButton zoomOriginal = new JCommandButton(Lang.getMsg("gui.zoomband.Original"), ImageLoader.getResizableIcon("viewmag1")); final JCommandButton zoomOut = new JCommandButton(Lang.getMsg("gui.zoomband.Out"), ImageLoader.getResizableIcon("viewmag-")); final JCommandButton zoomIn = new JCommandButton(Lang.getMsg("gui.zoomband.In"), ImageLoader.getResizableIcon("viewmag+")); final ActionListener zoomOutListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { - EventBus.publish(new ZoomEvent(ZOOM_STEP)); + EventBus.publish(new ZoomEvent(-ZOOM_STEP)); } }; final ActionListener zoomInListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { - EventBus.publish(new ZoomEvent(-ZOOM_STEP)); + EventBus.publish(new ZoomEvent(ZOOM_STEP)); } }; final ActionListener zoomOriginalListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventBus.publish(new ZoomEvent()); } }; zoomIn.addActionListener(zoomInListener); zoomOut.addActionListener(zoomOutListener); zoomOriginal.addActionListener(zoomOriginalListener); addCommandButton(zoomOriginal, RibbonElementPriority.TOP); addCommandButton(zoomOut, RibbonElementPriority.TOP); addCommandButton(zoomIn, RibbonElementPriority.TOP); final List<RibbonBandResizePolicy> policies = new ArrayList<RibbonBandResizePolicy>(); policies.add(new CoreRibbonResizePolicies.Mirror(getControlPanel())); policies.add(new CoreRibbonResizePolicies.High2Low(getControlPanel())); setResizePolicies(policies); } }
false
true
public ZoomBand() { super(Lang.getMsg("gui.zoomband.Name"), ImageLoader.getResizableIcon("viewmag")); final JCommandButton zoomOriginal = new JCommandButton(Lang.getMsg("gui.zoomband.Original"), ImageLoader.getResizableIcon("viewmag1")); final JCommandButton zoomOut = new JCommandButton(Lang.getMsg("gui.zoomband.Out"), ImageLoader.getResizableIcon("viewmag-")); final JCommandButton zoomIn = new JCommandButton(Lang.getMsg("gui.zoomband.In"), ImageLoader.getResizableIcon("viewmag+")); final ActionListener zoomOutListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventBus.publish(new ZoomEvent(ZOOM_STEP)); } }; final ActionListener zoomInListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventBus.publish(new ZoomEvent(-ZOOM_STEP)); } }; final ActionListener zoomOriginalListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventBus.publish(new ZoomEvent()); } }; zoomIn.addActionListener(zoomInListener); zoomOut.addActionListener(zoomOutListener); zoomOriginal.addActionListener(zoomOriginalListener); addCommandButton(zoomOriginal, RibbonElementPriority.TOP); addCommandButton(zoomOut, RibbonElementPriority.TOP); addCommandButton(zoomIn, RibbonElementPriority.TOP); final List<RibbonBandResizePolicy> policies = new ArrayList<RibbonBandResizePolicy>(); policies.add(new CoreRibbonResizePolicies.Mirror(getControlPanel())); policies.add(new CoreRibbonResizePolicies.High2Low(getControlPanel())); setResizePolicies(policies); }
public ZoomBand() { super(Lang.getMsg("gui.zoomband.Name"), ImageLoader.getResizableIcon("viewmag")); final JCommandButton zoomOriginal = new JCommandButton(Lang.getMsg("gui.zoomband.Original"), ImageLoader.getResizableIcon("viewmag1")); final JCommandButton zoomOut = new JCommandButton(Lang.getMsg("gui.zoomband.Out"), ImageLoader.getResizableIcon("viewmag-")); final JCommandButton zoomIn = new JCommandButton(Lang.getMsg("gui.zoomband.In"), ImageLoader.getResizableIcon("viewmag+")); final ActionListener zoomOutListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventBus.publish(new ZoomEvent(-ZOOM_STEP)); } }; final ActionListener zoomInListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventBus.publish(new ZoomEvent(ZOOM_STEP)); } }; final ActionListener zoomOriginalListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { EventBus.publish(new ZoomEvent()); } }; zoomIn.addActionListener(zoomInListener); zoomOut.addActionListener(zoomOutListener); zoomOriginal.addActionListener(zoomOriginalListener); addCommandButton(zoomOriginal, RibbonElementPriority.TOP); addCommandButton(zoomOut, RibbonElementPriority.TOP); addCommandButton(zoomIn, RibbonElementPriority.TOP); final List<RibbonBandResizePolicy> policies = new ArrayList<RibbonBandResizePolicy>(); policies.add(new CoreRibbonResizePolicies.Mirror(getControlPanel())); policies.add(new CoreRibbonResizePolicies.High2Low(getControlPanel())); setResizePolicies(policies); }
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java index b8ca27809..da8bab8a6 100644 --- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java +++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/SaxMultiBugReportContentHandler.java @@ -1,777 +1,776 @@ /******************************************************************************* * Copyright (c) 2004, 2010 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.core; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.eclipse.mylyn.tasks.core.IRepositoryPerson; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; import org.eclipse.mylyn.tasks.core.data.TaskAttributeMapper; import org.eclipse.mylyn.tasks.core.data.TaskCommentMapper; import org.eclipse.mylyn.tasks.core.data.TaskData; import org.eclipse.mylyn.tasks.core.data.TaskDataCollector; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Parser for xml bugzilla reports. * * @author Rob Elves * @author Hiroyuki Inaba (internationalization) */ public class SaxMultiBugReportContentHandler extends DefaultHandler { private static final String ATTRIBUTE_NAME = "name"; //$NON-NLS-1$ private static final String ID_STRING_BEGIN = " (id="; //$NON-NLS-1$ private static final String ID_STRING_END = ")"; //$NON-NLS-1$ private StringBuffer characters; private TaskComment taskComment; private Map<String, TaskCommentMapper> attachIdToComment = new HashMap<String, TaskCommentMapper>(); private int commentNum = 0; private BugzillaAttachmentMapper attachment; private final Map<String, TaskData> taskDataMap; private TaskData repositoryTaskData; private List<TaskComment> longDescs; private String errorMessage = null; private final List<BugzillaCustomField> customFields; private final TaskDataCollector collector; private boolean isDeprecated = false; private boolean isPatch = false; private String token; private String exporter; private TaskAttribute attachmentAttribute; private boolean bugParseErrorOccurred; private final BugzillaRepositoryConnector connector; private boolean useIsPrivate; private final TaskAttributeMapper mapper; private final SimpleDateFormat simpleFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //$NON-NLS-1$ public SaxMultiBugReportContentHandler(TaskAttributeMapper mapper, TaskDataCollector collector, Map<String, TaskData> taskDataMap, List<BugzillaCustomField> customFields, BugzillaRepositoryConnector connector) { this.mapper = mapper; this.taskDataMap = taskDataMap; this.customFields = customFields; this.collector = collector; this.connector = connector; TaskRepository taskRepository = mapper.getTaskRepository(); String useParam = taskRepository.getProperty(IBugzillaConstants.BUGZILLA_INSIDER_GROUP); useIsPrivate = (useParam == null || (useParam != null && useParam.equals("true"))); //$NON-NLS-1$ } public boolean errorOccurred() { return errorMessage != null; } public String getErrorMessage() { return errorMessage; } @Override public void characters(char[] ch, int start, int length) throws SAXException { characters.append(ch, start, length); //System.err.println(String.copyValueOf(ch, start, length)); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { characters = new StringBuffer(); BugzillaAttribute tag = BugzillaAttribute.UNKNOWN; if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) { return; } try { tag = BugzillaAttribute.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUGZILLA: // Note: here we can get the bugzilla version if necessary // String version = attributes.getValue("version"); // urlbase = attributes.getValue("urlbase"); //$NON-NLS-1$ // String maintainer = attributes.getValue("maintainer"); exporter = attributes.getValue("exporter"); //$NON-NLS-1$ break; case BUG: if (attributes != null && (attributes.getValue("error") != null)) { //$NON-NLS-1$ errorMessage = attributes.getValue("error"); //$NON-NLS-1$ bugParseErrorOccurred = true; repositoryTaskData = null; } attachIdToComment = new HashMap<String, TaskCommentMapper>(); commentNum = 0; taskComment = null; longDescs = new ArrayList<TaskComment>(); token = null; break; case LONG_DESC: String is_private = attributes.getValue("isprivate"); //$NON-NLS-1$ taskComment = new TaskComment(is_private); break; case WHO: if (taskComment != null) { if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null && name.length() > 0) { taskComment.authorName = name; } } } break; case REPORTER: if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.REPORTER_NAME) .setValue(name); } } break; case QA_CONTACT: if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.QA_CONTACT_NAME) .setValue(name); } } break; case ASSIGNED_TO: if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.ASSIGNED_TO_NAME) .setValue(name); } } break; case ATTACHMENT: if (attributes != null) { isDeprecated = "1".equals(attributes.getValue(BugzillaAttribute.IS_OBSOLETE.getKey())); //$NON-NLS-1$ isPatch = "1".equals(attributes.getValue(BugzillaAttribute.IS_PATCH.getKey())); //$NON-NLS-1$ } break; case FLAG: if (attributes != null && attributes.getLength() > 0) { String name = attributes.getValue(ATTRIBUTE_NAME); if (name != null) { BugzillaFlagMapper mapper = new BugzillaFlagMapper(connector); String requestee = attributes.getValue("requestee"); //$NON-NLS-1$ mapper.setRequestee(requestee); String setter = attributes.getValue("setter"); //$NON-NLS-1$ mapper.setSetter(setter); String status = attributes.getValue("status"); //$NON-NLS-1$ mapper.setState(status); mapper.setFlagId(name); String id = attributes.getValue("id"); //$NON-NLS-1$ if (id != null && !id.equals("")) { //$NON-NLS-1$ /* * for version 3.2rc1 and 3.2.rc2 the id was not defined so we ignore * the definition */ try { mapper.setNumber(Integer.valueOf(id)); TaskAttribute attribute; if (attachmentAttribute != null) { attribute = attachmentAttribute.createAttribute(BugzillaAttribute.KIND_FLAG + id); } else { attribute = repositoryTaskData.getRoot().createAttribute( BugzillaAttribute.KIND_FLAG + id); } mapper.applyTo(attribute); } catch (NumberFormatException e) { // ignore } } } } break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { //remove whitespaces from the end of the parsed Text while (characters.length() > 0 && Character.isWhitespace(characters.charAt(characters.length() - 1))) { characters.setLength(characters.length() - 1); } String parsedText = characters.toString(); if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) { TaskAttribute endAttribute = repositoryTaskData.getRoot().getAttribute(localName); if (endAttribute == null) { String desc = "???"; //$NON-NLS-1$ BugzillaCustomField customField = null; for (BugzillaCustomField bugzillaCustomField : customFields) { if (localName.equals(bugzillaCustomField.getName())) { customField = bugzillaCustomField; break; } } if (customField != null) { TaskAttribute atr = repositoryTaskData.getRoot().createAttribute(localName); desc = customField.getDescription(); atr.getMetaData().defaults().setLabel(desc).setReadOnly(false); atr.getMetaData().setKind(TaskAttribute.KIND_DEFAULT); atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); switch (customField.getFieldType()) { case FreeText: atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); break; case DropDown: atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); break; case MultipleSelection: atr.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT); break; case LargeText: atr.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT); break; case DateTime: atr.getMetaData().setType(TaskAttribute.TYPE_DATETIME); break; default: List<String> options = customField.getOptions(); if (options.size() > 0) { atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); } else { atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); } } atr.getMetaData().setReadOnly(false); atr.setValue(parsedText); } } else { endAttribute.addValue(parsedText); } } BugzillaAttribute tag = BugzillaAttribute.UNKNOWN; try { tag = BugzillaAttribute.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUG_ID: { repositoryTaskData = taskDataMap.get(parsedText.trim()); if (repositoryTaskData == null) { errorMessage = parsedText + Messages.SaxMultiBugReportContentHandler_id_not_found; bugParseErrorOccurred = true; break; } TaskAttribute attr = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (attr == null) { attr = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag); } attr.setValue(parsedText); if (exporter != null) { createAttrribute(exporter, BugzillaAttribute.EXPORTER_NAME); } else { createAttrribute("", BugzillaAttribute.EXPORTER_NAME); //$NON-NLS-1$ } break; } // Comment attributes case WHO: if (taskComment != null) { taskComment.author = parsedText; } break; case BUG_WHEN: if (taskComment != null) { taskComment.createdTimeStamp = parsedText; } break; case WORK_TIME: if (taskComment != null) { taskComment.timeWorked = parsedText; } break; case THETEXT: if (taskComment != null) { taskComment.commentText = parsedText; } break; case LONG_DESC: if (taskComment != null) { longDescs.add(taskComment); } break; // Attachment attributes case ATTACHID: attachmentAttribute = repositoryTaskData.getRoot().createAttribute( TaskAttribute.PREFIX_ATTACHMENT + parsedText); attachment = BugzillaAttachmentMapper.createFrom(attachmentAttribute); attachment.setLength(new Long(-1)); attachment.setAttachmentId(parsedText); attachment.setPatch(isPatch); attachment.setDeprecated(isDeprecated); attachment.setToken(null); break; case DATE: if (attachment != null) { try { attachment.setCreationDate(simpleFormatter.parse(parsedText)); break; } catch (ParseException e) { } catch (NumberFormatException e) { } } break; case DESC: if (attachment != null) { attachment.setDescription(parsedText); } break; case FILENAME: if (attachment != null) { attachment.setFileName(parsedText); } break; case CTYPE: case TYPE: if (attachment != null) { attachment.setContentType(parsedText); } break; case SIZE: if (attachment != null) { try { if (parsedText != null) { attachment.setLength(Long.parseLong(parsedText)); } } catch (NumberFormatException e) { // ignore } } break; case ATTACHMENT: if (attachment != null) { attachment.applyTo(attachmentAttribute); } isPatch = false; isDeprecated = false; attachment = null; attachmentAttribute = null; break; case DATA: // ignored break; case BUGZILLA: // ignored break; case BUG: // Reached end of bug. if (bugParseErrorOccurred) { bugParseErrorOccurred = false; break; } addDescriptionAndComments(); // Need to set LONGDESCLENGTH to number of comments + 1 for description TaskAttribute numCommentsAttribute = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.LONGDESCLENGTH.getKey()); if (numCommentsAttribute == null) { numCommentsAttribute = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.LONGDESCLENGTH); } numCommentsAttribute.setValue("" + commentNum); //$NON-NLS-1$ updateAttachmentMetaData(); TaskAttribute attrCreation = repositoryTaskData.getRoot().getAttribute( BugzillaAttribute.CREATION_TS.getKey()); updateCustomFields(repositoryTaskData); if (token != null) { TaskAttribute tokenAttribute = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.TOKEN); tokenAttribute.setValue(token); } // Work around (bug#285796) If planning enabled (ESTIMATE_TIME attr present) create DEADLINE attr since it should be present. TaskAttribute estimatedTimeAttr = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.ESTIMATED_TIME.getKey()); TaskAttribute deadlineAttr = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.DEADLINE.getKey()); if (estimatedTimeAttr != null && deadlineAttr == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.DEADLINE); } // Save/Add to collector. Guard against empty data sets if (attrCreation != null && !attrCreation.equals("")) { //$NON-NLS-1$ collector.accept(repositoryTaskData); } repositoryTaskData = null; break; case BLOCKED: // handled similarly to DEPENDSON case DEPENDSON: TaskAttribute blockOrDepends = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (blockOrDepends == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag).setValue(parsedText); } else { if (blockOrDepends.getValue().equals("")) { //$NON-NLS-1$ blockOrDepends.setValue(parsedText); } else { blockOrDepends.setValue(blockOrDepends.getValue() + ", " + parsedText); //$NON-NLS-1$ } } break; case DUP_ID: TaskAttribute duplicateOf = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (duplicateOf == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag).setValue(parsedText); } else { if (duplicateOf.getValue().equals("")) { //$NON-NLS-1$ duplicateOf.setValue(parsedText); } } break; case UNKNOWN: //ignore break; case FLAG: //ignore break; case TOKEN: if (attachment != null) { attachment.setToken(parsedText); } else { token = parsedText; } break; case ATTACHER: if (attachment != null) { IRepositoryPerson author = repositoryTaskData.getAttributeMapper() .getTaskRepository() .createPerson(parsedText); - author.setName(parsedText); attachment.setAuthor(author); } break; case TARGET_MILESTONE: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USETARGETMILESTONE, true); break; case QA_CONTACT: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT, true); break; case STATUS_WHITEBOARD: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USESTATUSWHITEBOARD, true); break; case CLASSIFICATION: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USECLASSIFICATION, false); break; case ALIAS: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USEBUGALIASES, false); break; case SEE_ALSO: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USE_SEE_ALSO, false); break; case COMMENTID: if (taskComment != null) { taskComment.id = Integer.parseInt(parsedText); } break; default: createAttrribute(parsedText, tag); break; } } private TaskAttribute createAttrribute(String parsedText, BugzillaAttribute tag) { TaskAttribute attribute = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (attribute == null) { attribute = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag); attribute.setValue(parsedText); } else { attribute.addValue(parsedText); } return attribute; } private void updateCustomFields(TaskData taskData) { RepositoryConfiguration config = connector.getRepositoryConfiguration(repositoryTaskData.getRepositoryUrl()); if (config != null) { for (BugzillaCustomField bugzillaCustomField : config.getCustomFields()) { TaskAttribute atr = taskData.getRoot().getAttribute(bugzillaCustomField.getName()); if (atr == null) { atr = taskData.getRoot().createAttribute(bugzillaCustomField.getName()); } if (atr != null) { atr.getMetaData().defaults().setLabel(bugzillaCustomField.getDescription()); atr.getMetaData().setKind(TaskAttribute.KIND_DEFAULT); switch (bugzillaCustomField.getFieldType()) { case FreeText: atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); break; case DropDown: atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); break; case MultipleSelection: atr.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT); break; case LargeText: atr.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT); break; case DateTime: atr.getMetaData().setType(TaskAttribute.TYPE_DATETIME); break; default: List<String> options = bugzillaCustomField.getOptions(); if (options.size() > 0) { atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); } else { atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); } } atr.getMetaData().setReadOnly(false); } } } } private void updateAttachmentMetaData() { List<TaskAttribute> taskAttachments = repositoryTaskData.getAttributeMapper().getAttributesByType( repositoryTaskData, TaskAttribute.TYPE_ATTACHMENT); for (TaskAttribute attachment : taskAttachments) { BugzillaAttachmentMapper attachmentMapper = BugzillaAttachmentMapper.createFrom(attachment); if (attachmentMapper.getAuthor() == null || attachmentMapper.getCreationDate() == null) { TaskCommentMapper taskComment = attachIdToComment.get(attachmentMapper.getAttachmentId()); if (taskComment != null) { attachmentMapper.setAuthor(taskComment.getAuthor()); attachmentMapper.setCreationDate(taskComment.getCreationDate()); } } attachmentMapper.setUrl(repositoryTaskData.getRepositoryUrl() + IBugzillaConstants.URL_GET_ATTACHMENT_SUFFIX + attachmentMapper.getAttachmentId()); attachmentMapper.applyTo(attachment); } } private void addDescriptionAndComments() { int longDescsSize = longDescs.size() - 1; commentNum = 1; if (longDescsSize == 0) { addDescription(longDescs.get(0).commentText); } else if (longDescsSize == 1) { if (longDescs.get(0).createdTimeStamp.compareTo(longDescs.get(1).createdTimeStamp) <= 0) { // if created_0 is equal to created_1 we assume that longDescs at index 0 is the description. addDescription(longDescs.get(0).commentText); addComment(longDescs.get(1)); } else { addDescription(longDescs.get(1).commentText); addComment(longDescs.get(0)); } } else if (longDescsSize > 1) { String created_0 = longDescs.get(0).createdTimeStamp; String created_1 = longDescs.get(1).createdTimeStamp; String created_n = longDescs.get(longDescsSize).createdTimeStamp; if (created_0.compareTo(created_1) <= 0 && created_0.compareTo(created_n) < 0) { // if created_0 is equal to created_1 we assume that longDescs at index 0 is the description. addDescription(longDescs.get(0).commentText); if (created_1.compareTo(created_n) < 0) { for (int i = 1; i <= longDescsSize; i++) { addComment(longDescs.get(i)); } } else { for (int i = longDescsSize; i > 0; i--) { addComment(longDescs.get(i)); } } } else { addDescription(longDescs.get(longDescsSize).commentText); if (created_0.compareTo(created_1) < 0) { for (int i = 0; i < longDescsSize; i++) { addComment(longDescs.get(i)); } } else { for (int i = longDescsSize - 1; i >= 0; i--) { addComment(longDescs.get(i)); } } } } } private void addDescription(String commentText) { TaskAttribute attrDescription = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.LONG_DESC); attrDescription.setValue(commentText); } private void addComment(TaskComment comment) { TaskAttribute attribute = repositoryTaskData.getRoot().createAttribute( TaskAttribute.PREFIX_COMMENT + commentNum); TaskCommentMapper taskComment = TaskCommentMapper.createFrom(attribute); taskComment.setCommentId(comment.id + ""); //$NON-NLS-1$ taskComment.setNumber(commentNum); IRepositoryPerson author = repositoryTaskData.getAttributeMapper() .getTaskRepository() .createPerson(comment.author); author.setName(comment.authorName); taskComment.setAuthor(author); if (useIsPrivate) { taskComment.setIsPrivate(comment.isPrivate.equals("1")); //$NON-NLS-1$ } else { if (comment.isPrivate.equals("1")) { //$NON-NLS-1$ TaskRepository taskRepository = mapper.getTaskRepository(); taskRepository.setProperty(IBugzillaConstants.BUGZILLA_INSIDER_GROUP, "true"); //$NON-NLS-1$ useIsPrivate = true; } taskComment.setIsPrivate(null); } TaskAttribute attrTimestamp = attribute.createAttribute(BugzillaAttribute.BUG_WHEN.getKey()); attrTimestamp.setValue(comment.createdTimeStamp); taskComment.setCreationDate(repositoryTaskData.getAttributeMapper().getDateValue(attrTimestamp)); if (comment.commentText != null) { String commentText = comment.commentText.trim(); taskComment.setText(commentText); } taskComment.applyTo(attribute); commentNum++; if (comment.timeWorked != null) { TaskAttribute workTime = BugzillaTaskDataHandler.createAttribute(attribute, BugzillaAttribute.WORK_TIME); workTime.setValue(comment.timeWorked); } if (comment.id != 0) { TaskAttribute commentID = BugzillaTaskDataHandler.createAttribute(attribute, BugzillaAttribute.COMMENTID); commentID.setValue(Integer.toString(comment.id)); } parseAttachment(taskComment); } /** determines attachment id from comment */ private void parseAttachment(TaskCommentMapper comment) { String attachmentID = ""; //$NON-NLS-1$ String commentText = comment.getText(); int firstDelimiter = commentText.indexOf("\n"); //$NON-NLS-1$ if (firstDelimiter < 0) { firstDelimiter = commentText.length(); } int startIndex = commentText.indexOf(ID_STRING_BEGIN); if (startIndex > 0 && startIndex < firstDelimiter) { int endIndex = commentText.indexOf(ID_STRING_END, startIndex); if (endIndex > 0 && endIndex < firstDelimiter) { startIndex += ID_STRING_BEGIN.length(); int p = startIndex; while (p < endIndex) { char c = commentText.charAt(p); if (c < '0' || c > '9') { break; } p++; } if (p == endIndex) { attachmentID = commentText.substring(startIndex, endIndex); if (!attachmentID.equals("")) { //$NON-NLS-1$ attachIdToComment.put(attachmentID, comment); } } } } } private static class TaskComment { @SuppressWarnings("unused") public int number; public int id; public String author; public String authorName; public String createdTimeStamp; public String commentText; public String timeWorked; public String isPrivate; public TaskComment(String isprivate) { this.isPrivate = isprivate; } } }
true
true
public void endElement(String uri, String localName, String qName) throws SAXException { //remove whitespaces from the end of the parsed Text while (characters.length() > 0 && Character.isWhitespace(characters.charAt(characters.length() - 1))) { characters.setLength(characters.length() - 1); } String parsedText = characters.toString(); if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) { TaskAttribute endAttribute = repositoryTaskData.getRoot().getAttribute(localName); if (endAttribute == null) { String desc = "???"; //$NON-NLS-1$ BugzillaCustomField customField = null; for (BugzillaCustomField bugzillaCustomField : customFields) { if (localName.equals(bugzillaCustomField.getName())) { customField = bugzillaCustomField; break; } } if (customField != null) { TaskAttribute atr = repositoryTaskData.getRoot().createAttribute(localName); desc = customField.getDescription(); atr.getMetaData().defaults().setLabel(desc).setReadOnly(false); atr.getMetaData().setKind(TaskAttribute.KIND_DEFAULT); atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); switch (customField.getFieldType()) { case FreeText: atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); break; case DropDown: atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); break; case MultipleSelection: atr.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT); break; case LargeText: atr.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT); break; case DateTime: atr.getMetaData().setType(TaskAttribute.TYPE_DATETIME); break; default: List<String> options = customField.getOptions(); if (options.size() > 0) { atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); } else { atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); } } atr.getMetaData().setReadOnly(false); atr.setValue(parsedText); } } else { endAttribute.addValue(parsedText); } } BugzillaAttribute tag = BugzillaAttribute.UNKNOWN; try { tag = BugzillaAttribute.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUG_ID: { repositoryTaskData = taskDataMap.get(parsedText.trim()); if (repositoryTaskData == null) { errorMessage = parsedText + Messages.SaxMultiBugReportContentHandler_id_not_found; bugParseErrorOccurred = true; break; } TaskAttribute attr = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (attr == null) { attr = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag); } attr.setValue(parsedText); if (exporter != null) { createAttrribute(exporter, BugzillaAttribute.EXPORTER_NAME); } else { createAttrribute("", BugzillaAttribute.EXPORTER_NAME); //$NON-NLS-1$ } break; } // Comment attributes case WHO: if (taskComment != null) { taskComment.author = parsedText; } break; case BUG_WHEN: if (taskComment != null) { taskComment.createdTimeStamp = parsedText; } break; case WORK_TIME: if (taskComment != null) { taskComment.timeWorked = parsedText; } break; case THETEXT: if (taskComment != null) { taskComment.commentText = parsedText; } break; case LONG_DESC: if (taskComment != null) { longDescs.add(taskComment); } break; // Attachment attributes case ATTACHID: attachmentAttribute = repositoryTaskData.getRoot().createAttribute( TaskAttribute.PREFIX_ATTACHMENT + parsedText); attachment = BugzillaAttachmentMapper.createFrom(attachmentAttribute); attachment.setLength(new Long(-1)); attachment.setAttachmentId(parsedText); attachment.setPatch(isPatch); attachment.setDeprecated(isDeprecated); attachment.setToken(null); break; case DATE: if (attachment != null) { try { attachment.setCreationDate(simpleFormatter.parse(parsedText)); break; } catch (ParseException e) { } catch (NumberFormatException e) { } } break; case DESC: if (attachment != null) { attachment.setDescription(parsedText); } break; case FILENAME: if (attachment != null) { attachment.setFileName(parsedText); } break; case CTYPE: case TYPE: if (attachment != null) { attachment.setContentType(parsedText); } break; case SIZE: if (attachment != null) { try { if (parsedText != null) { attachment.setLength(Long.parseLong(parsedText)); } } catch (NumberFormatException e) { // ignore } } break; case ATTACHMENT: if (attachment != null) { attachment.applyTo(attachmentAttribute); } isPatch = false; isDeprecated = false; attachment = null; attachmentAttribute = null; break; case DATA: // ignored break; case BUGZILLA: // ignored break; case BUG: // Reached end of bug. if (bugParseErrorOccurred) { bugParseErrorOccurred = false; break; } addDescriptionAndComments(); // Need to set LONGDESCLENGTH to number of comments + 1 for description TaskAttribute numCommentsAttribute = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.LONGDESCLENGTH.getKey()); if (numCommentsAttribute == null) { numCommentsAttribute = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.LONGDESCLENGTH); } numCommentsAttribute.setValue("" + commentNum); //$NON-NLS-1$ updateAttachmentMetaData(); TaskAttribute attrCreation = repositoryTaskData.getRoot().getAttribute( BugzillaAttribute.CREATION_TS.getKey()); updateCustomFields(repositoryTaskData); if (token != null) { TaskAttribute tokenAttribute = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.TOKEN); tokenAttribute.setValue(token); } // Work around (bug#285796) If planning enabled (ESTIMATE_TIME attr present) create DEADLINE attr since it should be present. TaskAttribute estimatedTimeAttr = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.ESTIMATED_TIME.getKey()); TaskAttribute deadlineAttr = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.DEADLINE.getKey()); if (estimatedTimeAttr != null && deadlineAttr == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.DEADLINE); } // Save/Add to collector. Guard against empty data sets if (attrCreation != null && !attrCreation.equals("")) { //$NON-NLS-1$ collector.accept(repositoryTaskData); } repositoryTaskData = null; break; case BLOCKED: // handled similarly to DEPENDSON case DEPENDSON: TaskAttribute blockOrDepends = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (blockOrDepends == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag).setValue(parsedText); } else { if (blockOrDepends.getValue().equals("")) { //$NON-NLS-1$ blockOrDepends.setValue(parsedText); } else { blockOrDepends.setValue(blockOrDepends.getValue() + ", " + parsedText); //$NON-NLS-1$ } } break; case DUP_ID: TaskAttribute duplicateOf = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (duplicateOf == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag).setValue(parsedText); } else { if (duplicateOf.getValue().equals("")) { //$NON-NLS-1$ duplicateOf.setValue(parsedText); } } break; case UNKNOWN: //ignore break; case FLAG: //ignore break; case TOKEN: if (attachment != null) { attachment.setToken(parsedText); } else { token = parsedText; } break; case ATTACHER: if (attachment != null) { IRepositoryPerson author = repositoryTaskData.getAttributeMapper() .getTaskRepository() .createPerson(parsedText); author.setName(parsedText); attachment.setAuthor(author); } break; case TARGET_MILESTONE: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USETARGETMILESTONE, true); break; case QA_CONTACT: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT, true); break; case STATUS_WHITEBOARD: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USESTATUSWHITEBOARD, true); break; case CLASSIFICATION: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USECLASSIFICATION, false); break; case ALIAS: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USEBUGALIASES, false); break; case SEE_ALSO: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USE_SEE_ALSO, false); break; case COMMENTID: if (taskComment != null) { taskComment.id = Integer.parseInt(parsedText); } break; default: createAttrribute(parsedText, tag); break; } }
public void endElement(String uri, String localName, String qName) throws SAXException { //remove whitespaces from the end of the parsed Text while (characters.length() > 0 && Character.isWhitespace(characters.charAt(characters.length() - 1))) { characters.setLength(characters.length() - 1); } String parsedText = characters.toString(); if (localName.startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) { TaskAttribute endAttribute = repositoryTaskData.getRoot().getAttribute(localName); if (endAttribute == null) { String desc = "???"; //$NON-NLS-1$ BugzillaCustomField customField = null; for (BugzillaCustomField bugzillaCustomField : customFields) { if (localName.equals(bugzillaCustomField.getName())) { customField = bugzillaCustomField; break; } } if (customField != null) { TaskAttribute atr = repositoryTaskData.getRoot().createAttribute(localName); desc = customField.getDescription(); atr.getMetaData().defaults().setLabel(desc).setReadOnly(false); atr.getMetaData().setKind(TaskAttribute.KIND_DEFAULT); atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); switch (customField.getFieldType()) { case FreeText: atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); break; case DropDown: atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); break; case MultipleSelection: atr.getMetaData().setType(TaskAttribute.TYPE_MULTI_SELECT); break; case LargeText: atr.getMetaData().setType(TaskAttribute.TYPE_LONG_TEXT); break; case DateTime: atr.getMetaData().setType(TaskAttribute.TYPE_DATETIME); break; default: List<String> options = customField.getOptions(); if (options.size() > 0) { atr.getMetaData().setType(TaskAttribute.TYPE_SINGLE_SELECT); } else { atr.getMetaData().setType(TaskAttribute.TYPE_SHORT_TEXT); } } atr.getMetaData().setReadOnly(false); atr.setValue(parsedText); } } else { endAttribute.addValue(parsedText); } } BugzillaAttribute tag = BugzillaAttribute.UNKNOWN; try { tag = BugzillaAttribute.valueOf(localName.trim().toUpperCase(Locale.ENGLISH)); } catch (RuntimeException e) { if (e instanceof IllegalArgumentException) { // ignore unrecognized tags return; } throw e; } switch (tag) { case BUG_ID: { repositoryTaskData = taskDataMap.get(parsedText.trim()); if (repositoryTaskData == null) { errorMessage = parsedText + Messages.SaxMultiBugReportContentHandler_id_not_found; bugParseErrorOccurred = true; break; } TaskAttribute attr = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (attr == null) { attr = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag); } attr.setValue(parsedText); if (exporter != null) { createAttrribute(exporter, BugzillaAttribute.EXPORTER_NAME); } else { createAttrribute("", BugzillaAttribute.EXPORTER_NAME); //$NON-NLS-1$ } break; } // Comment attributes case WHO: if (taskComment != null) { taskComment.author = parsedText; } break; case BUG_WHEN: if (taskComment != null) { taskComment.createdTimeStamp = parsedText; } break; case WORK_TIME: if (taskComment != null) { taskComment.timeWorked = parsedText; } break; case THETEXT: if (taskComment != null) { taskComment.commentText = parsedText; } break; case LONG_DESC: if (taskComment != null) { longDescs.add(taskComment); } break; // Attachment attributes case ATTACHID: attachmentAttribute = repositoryTaskData.getRoot().createAttribute( TaskAttribute.PREFIX_ATTACHMENT + parsedText); attachment = BugzillaAttachmentMapper.createFrom(attachmentAttribute); attachment.setLength(new Long(-1)); attachment.setAttachmentId(parsedText); attachment.setPatch(isPatch); attachment.setDeprecated(isDeprecated); attachment.setToken(null); break; case DATE: if (attachment != null) { try { attachment.setCreationDate(simpleFormatter.parse(parsedText)); break; } catch (ParseException e) { } catch (NumberFormatException e) { } } break; case DESC: if (attachment != null) { attachment.setDescription(parsedText); } break; case FILENAME: if (attachment != null) { attachment.setFileName(parsedText); } break; case CTYPE: case TYPE: if (attachment != null) { attachment.setContentType(parsedText); } break; case SIZE: if (attachment != null) { try { if (parsedText != null) { attachment.setLength(Long.parseLong(parsedText)); } } catch (NumberFormatException e) { // ignore } } break; case ATTACHMENT: if (attachment != null) { attachment.applyTo(attachmentAttribute); } isPatch = false; isDeprecated = false; attachment = null; attachmentAttribute = null; break; case DATA: // ignored break; case BUGZILLA: // ignored break; case BUG: // Reached end of bug. if (bugParseErrorOccurred) { bugParseErrorOccurred = false; break; } addDescriptionAndComments(); // Need to set LONGDESCLENGTH to number of comments + 1 for description TaskAttribute numCommentsAttribute = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.LONGDESCLENGTH.getKey()); if (numCommentsAttribute == null) { numCommentsAttribute = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.LONGDESCLENGTH); } numCommentsAttribute.setValue("" + commentNum); //$NON-NLS-1$ updateAttachmentMetaData(); TaskAttribute attrCreation = repositoryTaskData.getRoot().getAttribute( BugzillaAttribute.CREATION_TS.getKey()); updateCustomFields(repositoryTaskData); if (token != null) { TaskAttribute tokenAttribute = BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.TOKEN); tokenAttribute.setValue(token); } // Work around (bug#285796) If planning enabled (ESTIMATE_TIME attr present) create DEADLINE attr since it should be present. TaskAttribute estimatedTimeAttr = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.ESTIMATED_TIME.getKey()); TaskAttribute deadlineAttr = repositoryTaskData.getRoot().getMappedAttribute( BugzillaAttribute.DEADLINE.getKey()); if (estimatedTimeAttr != null && deadlineAttr == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, BugzillaAttribute.DEADLINE); } // Save/Add to collector. Guard against empty data sets if (attrCreation != null && !attrCreation.equals("")) { //$NON-NLS-1$ collector.accept(repositoryTaskData); } repositoryTaskData = null; break; case BLOCKED: // handled similarly to DEPENDSON case DEPENDSON: TaskAttribute blockOrDepends = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (blockOrDepends == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag).setValue(parsedText); } else { if (blockOrDepends.getValue().equals("")) { //$NON-NLS-1$ blockOrDepends.setValue(parsedText); } else { blockOrDepends.setValue(blockOrDepends.getValue() + ", " + parsedText); //$NON-NLS-1$ } } break; case DUP_ID: TaskAttribute duplicateOf = repositoryTaskData.getRoot().getMappedAttribute(tag.getKey()); if (duplicateOf == null) { BugzillaTaskDataHandler.createAttribute(repositoryTaskData, tag).setValue(parsedText); } else { if (duplicateOf.getValue().equals("")) { //$NON-NLS-1$ duplicateOf.setValue(parsedText); } } break; case UNKNOWN: //ignore break; case FLAG: //ignore break; case TOKEN: if (attachment != null) { attachment.setToken(parsedText); } else { token = parsedText; } break; case ATTACHER: if (attachment != null) { IRepositoryPerson author = repositoryTaskData.getAttributeMapper() .getTaskRepository() .createPerson(parsedText); attachment.setAuthor(author); } break; case TARGET_MILESTONE: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USETARGETMILESTONE, true); break; case QA_CONTACT: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT, true); break; case STATUS_WHITEBOARD: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USESTATUSWHITEBOARD, true); break; case CLASSIFICATION: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USECLASSIFICATION, false); break; case ALIAS: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USEBUGALIASES, false); break; case SEE_ALSO: BugzillaUtil.createAttributeWithKindDefaultIfUsed(parsedText, tag, repositoryTaskData, IBugzillaConstants.BUGZILLA_PARAM_USE_SEE_ALSO, false); break; case COMMENTID: if (taskComment != null) { taskComment.id = Integer.parseInt(parsedText); } break; default: createAttrribute(parsedText, tag); break; } }
diff --git a/Meat-Loaf/src/com/cs301w01/meatload/activities/SendEmailActivity.java b/Meat-Loaf/src/com/cs301w01/meatload/activities/SendEmailActivity.java index 46395e6..284cb95 100644 --- a/Meat-Loaf/src/com/cs301w01/meatload/activities/SendEmailActivity.java +++ b/Meat-Loaf/src/com/cs301w01/meatload/activities/SendEmailActivity.java @@ -1,82 +1,81 @@ package com.cs301w01.meatload.activities; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.cs301w01.meatload.R; import com.cs301w01.meatload.model.Picture; import java.util.Collection; public class SendEmailActivity extends Skindactivity { Button sendButton; EditText textTo; EditText textSubject; EditText textMessage; private Picture picture; @Override /** * Adopted from: http://www.mkyong.com/android/how-to-send-email-in-android/ */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //picture = (Picture) getIntent().getExtras().getSerializable("picture"); sendButton = (Button) findViewById(R.id.buttonSend); textTo = (EditText) findViewById(R.id.editTextTo); textSubject = (EditText) findViewById(R.id.editTextSubject); textMessage = (EditText) findViewById(R.id.editTextMessage); //handle logic for when user chooses to send an email sendButton.setOnClickListener(new View.OnClickListener() { - @Override public void onClick(View v) { String recipient = textTo.getText().toString(); String subject = textSubject.getText().toString(); String message = textMessage.getText().toString(); Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient}); //email.putExtra(Intent.EXTRA_CC, new String[]{ recipient}); //email.putExtra(Intent.EXTRA_BCC, new String[]{recipient}); // email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + picture.getPath())); //add multiple photos // for(Picture picture: pictureAttachments){ // // email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + picture.getPath())); // // // } //add subject and additional message email.putExtra(Intent.EXTRA_SUBJECT, subject); email.putExtra(Intent.EXTRA_TEXT, message); //need this to prompts email client only email.setType("message/rfc822"); startActivity(Intent.createChooser(email, "Choose an Email client :")); } }); } @Override public void update(Object model) { //To change body of implemented methods use File | Settings | File Templates. } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //picture = (Picture) getIntent().getExtras().getSerializable("picture"); sendButton = (Button) findViewById(R.id.buttonSend); textTo = (EditText) findViewById(R.id.editTextTo); textSubject = (EditText) findViewById(R.id.editTextSubject); textMessage = (EditText) findViewById(R.id.editTextMessage); //handle logic for when user chooses to send an email sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String recipient = textTo.getText().toString(); String subject = textSubject.getText().toString(); String message = textMessage.getText().toString(); Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient}); //email.putExtra(Intent.EXTRA_CC, new String[]{ recipient}); //email.putExtra(Intent.EXTRA_BCC, new String[]{recipient}); // email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + picture.getPath())); //add multiple photos // for(Picture picture: pictureAttachments){ // // email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + picture.getPath())); // // // } //add subject and additional message email.putExtra(Intent.EXTRA_SUBJECT, subject); email.putExtra(Intent.EXTRA_TEXT, message); //need this to prompts email client only email.setType("message/rfc822"); startActivity(Intent.createChooser(email, "Choose an Email client :")); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //picture = (Picture) getIntent().getExtras().getSerializable("picture"); sendButton = (Button) findViewById(R.id.buttonSend); textTo = (EditText) findViewById(R.id.editTextTo); textSubject = (EditText) findViewById(R.id.editTextSubject); textMessage = (EditText) findViewById(R.id.editTextMessage); //handle logic for when user chooses to send an email sendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String recipient = textTo.getText().toString(); String subject = textSubject.getText().toString(); String message = textMessage.getText().toString(); Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient}); //email.putExtra(Intent.EXTRA_CC, new String[]{ recipient}); //email.putExtra(Intent.EXTRA_BCC, new String[]{recipient}); // email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + picture.getPath())); //add multiple photos // for(Picture picture: pictureAttachments){ // // email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + picture.getPath())); // // // } //add subject and additional message email.putExtra(Intent.EXTRA_SUBJECT, subject); email.putExtra(Intent.EXTRA_TEXT, message); //need this to prompts email client only email.setType("message/rfc822"); startActivity(Intent.createChooser(email, "Choose an Email client :")); } }); }
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java index ba99f2b27..083855ca7 100644 --- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java +++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IScrollTable.java @@ -1,2466 +1,2467 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.itmill.toolkit.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Vector; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.ScrollListener; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.Widget; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.BrowserInfo; import com.itmill.toolkit.terminal.gwt.client.Container; import com.itmill.toolkit.terminal.gwt.client.MouseEventDetails; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.RenderSpace; import com.itmill.toolkit.terminal.gwt.client.UIDL; import com.itmill.toolkit.terminal.gwt.client.Util; import com.itmill.toolkit.terminal.gwt.client.ui.IScrollTable.IScrollTableBody.IScrollTableRow; /** * IScrollTable * * IScrollTable is a FlowPanel having two widgets in it: * TableHead component * * ScrollPanel * * TableHead contains table's header and widgets + logic for resizing, * reordering and hiding columns. * * ScrollPanel contains IScrollTableBody object which handles content. To save * some bandwidth and to improve clients responsiveness with loads of data, in * IScrollTableBody all rows are not necessary rendered. There are "spacers" in * IScrollTableBody to use the exact same space as non-rendered rows would use. * This way we can use seamlessly traditional scrollbars and scrolling to fetch * more rows instead of "paging". * * In IScrollTable we listen to scroll events. On horizontal scrolling we also * update TableHeads scroll position which has its scrollbars hidden. On * vertical scroll events we will check if we are reaching the end of area where * we have rows rendered and * * TODO implement unregistering for child components in Cells */ public class IScrollTable extends FlowPanel implements Table, ScrollListener { public static final String CLASSNAME = "i-table"; /** * multiple of pagelength which component will cache when requesting more * rows */ private static final double CACHE_RATE = 2; /** * fraction of pageLenght which can be scrolled without making new request */ private static final double CACHE_REACT_RATE = 1.5; public static final char ALIGN_CENTER = 'c'; public static final char ALIGN_LEFT = 'b'; public static final char ALIGN_RIGHT = 'e'; private int firstRowInViewPort = 0; private int pageLength = 15; private int lastRequestedFirstvisible = 0; // to detect "serverside scroll" private boolean showRowHeaders = false; private String[] columnOrder; private ApplicationConnection client; private String paintableId; private boolean immediate; private int selectMode = Table.SELECT_MODE_NONE; private final HashSet selectedRowKeys = new HashSet(); private boolean initializedAndAttached = false; private final TableHead tHead = new TableHead(); private final ScrollPanel bodyContainer = new ScrollPanel(); private int totalRows; private Set<String> collapsedColumns; private final RowRequestHandler rowRequestHandler; private IScrollTableBody tBody; private int firstvisible = 0; private boolean sortAscending; private String sortColumn; private boolean columnReordering; /** * This map contains captions and icon urls for actions like: * "33_c" -> * "Edit" * "33_i" -> "http://dom.com/edit.png" */ private final HashMap actionMap = new HashMap(); private String[] visibleColOrder; private boolean initialContentReceived = false; private Element scrollPositionElement; private boolean enabled; private boolean showColHeaders; /** flag to indicate that table body has changed */ private boolean isNewBody = true; private boolean emitClickEvents; /* * Read from the "recalcWidths" -attribute. When it is true, the table will * recalculate the widths for columns - desirable in some cases. For #1983, * marked experimental. */ boolean recalcWidths = false; int scrollbarWidthReservedInColumn = -1; int scrollbarWidthReserved = -1; boolean relativeWidth = false; private final ArrayList lazyUnregistryBag = new ArrayList(); private String height; private String width = ""; public IScrollTable() { bodyContainer.addScrollListener(this); bodyContainer.setStyleName(CLASSNAME + "-body"); setStyleName(CLASSNAME); add(tHead); add(bodyContainer); rowRequestHandler = new RowRequestHandler(); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { if (client.updateComponent(this, uidl, true)) { return; } if (uidl.hasAttribute("width")) { relativeWidth = uidl.getStringAttribute("width").endsWith("%"); } // we may have pending cache row fetch, cancel it. See #2136 rowRequestHandler.cancel(); enabled = !uidl.hasAttribute("disabled"); this.client = client; paintableId = uidl.getStringAttribute("id"); immediate = uidl.getBooleanAttribute("immediate"); emitClickEvents = uidl.getBooleanAttribute("listenClicks"); final int newTotalRows = uidl.getIntAttribute("totalrows"); if (newTotalRows != totalRows) { if (tBody != null) { if (totalRows == 0) { tHead.clear(); } initializedAndAttached = false; initialContentReceived = false; isNewBody = true; } totalRows = newTotalRows; } recalcWidths = uidl.hasAttribute("recalcWidths"); pageLength = uidl.getIntAttribute("pagelength"); if (pageLength == 0) { pageLength = totalRows; } firstvisible = uidl.hasVariable("firstvisible") ? uidl .getIntVariable("firstvisible") : 0; if (firstvisible != lastRequestedFirstvisible && tBody != null) { // received 'surprising' firstvisible from server: scroll there firstRowInViewPort = firstvisible; bodyContainer .setScrollPosition(firstvisible * tBody.getRowHeight()); } showRowHeaders = uidl.getBooleanAttribute("rowheaders"); showColHeaders = uidl.getBooleanAttribute("colheaders"); if (uidl.hasVariable("sortascending")) { sortAscending = uidl.getBooleanVariable("sortascending"); sortColumn = uidl.getStringVariable("sortcolumn"); } if (uidl.hasVariable("selected")) { final Set selectedKeys = uidl .getStringArrayVariableAsSet("selected"); selectedRowKeys.clear(); for (final Iterator it = selectedKeys.iterator(); it.hasNext();) { selectedRowKeys.add(it.next()); } } if (uidl.hasAttribute("selectmode")) { if (uidl.getBooleanAttribute("readonly")) { selectMode = Table.SELECT_MODE_NONE; } else if (uidl.getStringAttribute("selectmode").equals("multi")) { selectMode = Table.SELECT_MODE_MULTI; } else if (uidl.getStringAttribute("selectmode").equals("single")) { selectMode = Table.SELECT_MODE_SINGLE; } else { selectMode = Table.SELECT_MODE_NONE; } } if (uidl.hasVariable("columnorder")) { columnReordering = true; columnOrder = uidl.getStringArrayVariable("columnorder"); } if (uidl.hasVariable("collapsedcolumns")) { tHead.setColumnCollapsingAllowed(true); collapsedColumns = uidl .getStringArrayVariableAsSet("collapsedcolumns"); } else { tHead.setColumnCollapsingAllowed(false); } UIDL rowData = null; for (final Iterator it = uidl.getChildIterator(); it.hasNext();) { final UIDL c = (UIDL) it.next(); if (c.getTag().equals("rows")) { rowData = c; } else if (c.getTag().equals("actions")) { updateActionMap(c); } else if (c.getTag().equals("visiblecolumns")) { tHead.updateCellsFromUIDL(c); } } updateHeader(uidl.getStringArrayAttribute("vcolorder")); if (!recalcWidths && initializedAndAttached) { updateBody(rowData, uidl.getIntAttribute("firstrow"), uidl .getIntAttribute("rows")); } else { if (tBody != null) { tBody.removeFromParent(); lazyUnregistryBag.add(tBody); } tBody = new IScrollTableBody(); tBody.renderInitialRows(rowData, uidl.getIntAttribute("firstrow"), uidl.getIntAttribute("rows")); bodyContainer.add(tBody); initialContentReceived = true; if (isAttached()) { sizeInit(); } } hideScrollPositionAnnotation(); purgeUnregistryBag(); } /** * Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or * IScrollTableRows). This is done lazily as Table must survive from * "subtreecaching" logic. */ private void purgeUnregistryBag() { for (Iterator iterator = lazyUnregistryBag.iterator(); iterator .hasNext();) { client.unregisterChildPaintables((HasWidgets) iterator.next()); } lazyUnregistryBag.clear(); } private void updateActionMap(UIDL c) { final Iterator it = c.getChildIterator(); while (it.hasNext()) { final UIDL action = (UIDL) it.next(); final String key = action.getStringAttribute("key"); final String caption = action.getStringAttribute("caption"); actionMap.put(key + "_c", caption); if (action.hasAttribute("icon")) { // TODO need some uri handling ?? actionMap.put(key + "_i", client.translateToolkitUri(action .getStringAttribute("icon"))); } } } public String getActionCaption(String actionKey) { return (String) actionMap.get(actionKey + "_c"); } public String getActionIcon(String actionKey) { return (String) actionMap.get(actionKey + "_i"); } private void updateHeader(String[] strings) { if (strings == null) { return; } int visibleCols = strings.length; int colIndex = 0; if (showRowHeaders) { tHead.enableColumn("0", colIndex); visibleCols++; visibleColOrder = new String[visibleCols]; visibleColOrder[colIndex] = "0"; colIndex++; } else { visibleColOrder = new String[visibleCols]; tHead.removeCell("0"); } int i; for (i = 0; i < strings.length; i++) { final String cid = strings[i]; visibleColOrder[colIndex] = cid; tHead.enableColumn(cid, colIndex); colIndex++; } tHead.setVisible(showColHeaders); } /** * @param uidl * which contains row data * @param firstRow * first row in data set * @param reqRows * amount of rows in data set */ private void updateBody(UIDL uidl, int firstRow, int reqRows) { if (uidl == null || reqRows < 1) { // container is empty, remove possibly existing rows if (firstRow < 0) { while (tBody.getLastRendered() > tBody.firstRendered) { tBody.unlinkRow(false); } tBody.unlinkRow(false); } return; } tBody.renderRows(uidl, firstRow, reqRows); final int optimalFirstRow = (int) (firstRowInViewPort - pageLength * CACHE_RATE); boolean cont = true; while (cont && tBody.getLastRendered() > optimalFirstRow && tBody.getFirstRendered() < optimalFirstRow) { // client.console.log("removing row from start"); cont = tBody.unlinkRow(true); } final int optimalLastRow = (int) (firstRowInViewPort + pageLength + pageLength * CACHE_RATE); cont = true; while (cont && tBody.getLastRendered() > optimalLastRow) { // client.console.log("removing row from the end"); cont = tBody.unlinkRow(false); } tBody.fixSpacers(); } /** * Gives correct column index for given column key ("cid" in UIDL). * * @param colKey * @return column index of visible columns, -1 if column not visible */ private int getColIndexByKey(String colKey) { // return 0 if asked for rowHeaders if ("0".equals(colKey)) { return 0; } for (int i = 0; i < visibleColOrder.length; i++) { if (visibleColOrder[i].equals(colKey)) { return i; } } return -1; } private boolean isCollapsedColumn(String colKey) { if (collapsedColumns == null) { return false; } if (collapsedColumns.contains(colKey)) { return true; } return false; } private String getColKeyByIndex(int index) { return tHead.getHeaderCell(index).getColKey(); } private void setColWidth(int colIndex, int w) { final HeaderCell cell = tHead.getHeaderCell(colIndex); cell.setWidth(w); tBody.setColWidth(colIndex, w); } private int getColWidth(String colKey) { return tHead.getHeaderCell(colKey).getWidth(); } private IScrollTableRow getRenderedRowByKey(String key) { final Iterator it = tBody.iterator(); IScrollTableRow r = null; while (it.hasNext()) { r = (IScrollTableRow) it.next(); if (r.getKey().equals(key)) { return r; } } return null; } private void reOrderColumn(String columnKey, int newIndex) { final int oldIndex = getColIndexByKey(columnKey); // Change header order tHead.moveCell(oldIndex, newIndex); // Change body order tBody.moveCol(oldIndex, newIndex); /* * Build new columnOrder and update it to server Note that columnOrder * also contains collapsed columns so we cannot directly build it from * cells vector Loop the old columnOrder and append in order to new * array unless on moved columnKey. On new index also put the moved key * i == index on columnOrder, j == index on newOrder */ final String oldKeyOnNewIndex = visibleColOrder[newIndex]; if (showRowHeaders) { newIndex--; // columnOrder don't have rowHeader } // add back hidden rows, for (int i = 0; i < columnOrder.length; i++) { if (columnOrder[i].equals(oldKeyOnNewIndex)) { break; // break loop at target } if (isCollapsedColumn(columnOrder[i])) { newIndex++; } } // finally we can build the new columnOrder for server final String[] newOrder = new String[columnOrder.length]; for (int i = 0, j = 0; j < newOrder.length; i++) { if (j == newIndex) { newOrder[j] = columnKey; j++; } if (i == columnOrder.length) { break; } if (columnOrder[i].equals(columnKey)) { continue; } newOrder[j] = columnOrder[i]; j++; } columnOrder = newOrder; // also update visibleColumnOrder int i = showRowHeaders ? 1 : 0; for (int j = 0; j < newOrder.length; j++) { final String cid = newOrder[j]; if (!isCollapsedColumn(cid)) { visibleColOrder[i++] = cid; } } client.updateVariable(paintableId, "columnorder", columnOrder, false); } protected void onAttach() { super.onAttach(); if (initialContentReceived) { sizeInit(); } } protected void onDetach() { rowRequestHandler.cancel(); super.onDetach(); // ensure that scrollPosElement will be detached if (scrollPositionElement != null) { final Element parent = DOM.getParent(scrollPositionElement); if (parent != null) { DOM.removeChild(parent, scrollPositionElement); } } } /** * Run only once when component is attached and received its initial * content. This function : * Syncs headers and bodys "natural widths and * saves the values. * Sets proper width and height * Makes deferred request * to get some cache rows */ private void sizeInit() { /* * We will use browsers table rendering algorithm to find proper column * widths. If content and header take less space than available, we will * divide extra space relatively to each column which has not width set. * * Overflow pixels are added to last column. */ Iterator headCells = tHead.iterator(); int i = 0; int totalExplicitColumnsWidths = 0; int total = 0; final int[] widths = new int[tHead.visibleCells.size()]; tHead.enableBrowserIntelligence(); // first loop: collect natural widths while (headCells.hasNext()) { final HeaderCell hCell = (HeaderCell) headCells.next(); int w = hCell.getWidth(); if (w > 0) { // server has defined column width explicitly totalExplicitColumnsWidths += w; } else { final int hw = hCell.getOffsetWidth(); final int cw = tBody.getColWidth(i); w = (hw > cw ? hw : cw) + IScrollTableBody.CELL_EXTRA_WIDTH; } widths[i] = w; total += w; i++; } tHead.disableBrowserIntelligence(); // fix "natural" height if height not set if (height == null || "".equals(height)) { bodyContainer.setHeight((tBody.getRowHeight() * pageLength) + "px"); } // fix "natural" width if width not set if (width == null || "".equals(width)) { int w = total; w += getScrollbarWidth(); setContentWidth(w); } int availW = tBody.getAvailableWidth(); // Hey IE, are you really sure about this? availW = tBody.getAvailableWidth(); boolean needsReLayout = false; if (availW > total) { // natural size is smaller than available space int extraSpace = availW - total; int totalWidthR = total - totalExplicitColumnsWidths; if (totalWidthR > 0) { needsReLayout = true; /* * If the table has a relative width and there is enough space * for a scrollbar we reserve this in the last column */ int scrollbarWidth = getScrollbarWidth(); + scrollbarWidth = Util.getNativeScrollbarSize(); if (relativeWidth && totalWidthR >= scrollbarWidth) { scrollbarWidthReserved = scrollbarWidth + 1; // widths[tHead.getVisibleCellCount() - 1] += scrollbarWidthReserved; totalWidthR += scrollbarWidthReserved; extraSpace -= scrollbarWidthReserved; scrollbarWidthReservedInColumn = tHead .getVisibleCellCount() - 1; } // now we will share this sum relatively to those without // explicit width headCells = tHead.iterator(); i = 0; HeaderCell hCell; while (headCells.hasNext()) { hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; final int newSpace = extraSpace * w / totalWidthR; w += newSpace; widths[i] = w; } i++; } } } else { // bodys size will be more than available and scrollbar will appear } // last loop: set possibly modified values or reset if new tBody i = 0; headCells = tHead.iterator(); while (headCells.hasNext()) { final HeaderCell hCell = (HeaderCell) headCells.next(); if (isNewBody || hCell.getWidth() == -1) { final int w = widths[i]; setColWidth(i, w); } i++; } if (needsReLayout) { tBody.reLayoutComponents(); } isNewBody = false; if (firstvisible > 0) { // Deferred due some Firefox oddities. IE & Safari could survive // without DeferredCommand.addCommand(new Command() { public void execute() { bodyContainer.setScrollPosition(firstvisible * tBody.getRowHeight()); firstRowInViewPort = firstvisible; } }); } if (enabled) { // Do we need cache rows if (tBody.getLastRendered() + 1 < firstRowInViewPort + pageLength + CACHE_REACT_RATE * pageLength) { if (totalRows - 1 > tBody.getLastRendered()) { // fetch cache rows rowRequestHandler .setReqFirstRow(tBody.getLastRendered() + 1); rowRequestHandler .setReqRows((int) (pageLength * CACHE_RATE)); rowRequestHandler.deferRowFetch(1); } } } initializedAndAttached = true; } private int getScrollbarWidth() { if (BrowserInfo.get().isIE6()) { return Util.measureHorizontalBorder(bodyContainer.getElement()); } return bodyContainer.getOffsetWidth() - DOM.getElementPropertyInt(bodyContainer.getElement(), "clientWidth"); } /** * This method has logic which rows needs to be requested from server when * user scrolls */ public void onScroll(Widget widget, int scrollLeft, int scrollTop) { if (!initializedAndAttached) { return; } if (!enabled) { bodyContainer.setScrollPosition(firstRowInViewPort * tBody.getRowHeight()); return; } rowRequestHandler.cancel(); // fix headers horizontal scrolling tHead.setHorizontalScrollPosition(scrollLeft); firstRowInViewPort = (int) Math.ceil(scrollTop / (double) tBody.getRowHeight()); // ApplicationConnection.getConsole().log( // "At scrolltop: " + scrollTop + " At row " + firstRowInViewPort); int postLimit = (int) (firstRowInViewPort + pageLength + pageLength * CACHE_REACT_RATE); if (postLimit > totalRows - 1) { postLimit = totalRows - 1; } int preLimit = (int) (firstRowInViewPort - pageLength * CACHE_REACT_RATE); if (preLimit < 0) { preLimit = 0; } final int lastRendered = tBody.getLastRendered(); final int firstRendered = tBody.getFirstRendered(); if (postLimit <= lastRendered && preLimit >= firstRendered) { // remember which firstvisible we requested, in case the server has // a differing opinion lastRequestedFirstvisible = firstRowInViewPort; client.updateVariable(paintableId, "firstvisible", firstRowInViewPort, false); return; // scrolled withing "non-react area" } if (firstRowInViewPort - pageLength * CACHE_RATE > lastRendered || firstRowInViewPort + pageLength + pageLength * CACHE_RATE < firstRendered) { // need a totally new set // ApplicationConnection.getConsole().log( // "Table: need a totally new set"); rowRequestHandler .setReqFirstRow((int) (firstRowInViewPort - pageLength * CACHE_RATE)); int last = firstRowInViewPort + (int) CACHE_RATE * pageLength + pageLength; if (last > totalRows) { last = totalRows - 1; } rowRequestHandler.setReqRows(last - rowRequestHandler.getReqFirstRow() + 1); rowRequestHandler.deferRowFetch(); return; } if (preLimit < firstRendered) { // need some rows to the beginning of the rendered area // ApplicationConnection // .getConsole() // .log( // "Table: need some rows to the beginning of the rendered area"); rowRequestHandler .setReqFirstRow((int) (firstRowInViewPort - pageLength * CACHE_RATE)); rowRequestHandler.setReqRows(firstRendered - rowRequestHandler.getReqFirstRow()); rowRequestHandler.deferRowFetch(); return; } if (postLimit > lastRendered) { // need some rows to the end of the rendered area // ApplicationConnection.getConsole().log( // "need some rows to the end of the rendered area"); rowRequestHandler.setReqFirstRow(lastRendered + 1); rowRequestHandler.setReqRows((int) ((firstRowInViewPort + pageLength + pageLength * CACHE_RATE) - lastRendered)); rowRequestHandler.deferRowFetch(); } } private void announceScrollPosition() { if (scrollPositionElement == null) { scrollPositionElement = DOM.createDiv(); DOM.setElementProperty(scrollPositionElement, "className", "i-table-scrollposition"); DOM.appendChild(getElement(), scrollPositionElement); } DOM.setStyleAttribute(scrollPositionElement, "position", "absolute"); DOM.setStyleAttribute(scrollPositionElement, "marginLeft", (DOM .getElementPropertyInt(getElement(), "offsetWidth") / 2 - 80) + "px"); DOM.setStyleAttribute(scrollPositionElement, "marginTop", -(DOM .getElementPropertyInt(getElement(), "offsetHeight") - 2) + "px"); // indexes go from 1-totalRows, as rowheaders in index-mode indicate int last = (firstRowInViewPort + (bodyContainer.getOffsetHeight() / tBody .getRowHeight())); if (last > totalRows) { last = totalRows; } DOM.setInnerHTML(scrollPositionElement, "<span>" + (firstRowInViewPort + 1) + " &ndash; " + last + "..." + "</span>"); DOM.setStyleAttribute(scrollPositionElement, "display", "block"); } private void hideScrollPositionAnnotation() { if (scrollPositionElement != null) { DOM.setStyleAttribute(scrollPositionElement, "display", "none"); } } private class RowRequestHandler extends Timer { private int reqFirstRow = 0; private int reqRows = 0; public void deferRowFetch() { deferRowFetch(250); } public void deferRowFetch(int msec) { if (reqRows > 0 && reqFirstRow < totalRows) { schedule(msec); // tell scroll position to user if currently "visible" rows are // not rendered if ((firstRowInViewPort + pageLength > tBody.getLastRendered()) || (firstRowInViewPort < tBody.getFirstRendered())) { announceScrollPosition(); } else { hideScrollPositionAnnotation(); } } } public void setReqFirstRow(int reqFirstRow) { if (reqFirstRow < 0) { reqFirstRow = 0; } else if (reqFirstRow >= totalRows) { reqFirstRow = totalRows - 1; } this.reqFirstRow = reqFirstRow; } public void setReqRows(int reqRows) { this.reqRows = reqRows; } public void run() { if (client.hasActiveRequest()) { // if client connection is busy, don't bother loading it more schedule(250); ApplicationConnection.getConsole().log( "Table: AC is busy, deferring cache row fetch.."); } else { ApplicationConnection.getConsole().log( "Getting " + reqRows + " rows from " + reqFirstRow); int firstToBeRendered = tBody.firstRendered; if (reqFirstRow < firstToBeRendered) { firstToBeRendered = reqFirstRow; } else if (firstRowInViewPort - (int) (CACHE_RATE * pageLength) > firstToBeRendered) { firstToBeRendered = firstRowInViewPort - (int) (CACHE_RATE * pageLength); if (firstToBeRendered < 0) { firstToBeRendered = 0; } } int lastToBeRendered = tBody.lastRendered; if (reqFirstRow + reqRows - 1 > lastToBeRendered) { lastToBeRendered = reqFirstRow + reqRows - 1; } else if (firstRowInViewPort + pageLength + pageLength * CACHE_RATE < lastToBeRendered) { lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * CACHE_RATE)); if (lastToBeRendered >= totalRows) { lastToBeRendered = totalRows - 1; } } client.updateVariable(paintableId, "firstToBeRendered", firstToBeRendered, false); client.updateVariable(paintableId, "lastToBeRendered", lastToBeRendered, false); // remember which firstvisible we requested, in case the server // has // a differing opinion lastRequestedFirstvisible = firstRowInViewPort; client.updateVariable(paintableId, "firstvisible", firstRowInViewPort, false); client.updateVariable(paintableId, "reqfirstrow", reqFirstRow, false); client.updateVariable(paintableId, "reqrows", reqRows, true); } } public int getReqFirstRow() { return reqFirstRow; } public int getReqRows() { return reqRows; } /** * Sends request to refresh content at this position. */ public void refreshContent() { int first = (int) (firstRowInViewPort - pageLength * CACHE_RATE); int reqRows = (int) (2 * pageLength * CACHE_RATE + pageLength); if (first < 0) { reqRows = reqRows + first; first = 0; } setReqFirstRow(first); setReqRows(reqRows); run(); } } public class HeaderCell extends Widget { private static final int DRAG_WIDGET_WIDTH = 4; private static final int MINIMUM_COL_WIDTH = 20; Element td = DOM.createTD(); Element captionContainer = DOM.createDiv(); Element colResizeWidget = DOM.createDiv(); Element floatingCopyOfHeaderCell; private boolean sortable = false; private final String cid; private boolean dragging; private int dragStartX; private int colIndex; private int originalWidth; private boolean isResizing; private int headerX; private boolean moved; private int closestSlot; private int width = -1; private char align = ALIGN_LEFT; public void setSortable(boolean b) { sortable = b; } public HeaderCell(String colId, String headerText) { cid = colId; DOM.setElementProperty(colResizeWidget, "className", CLASSNAME + "-resizer"); DOM.setStyleAttribute(colResizeWidget, "width", DRAG_WIDGET_WIDTH + "px"); DOM.sinkEvents(colResizeWidget, Event.MOUSEEVENTS); setText(headerText); DOM.appendChild(td, colResizeWidget); DOM.setElementProperty(captionContainer, "className", CLASSNAME + "-caption-container"); // ensure no clipping initially (problem on column additions) DOM.setStyleAttribute(captionContainer, "overflow", "visible"); DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS); DOM.appendChild(td, captionContainer); DOM.sinkEvents(td, Event.MOUSEEVENTS); setElement(td); } public void setWidth(int w) { if (width == -1) { // go to default mode, clip content if necessary DOM.setStyleAttribute(captionContainer, "overflow", ""); } width = w; if (w == -1) { DOM.setStyleAttribute(captionContainer, "width", ""); setWidth(""); } else { DOM.setStyleAttribute(captionContainer, "width", (w - DRAG_WIDGET_WIDTH - 4) + "px"); setWidth(w + "px"); } } public int getWidth() { return width; } public void setText(String headerText) { DOM.setInnerHTML(captionContainer, headerText); } public String getColKey() { return cid; } private void setSorted(boolean sorted) { if (sorted) { if (sortAscending) { this.setStyleName(CLASSNAME + "-header-cell-asc"); } else { this.setStyleName(CLASSNAME + "-header-cell-desc"); } } else { this.setStyleName(CLASSNAME + "-header-cell"); } } /** * Handle column reordering. */ public void onBrowserEvent(Event event) { if (enabled && event != null) { if (isResizing || event.getTarget() == colResizeWidget) { onResizeEvent(event); } else { handleCaptionEvent(event); } } } private void createFloatingCopy() { floatingCopyOfHeaderCell = DOM.createDiv(); DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td)); floatingCopyOfHeaderCell = DOM .getChild(floatingCopyOfHeaderCell, 1); DOM.setElementProperty(floatingCopyOfHeaderCell, "className", CLASSNAME + "-header-drag"); updateFloatingCopysPosition(DOM.getAbsoluteLeft(td), DOM .getAbsoluteTop(td)); DOM.appendChild(RootPanel.get().getElement(), floatingCopyOfHeaderCell); } private void updateFloatingCopysPosition(int x, int y) { x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell, "offsetWidth") / 2; DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px"); if (y > 0) { DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7) + "px"); } } private void hideFloatingCopy() { DOM.removeChild(RootPanel.get().getElement(), floatingCopyOfHeaderCell); floatingCopyOfHeaderCell = null; } protected void handleCaptionEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: ApplicationConnection.getConsole().log( "HeaderCaption: mouse down"); if (columnReordering) { dragging = true; moved = false; colIndex = getColIndexByKey(cid); DOM.setCapture(getElement()); headerX = tHead.getAbsoluteLeft(); ApplicationConnection .getConsole() .log( "HeaderCaption: Caption set to capture mouse events"); DOM.eventPreventDefault(event); // prevent selecting text } break; case Event.ONMOUSEUP: ApplicationConnection.getConsole() .log("HeaderCaption: mouseUP"); if (columnReordering) { dragging = false; DOM.releaseCapture(getElement()); ApplicationConnection.getConsole().log( "HeaderCaption: Stopped column reordering"); if (moved) { hideFloatingCopy(); tHead.removeSlotFocus(); if (closestSlot != colIndex && closestSlot != (colIndex + 1)) { if (closestSlot > colIndex) { reOrderColumn(cid, closestSlot - 1); } else { reOrderColumn(cid, closestSlot); } } } } if (!moved) { // mouse event was a click to header -> sort column if (sortable) { if (sortColumn.equals(cid)) { // just toggle order client.updateVariable(paintableId, "sortascending", !sortAscending, false); } else { // set table scrolled by this column client.updateVariable(paintableId, "sortcolumn", cid, false); } // get also cache columns at the same request bodyContainer.setScrollPosition(0); firstvisible = 0; rowRequestHandler.setReqFirstRow(0); rowRequestHandler.setReqRows((int) (2 * pageLength * CACHE_RATE + pageLength)); rowRequestHandler.deferRowFetch(); } break; } break; case Event.ONMOUSEMOVE: if (dragging) { ApplicationConnection.getConsole().log( "HeaderCaption: Dragging column, optimal index..."); if (!moved) { createFloatingCopy(); moved = true; } final int x = DOM.eventGetClientX(event) + DOM.getElementPropertyInt(tHead.hTableWrapper, "scrollLeft"); int slotX = headerX; closestSlot = colIndex; int closestDistance = -1; int start = 0; if (showRowHeaders) { start++; } final int visibleCellCount = tHead.getVisibleCellCount(); for (int i = start; i <= visibleCellCount; i++) { if (i > 0) { final String colKey = getColKeyByIndex(i - 1); slotX += getColWidth(colKey); } final int dist = Math.abs(x - slotX); if (closestDistance == -1 || dist < closestDistance) { closestDistance = dist; closestSlot = i; } } tHead.focusSlot(closestSlot); updateFloatingCopysPosition(DOM.eventGetClientX(event), -1); ApplicationConnection.getConsole().log("" + closestSlot); } break; default: break; } } private void onResizeEvent(Event event) { switch (DOM.eventGetType(event)) { case Event.ONMOUSEDOWN: isResizing = true; DOM.setCapture(getElement()); dragStartX = DOM.eventGetClientX(event); colIndex = getColIndexByKey(cid); originalWidth = getWidth(); DOM.eventPreventDefault(event); break; case Event.ONMOUSEUP: isResizing = false; DOM.releaseCapture(getElement()); tBody.reLayoutComponents(); break; case Event.ONMOUSEMOVE: if (isResizing) { final int deltaX = DOM.eventGetClientX(event) - dragStartX; if (deltaX == 0) { return; } int newWidth = originalWidth + deltaX; if (newWidth < MINIMUM_COL_WIDTH) { newWidth = MINIMUM_COL_WIDTH; } setColWidth(colIndex, newWidth); } break; default: break; } } public String getCaption() { return DOM.getInnerText(captionContainer); } public boolean isEnabled() { return getParent() != null; } public void setAlign(char c) { if (align != c) { switch (c) { case ALIGN_CENTER: DOM.setStyleAttribute(captionContainer, "textAlign", "center"); break; case ALIGN_RIGHT: DOM.setStyleAttribute(captionContainer, "textAlign", "right"); break; default: DOM.setStyleAttribute(captionContainer, "textAlign", ""); break; } } align = c; } public char getAlign() { return align; } } /** * HeaderCell that is header cell for row headers. * * Reordering disabled and clicking on it resets sorting. */ public class RowHeadersHeaderCell extends HeaderCell { RowHeadersHeaderCell() { super("0", ""); } protected void handleCaptionEvent(Event event) { // NOP: RowHeaders cannot be reordered // TODO It'd be nice to reset sorting here } } public class TableHead extends Panel implements ActionOwner { private static final int WRAPPER_WIDTH = 9000; Vector visibleCells = new Vector(); HashMap availableCells = new HashMap(); Element div = DOM.createDiv(); Element hTableWrapper = DOM.createDiv(); Element hTableContainer = DOM.createDiv(); Element table = DOM.createTable(); Element headerTableBody = DOM.createTBody(); Element tr = DOM.createTR(); private final Element columnSelector = DOM.createDiv(); private int focusedSlot = -1; public TableHead() { DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden"); DOM.setElementProperty(hTableWrapper, "className", CLASSNAME + "-header"); // TODO move styles to CSS DOM.setElementProperty(columnSelector, "className", CLASSNAME + "-column-selector"); DOM.setStyleAttribute(columnSelector, "display", "none"); DOM.appendChild(table, headerTableBody); DOM.appendChild(headerTableBody, tr); DOM.appendChild(hTableContainer, table); DOM.appendChild(hTableWrapper, hTableContainer); DOM.appendChild(div, hTableWrapper); DOM.appendChild(div, columnSelector); setElement(div); setStyleName(CLASSNAME + "-header-wrap"); DOM.sinkEvents(columnSelector, Event.ONCLICK); availableCells.put("0", new RowHeadersHeaderCell()); } public void clear() { for (Iterator iterator = availableCells.keySet().iterator(); iterator .hasNext();) { String cid = (String) iterator.next(); removeCell(cid); } availableCells.clear(); availableCells.put("0", new RowHeadersHeaderCell()); } public void updateCellsFromUIDL(UIDL uidl) { Iterator it = uidl.getChildIterator(); HashSet updated = new HashSet(); updated.add("0"); while (it.hasNext()) { final UIDL col = (UIDL) it.next(); final String cid = col.getStringAttribute("cid"); updated.add(cid); String caption = buildCaptionHtmlSnippet(col); HeaderCell c = getHeaderCell(cid); if (c == null) { c = new HeaderCell(cid, caption); availableCells.put(cid, c); if (initializedAndAttached) { // we will need a column width recalculation initializedAndAttached = false; initialContentReceived = false; isNewBody = true; } } else { c.setText(caption); } if (col.hasAttribute("sortable")) { c.setSortable(true); if (cid.equals(sortColumn)) { c.setSorted(true); } else { c.setSorted(false); } } if (col.hasAttribute("align")) { c.setAlign(col.getStringAttribute("align").charAt(0)); } if (col.hasAttribute("width")) { final String width = col.getStringAttribute("width"); c.setWidth(Integer.parseInt(width)); } else if (recalcWidths) { c.setWidth(-1); } } // check for orphaned header cells it = availableCells.keySet().iterator(); while (it.hasNext()) { String cid = (String) it.next(); if (!updated.contains(cid)) { removeCell(cid); it.remove(); } } } public void enableColumn(String cid, int index) { final HeaderCell c = getHeaderCell(cid); if (!c.isEnabled() || getHeaderCell(index) != c) { setHeaderCell(index, c); if (c.getWidth() == -1) { if (initializedAndAttached) { // column is not drawn before, // we will need a column width recalculation initializedAndAttached = false; initialContentReceived = false; isNewBody = true; } } } } public int getVisibleCellCount() { return visibleCells.size(); } public void setHorizontalScrollPosition(int scrollLeft) { DOM.setElementPropertyInt(hTableWrapper, "scrollLeft", scrollLeft); } public void setColumnCollapsingAllowed(boolean cc) { if (cc) { DOM.setStyleAttribute(columnSelector, "display", "block"); } else { DOM.setStyleAttribute(columnSelector, "display", "none"); } } public void disableBrowserIntelligence() { DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH + "px"); } public void enableBrowserIntelligence() { DOM.setStyleAttribute(hTableContainer, "width", ""); } public void setHeaderCell(int index, HeaderCell cell) { if (cell.isEnabled()) { // we're moving the cell DOM.removeChild(tr, cell.getElement()); orphan(cell); } if (index < visibleCells.size()) { // insert to right slot DOM.insertChild(tr, cell.getElement(), index); adopt(cell); visibleCells.insertElementAt(cell, index); } else if (index == visibleCells.size()) { // simply append DOM.appendChild(tr, cell.getElement()); adopt(cell); visibleCells.add(cell); } else { throw new RuntimeException( "Header cells must be appended in order"); } } public HeaderCell getHeaderCell(int index) { if (index < visibleCells.size()) { return (HeaderCell) visibleCells.get(index); } else { return null; } } /** * Get's HeaderCell by it's column Key. * * Note that this returns HeaderCell even if it is currently collapsed. * * @param cid * Column key of accessed HeaderCell * @return HeaderCell */ public HeaderCell getHeaderCell(String cid) { return (HeaderCell) availableCells.get(cid); } public void moveCell(int oldIndex, int newIndex) { final HeaderCell hCell = getHeaderCell(oldIndex); final Element cell = hCell.getElement(); visibleCells.remove(oldIndex); DOM.removeChild(tr, cell); DOM.insertChild(tr, cell, newIndex); visibleCells.insertElementAt(hCell, newIndex); } public Iterator iterator() { return visibleCells.iterator(); } public boolean remove(Widget w) { if (visibleCells.contains(w)) { visibleCells.remove(w); orphan(w); DOM.removeChild(DOM.getParent(w.getElement()), w.getElement()); return true; } return false; } public void removeCell(String colKey) { final HeaderCell c = getHeaderCell(colKey); remove(c); } private void focusSlot(int index) { removeSlotFocus(); if (index > 0) { DOM.setElementProperty(DOM.getFirstChild(DOM.getChild(tr, index - 1)), "className", CLASSNAME + "-resizer " + CLASSNAME + "-focus-slot-right"); } else { DOM.setElementProperty(DOM.getFirstChild(DOM .getChild(tr, index)), "className", CLASSNAME + "-resizer " + CLASSNAME + "-focus-slot-left"); } focusedSlot = index; } private void removeSlotFocus() { if (focusedSlot < 0) { return; } if (focusedSlot == 0) { DOM.setElementProperty(DOM.getFirstChild(DOM.getChild(tr, focusedSlot)), "className", CLASSNAME + "-resizer"); } else if (focusedSlot > 0) { DOM.setElementProperty(DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)), "className", CLASSNAME + "-resizer"); } focusedSlot = -1; } public void onBrowserEvent(Event event) { if (enabled) { if (event.getTarget() == columnSelector) { final int left = DOM.getAbsoluteLeft(columnSelector); final int top = DOM.getAbsoluteTop(columnSelector) + DOM.getElementPropertyInt(columnSelector, "offsetHeight"); client.getContextMenu().showAt(this, left, top); } } } class VisibleColumnAction extends Action { String colKey; private boolean collapsed; public VisibleColumnAction(String colKey) { super(IScrollTable.TableHead.this); this.colKey = colKey; caption = tHead.getHeaderCell(colKey).getCaption(); } public void execute() { client.getContextMenu().hide(); // toggle selected column if (collapsedColumns.contains(colKey)) { collapsedColumns.remove(colKey); } else { tHead.removeCell(colKey); collapsedColumns.add(colKey); } // update variable to server client.updateVariable(paintableId, "collapsedcolumns", collapsedColumns.toArray(), false); // let rowRequestHandler determine proper rows rowRequestHandler.refreshContent(); } public void setCollapsed(boolean b) { collapsed = b; } /** * Override default method to distinguish on/off columns */ public String getHTML() { final StringBuffer buf = new StringBuffer(); if (collapsed) { buf.append("<span class=\"i-off\">"); } else { buf.append("<span class=\"i-on\">"); } buf.append(super.getHTML()); buf.append("</span>"); return buf.toString(); } } /* * Returns columns as Action array for column select popup */ public Action[] getActions() { Object[] cols; if (columnReordering) { cols = columnOrder; } else { // if columnReordering is disabled, we need different way to get // all available columns cols = visibleColOrder; cols = new Object[visibleColOrder.length + collapsedColumns.size()]; int i; for (i = 0; i < visibleColOrder.length; i++) { cols[i] = visibleColOrder[i]; } for (final Iterator it = collapsedColumns.iterator(); it .hasNext();) { cols[i++] = it.next(); } } final Action[] actions = new Action[cols.length]; for (int i = 0; i < cols.length; i++) { final String cid = (String) cols[i]; final HeaderCell c = getHeaderCell(cid); final VisibleColumnAction a = new VisibleColumnAction(c .getColKey()); a.setCaption(c.getCaption()); if (!c.isEnabled()) { a.setCollapsed(true); } actions[i] = a; } return actions; } public ApplicationConnection getClient() { return client; } public String getPaintableId() { return paintableId; } /** * Returns column alignments for visible columns */ public char[] getColumnAlignments() { final Iterator it = visibleCells.iterator(); final char[] aligns = new char[visibleCells.size()]; int colIndex = 0; while (it.hasNext()) { aligns[colIndex++] = ((HeaderCell) it.next()).getAlign(); } return aligns; } } /** * This Panel can only contain IScrollTableRow type of widgets. This * "simulates" very large table, keeping spacers which take room of * unrendered rows. * */ public class IScrollTableBody extends Panel { public static final int CELL_EXTRA_WIDTH = 20; public static final int DEFAULT_ROW_HEIGHT = 24; /** * Amount of padding inside one table cell (this is reduced from the * "cellContent" element's width). You may override this in your own * widgetset. */ public static final int CELL_CONTENT_PADDING = 8; private int rowHeight = -1; private final List renderedRows = new Vector(); private boolean initDone = false; Element preSpacer = DOM.createDiv(); Element postSpacer = DOM.createDiv(); Element container = DOM.createDiv(); Element tBody = DOM.createTBody(); Element table = DOM.createTable(); private int firstRendered; private int lastRendered; private char[] aligns; IScrollTableBody() { constructDOM(); setElement(container); } private void constructDOM() { DOM.setElementProperty(table, "className", CLASSNAME + "-table"); DOM.setElementProperty(preSpacer, "className", CLASSNAME + "-row-spacer"); DOM.setElementProperty(postSpacer, "className", CLASSNAME + "-row-spacer"); DOM.appendChild(table, tBody); DOM.appendChild(container, preSpacer); DOM.appendChild(container, table); DOM.appendChild(container, postSpacer); } public int getAvailableWidth() { return DOM.getElementPropertyInt(preSpacer, "offsetWidth"); } public void renderInitialRows(UIDL rowData, int firstIndex, int rows) { firstRendered = firstIndex; lastRendered = firstIndex + rows - 1; final Iterator it = rowData.getChildIterator(); aligns = tHead.getColumnAlignments(); while (it.hasNext()) { final IScrollTableRow row = new IScrollTableRow((UIDL) it .next(), aligns); addRow(row); } if (isAttached()) { fixSpacers(); } } public void renderRows(UIDL rowData, int firstIndex, int rows) { // FIXME REVIEW aligns = tHead.getColumnAlignments(); final Iterator it = rowData.getChildIterator(); if (firstIndex == lastRendered + 1) { while (it.hasNext()) { final IScrollTableRow row = createRow((UIDL) it.next()); addRow(row); lastRendered++; } fixSpacers(); } else if (firstIndex + rows == firstRendered) { final IScrollTableRow[] rowArray = new IScrollTableRow[rows]; int i = rows; while (it.hasNext()) { i--; rowArray[i] = createRow((UIDL) it.next()); } for (i = 0; i < rows; i++) { addRowBeforeFirstRendered(rowArray[i]); firstRendered--; } } else { // completely new set of rows while (lastRendered + 1 > firstRendered) { unlinkRow(false); } final IScrollTableRow row = createRow((UIDL) it.next()); firstRendered = firstIndex; lastRendered = firstIndex - 1; addRow(row); lastRendered++; setContainerHeight(); fixSpacers(); while (it.hasNext()) { addRow(createRow((UIDL) it.next())); lastRendered++; } fixSpacers(); } // this may be a new set of rows due content change, // ensure we have proper cache rows int reactFirstRow = (int) (firstRowInViewPort - pageLength * CACHE_REACT_RATE); int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength * CACHE_REACT_RATE); if (reactFirstRow < 0) { reactFirstRow = 0; } if (reactLastRow > totalRows) { reactLastRow = totalRows - 1; } if (lastRendered < reactLastRow) { // get some cache rows below visible area rowRequestHandler.setReqFirstRow(lastRendered + 1); rowRequestHandler.setReqRows(reactLastRow - lastRendered - 1); rowRequestHandler.deferRowFetch(1); } else if (IScrollTable.this.tBody.getFirstRendered() > reactFirstRow) { /* * Branch for fetching cache above visible area. * * If cache needed for both before and after visible area, this * will be rendered after-cache is reveived and rendered. So in * some rare situations table may take two cache visits to * server. */ rowRequestHandler.setReqFirstRow(reactFirstRow); rowRequestHandler.setReqRows(firstRendered - reactFirstRow); rowRequestHandler.deferRowFetch(1); } } /** * This method is used to instantiate new rows for this table. It * automatically sets correct widths to rows cells and assigns correct * client reference for child widgets. * * This method can be called only after table has been initialized * * @param uidl */ private IScrollTableRow createRow(UIDL uidl) { final IScrollTableRow row = new IScrollTableRow(uidl, aligns); final int cells = DOM.getChildCount(row.getElement()); for (int i = 0; i < cells; i++) { final Element cell = DOM.getChild(row.getElement(), i); final int w = IScrollTable.this .getColWidth(getColKeyByIndex(i)); DOM.setStyleAttribute(DOM.getFirstChild(cell), "width", (w - CELL_CONTENT_PADDING) + "px"); DOM.setStyleAttribute(cell, "width", w + "px"); } return row; } private void addRowBeforeFirstRendered(IScrollTableRow row) { IScrollTableRow first = null; if (renderedRows.size() > 0) { first = (IScrollTableRow) renderedRows.get(0); } if (first != null && first.getStyleName().indexOf("-odd") == -1) { row.addStyleName(CLASSNAME + "-row-odd"); } else { row.addStyleName(CLASSNAME + "-row"); } if (row.isSelected()) { row.addStyleName("i-selected"); } DOM.insertChild(tBody, row.getElement(), 0); adopt(row); renderedRows.add(0, row); } private void addRow(IScrollTableRow row) { IScrollTableRow last = null; if (renderedRows.size() > 0) { last = (IScrollTableRow) renderedRows .get(renderedRows.size() - 1); } if (last != null && last.getStyleName().indexOf("-odd") == -1) { row.addStyleName(CLASSNAME + "-row-odd"); } else { row.addStyleName(CLASSNAME + "-row"); } if (row.isSelected()) { row.addStyleName("i-selected"); } DOM.appendChild(tBody, row.getElement()); adopt(row); renderedRows.add(row); } public Iterator iterator() { return renderedRows.iterator(); } /** * @return false if couldn't remove row */ public boolean unlinkRow(boolean fromBeginning) { if (lastRendered - firstRendered < 0) { return false; } int index; if (fromBeginning) { index = 0; firstRendered++; } else { index = renderedRows.size() - 1; lastRendered--; } final IScrollTableRow toBeRemoved = (IScrollTableRow) renderedRows .get(index); lazyUnregistryBag.add(toBeRemoved); DOM.removeChild(tBody, toBeRemoved.getElement()); orphan(toBeRemoved); renderedRows.remove(index); fixSpacers(); return true; } public boolean remove(Widget w) { throw new UnsupportedOperationException(); } protected void onAttach() { super.onAttach(); setContainerHeight(); } /** * Fix container blocks height according to totalRows to avoid * "bouncing" when scrolling */ private void setContainerHeight() { fixSpacers(); DOM.setStyleAttribute(container, "height", totalRows * getRowHeight() + "px"); } private void fixSpacers() { int prepx = getRowHeight() * firstRendered; if (prepx < 0) { prepx = 0; } DOM.setStyleAttribute(preSpacer, "height", prepx + "px"); int postpx = getRowHeight() * (totalRows - 1 - lastRendered); if (postpx < 0) { postpx = 0; } DOM.setStyleAttribute(postSpacer, "height", postpx + "px"); } public int getRowHeight() { if (initDone) { return rowHeight; } else { if (DOM.getChildCount(tBody) > 0) { rowHeight = DOM .getElementPropertyInt(tBody, "offsetHeight") / DOM.getChildCount(tBody); } else { return DEFAULT_ROW_HEIGHT; } initDone = true; return rowHeight; } } public int getColWidth(int i) { if (initDone) { final Element e = DOM.getChild(DOM.getChild(tBody, 0), i); return DOM.getElementPropertyInt(e, "offsetWidth"); } else { return 0; } } public void setColWidth(int colIndex, int w) { final int rows = DOM.getChildCount(tBody); for (int i = 0; i < rows; i++) { final Element cell = DOM.getChild(DOM.getChild(tBody, i), colIndex); DOM.setStyleAttribute(DOM.getFirstChild(cell), "width", (w - CELL_CONTENT_PADDING) + "px"); DOM.setStyleAttribute(cell, "width", w + "px"); } } private void reLayoutComponents() { for (Widget w : this) { IScrollTableRow r = (IScrollTableRow) w; for (Widget widget : r) { client.handleComponentRelativeSize(widget); } } } public int getLastRendered() { return lastRendered; } public int getFirstRendered() { return firstRendered; } public void moveCol(int oldIndex, int newIndex) { // loop all rows and move given index to its new place final Iterator rows = iterator(); while (rows.hasNext()) { final IScrollTableRow row = (IScrollTableRow) rows.next(); final Element td = DOM.getChild(row.getElement(), oldIndex); DOM.removeChild(row.getElement(), td); DOM.insertChild(row.getElement(), td, newIndex); } } public class IScrollTableRow extends Panel implements ActionOwner, Container { Vector childWidgets = new Vector(); private boolean selected = false; private final int rowKey; private List<UIDL> pendingComponentPaints; private String[] actionKeys = null; private IScrollTableRow(int rowKey) { this.rowKey = rowKey; setElement(DOM.createElement("tr")); DOM.sinkEvents(getElement(), Event.ONCLICK | Event.ONDBLCLICK | Event.ONCONTEXTMENU); } private void paintComponent(Paintable p, UIDL uidl) { if (isAttached()) { p.updateFromUIDL(uidl, client); } else { if (pendingComponentPaints == null) { pendingComponentPaints = new LinkedList<UIDL>(); } pendingComponentPaints.add(uidl); } } @Override protected void onAttach() { super.onAttach(); if (pendingComponentPaints != null) { for (UIDL uidl : pendingComponentPaints) { Paintable paintable = client.getPaintable(uidl); paintable.updateFromUIDL(uidl, client); } } } public String getKey() { return String.valueOf(rowKey); } public IScrollTableRow(UIDL uidl, char[] aligns) { this(uidl.getIntAttribute("key")); String rowStyle = uidl.getStringAttribute("rowstyle"); if (rowStyle != null) { addStyleName(CLASSNAME + "-row-" + rowStyle); } tHead.getColumnAlignments(); int col = 0; int visibleColumnIndex = -1; // row header if (showRowHeaders) { addCell(buildCaptionHtmlSnippet(uidl), aligns[col++], ""); } if (uidl.hasAttribute("al")) { actionKeys = uidl.getStringArrayAttribute("al"); } final Iterator cells = uidl.getChildIterator(); while (cells.hasNext()) { final Object cell = cells.next(); visibleColumnIndex++; String columnId = visibleColOrder[visibleColumnIndex]; String style = ""; if (uidl.hasAttribute("style-" + columnId)) { style = uidl.getStringAttribute("style-" + columnId); } if (cell instanceof String) { addCell(cell.toString(), aligns[col++], style); } else { final Paintable cellContent = client .getPaintable((UIDL) cell); addCell((Widget) cellContent, aligns[col++], style); paintComponent(cellContent, (UIDL) cell); } } if (uidl.hasAttribute("selected") && !isSelected()) { toggleSelection(); } } public void addCell(String text, char align, String style) { // String only content is optimized by not using Label widget final Element td = DOM.createTD(); final Element container = DOM.createDiv(); String className = CLASSNAME + "-cell-content"; if (style != null && !style.equals("")) { className += " " + CLASSNAME + "-cell-content-" + style; } DOM.setElementProperty(container, "className", className); DOM.setInnerText(container, text); if (align != ALIGN_LEFT) { switch (align) { case ALIGN_CENTER: DOM.setStyleAttribute(container, "textAlign", "center"); break; case ALIGN_RIGHT: default: DOM.setStyleAttribute(container, "textAlign", "right"); break; } } DOM.appendChild(td, container); DOM.appendChild(getElement(), td); } public void addCell(Widget w, char align, String style) { final Element td = DOM.createTD(); final Element container = DOM.createDiv(); String className = CLASSNAME + "-cell-content"; if (style != null && !style.equals("")) { className += " " + CLASSNAME + "-cell-content-" + style; } DOM.setElementProperty(container, "className", className); // TODO most components work with this, but not all (e.g. // Select) // Old comment: make widget cells respect align. // text-align:center for IE, margin: auto for others if (align != ALIGN_LEFT) { switch (align) { case ALIGN_CENTER: DOM.setStyleAttribute(container, "textAlign", "center"); break; case ALIGN_RIGHT: default: DOM.setStyleAttribute(container, "textAlign", "right"); break; } } DOM.appendChild(td, container); DOM.appendChild(getElement(), td); // ensure widget not attached to another element (possible tBody // change) w.removeFromParent(); DOM.appendChild(container, w.getElement()); adopt(w); childWidgets.add(w); } public Iterator iterator() { return childWidgets.iterator(); } public boolean remove(Widget w) { if (childWidgets.contains(w)) { orphan(w); DOM.removeChild(DOM.getParent(w.getElement()), w .getElement()); childWidgets.remove(w); return true; } else { return false; } } private void handleClickEvent(Event event) { if (emitClickEvents) { boolean dbl = DOM.eventGetType(event) == Event.ONDBLCLICK; final Element tdOrTr = DOM.getParent(DOM .eventGetTarget(event)); client.updateVariable(paintableId, "clickedKey", "" + rowKey, false); if (getElement() == tdOrTr.getParentElement()) { int childIndex = DOM .getChildIndex(getElement(), tdOrTr); String colKey = null; colKey = tHead.getHeaderCell(childIndex).getColKey(); client.updateVariable(paintableId, "clickedColKey", colKey, false); } MouseEventDetails details = new MouseEventDetails(event); // Note: the 'immediate' logic would need to be more // involved (see #2104), but iscrolltable always sends // select event, even though nullselectionallowed wont let // the change trough. Will need to be updated if that is // changed. client .updateVariable( paintableId, "clickEvent", details.toString(), !(!dbl && selectMode > Table.SELECT_MODE_NONE && immediate)); } } /* * React on click that occur on content cells only */ public void onBrowserEvent(Event event) { final Element tdOrTr = DOM.getParent(DOM.eventGetTarget(event)); if (getElement() == tdOrTr || getElement() == tdOrTr.getParentElement()) { switch (DOM.eventGetType(event)) { case Event.ONCLICK: handleClickEvent(event); if (selectMode > Table.SELECT_MODE_NONE) { toggleSelection(); // Note: changing the immediateness of this might // require changes to "clickEvent" immediateness // also. client.updateVariable(paintableId, "selected", selectedRowKeys.toArray(), immediate); } break; case Event.ONDBLCLICK: handleClickEvent(event); break; case Event.ONCONTEXTMENU: showContextMenu(event); break; default: break; } } super.onBrowserEvent(event); } public void showContextMenu(Event event) { if (enabled && actionKeys != null) { int left = event.getClientX(); int top = event.getClientY(); top += Window.getScrollTop(); left += Window.getScrollLeft(); client.getContextMenu().showAt(this, left, top); } event.cancelBubble(true); event.preventDefault(); } public boolean isSelected() { return selected; } private void toggleSelection() { selected = !selected; if (selected) { if (selectMode == Table.SELECT_MODE_SINGLE) { deselectAll(); } selectedRowKeys.add(String.valueOf(rowKey)); addStyleName("i-selected"); } else { selectedRowKeys.remove(String.valueOf(rowKey)); removeStyleName("i-selected"); } } /* * (non-Javadoc) * * @see * com.itmill.toolkit.terminal.gwt.client.ui.IActionOwner#getActions * () */ public Action[] getActions() { if (actionKeys == null) { return new Action[] {}; } final Action[] actions = new Action[actionKeys.length]; for (int i = 0; i < actions.length; i++) { final String actionKey = actionKeys[i]; final TreeAction a = new TreeAction(this, String .valueOf(rowKey), actionKey); a.setCaption(getActionCaption(actionKey)); a.setIconUrl(getActionIcon(actionKey)); actions[i] = a; } return actions; } public ApplicationConnection getClient() { return client; } public String getPaintableId() { return paintableId; } public RenderSpace getAllocatedSpace(Widget child) { int w = 0; int i = getColIndexOf(child); HeaderCell headerCell = tHead.getHeaderCell(i); if (headerCell != null) { if (initializedAndAttached) { w = headerCell.getWidth() - CELL_CONTENT_PADDING; } else { // header offset width is not absolutely correct value, // but // a best guess (expecting similar content in all // columns -> // if one component is relative width so are others) w = headerCell.getOffsetWidth() - CELL_CONTENT_PADDING; } } return new RenderSpace(w, getRowHeight()); } private int getColIndexOf(Widget child) { com.google.gwt.dom.client.Element widgetCell = child .getElement().getParentElement().getParentElement(); com.google.gwt.dom.client.Element td = getElement() .getFirstChildElement(); int index = 0; while (td != widgetCell && td.getNextSiblingElement() != null) { index++; td = td.getNextSiblingElement(); } return index; } public boolean hasChildComponent(Widget component) { return childWidgets.contains(component); } public void replaceChildComponent(Widget oldComponent, Widget newComponent) { com.google.gwt.dom.client.Element parentElement = oldComponent .getElement().getParentElement(); int index = childWidgets.indexOf(oldComponent); oldComponent.removeFromParent(); parentElement.appendChild(newComponent.getElement()); childWidgets.insertElementAt(newComponent, index); adopt(newComponent); } public boolean requestLayout(Set<Paintable> children) { // row size should never change and system wouldn't event // survive as this is a kind of fake paitable return true; } public void updateCaption(Paintable component, UIDL uidl) { // NOP, not rendered } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // Should never be called, // Component container interface faked here to get layouts // render properly } } } public void deselectAll() { final Object[] keys = selectedRowKeys.toArray(); for (int i = 0; i < keys.length; i++) { final IScrollTableRow row = getRenderedRowByKey((String) keys[i]); if (row != null && row.isSelected()) { row.toggleSelection(); } } // still ensure all selects are removed from (not necessary rendered) selectedRowKeys.clear(); } public void setWidth(String width) { if (this.width.equals(width)) { return; } this.width = width; if (width != null && !"".equals(width)) { int oldWidth = getOffsetWidth(); super.setWidth(width); int newWidth = getOffsetWidth(); if (scrollbarWidthReservedInColumn != -1 && oldWidth > newWidth && (oldWidth - newWidth) < scrollbarWidthReserved) { int col = scrollbarWidthReservedInColumn; String colKey = getColKeyByIndex(col); setColWidth(scrollbarWidthReservedInColumn, getColWidth(colKey) - (oldWidth - newWidth)); scrollbarWidthReservedInColumn = -1; } int innerPixels = getOffsetWidth() - getBorderWidth(); if (innerPixels < 0) { innerPixels = 0; } setContentWidth(innerPixels); } else { super.setWidth(""); } } /** * helper to set pixel size of head and body part * * @param pixels */ private void setContentWidth(int pixels) { tHead.setWidth(pixels + "px"); bodyContainer.setWidth(pixels + "px"); } private int borderWidth = -1; /** * @return border left + border right */ private int getBorderWidth() { if (borderWidth < 0) { borderWidth = Util.measureHorizontalPaddingAndBorder(bodyContainer .getElement(), 2); if (borderWidth < 0) { borderWidth = 0; } } return borderWidth; } /** * Ensures scrollable area is properly sized. */ private void setContainerHeight() { if (height != null && !"".equals(height)) { int contentH = getOffsetHeight() - tHead.getOffsetHeight(); contentH -= getContentAreaBorderHeight(); if (contentH < 0) { contentH = 0; } bodyContainer.setHeight(contentH + "px"); } } private int contentAreaBorderHeight = -1; /** * @return border top + border bottom of the scrollable area of table */ private int getContentAreaBorderHeight() { if (contentAreaBorderHeight < 0) { DOM.setStyleAttribute(bodyContainer.getElement(), "overflow", "hidden"); contentAreaBorderHeight = bodyContainer.getOffsetHeight() - bodyContainer.getElement().getPropertyInt("clientHeight"); DOM.setStyleAttribute(bodyContainer.getElement(), "overflow", "auto"); } return contentAreaBorderHeight; } public void setHeight(String height) { this.height = height; super.setHeight(height); setContainerHeight(); } /* * Overridden due Table might not survive of visibility change (scroll pos * lost). Example ITabPanel just set contained components invisible and back * when changing tabs. */ public void setVisible(boolean visible) { if (isVisible() != visible) { super.setVisible(visible); if (initializedAndAttached) { if (visible) { DeferredCommand.addCommand(new Command() { public void execute() { bodyContainer.setScrollPosition(firstRowInViewPort * tBody.getRowHeight()); } }); } } } } /** * Helper function to build html snippet for column or row headers * * @param uidl * possibly with values caption and icon * @return html snippet containing possibly an icon + caption text */ private String buildCaptionHtmlSnippet(UIDL uidl) { String s = uidl.getStringAttribute("caption"); if (uidl.hasAttribute("icon")) { s = "<img src=\"" + client.translateToolkitUri(uidl .getStringAttribute("icon")) + "\" alt=\"icon\" class=\"i-icon\">" + s; } return s; } }
true
true
private void sizeInit() { /* * We will use browsers table rendering algorithm to find proper column * widths. If content and header take less space than available, we will * divide extra space relatively to each column which has not width set. * * Overflow pixels are added to last column. */ Iterator headCells = tHead.iterator(); int i = 0; int totalExplicitColumnsWidths = 0; int total = 0; final int[] widths = new int[tHead.visibleCells.size()]; tHead.enableBrowserIntelligence(); // first loop: collect natural widths while (headCells.hasNext()) { final HeaderCell hCell = (HeaderCell) headCells.next(); int w = hCell.getWidth(); if (w > 0) { // server has defined column width explicitly totalExplicitColumnsWidths += w; } else { final int hw = hCell.getOffsetWidth(); final int cw = tBody.getColWidth(i); w = (hw > cw ? hw : cw) + IScrollTableBody.CELL_EXTRA_WIDTH; } widths[i] = w; total += w; i++; } tHead.disableBrowserIntelligence(); // fix "natural" height if height not set if (height == null || "".equals(height)) { bodyContainer.setHeight((tBody.getRowHeight() * pageLength) + "px"); } // fix "natural" width if width not set if (width == null || "".equals(width)) { int w = total; w += getScrollbarWidth(); setContentWidth(w); } int availW = tBody.getAvailableWidth(); // Hey IE, are you really sure about this? availW = tBody.getAvailableWidth(); boolean needsReLayout = false; if (availW > total) { // natural size is smaller than available space int extraSpace = availW - total; int totalWidthR = total - totalExplicitColumnsWidths; if (totalWidthR > 0) { needsReLayout = true; /* * If the table has a relative width and there is enough space * for a scrollbar we reserve this in the last column */ int scrollbarWidth = getScrollbarWidth(); if (relativeWidth && totalWidthR >= scrollbarWidth) { scrollbarWidthReserved = scrollbarWidth + 1; // widths[tHead.getVisibleCellCount() - 1] += scrollbarWidthReserved; totalWidthR += scrollbarWidthReserved; extraSpace -= scrollbarWidthReserved; scrollbarWidthReservedInColumn = tHead .getVisibleCellCount() - 1; } // now we will share this sum relatively to those without // explicit width headCells = tHead.iterator(); i = 0; HeaderCell hCell; while (headCells.hasNext()) { hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; final int newSpace = extraSpace * w / totalWidthR; w += newSpace; widths[i] = w; } i++; } } } else { // bodys size will be more than available and scrollbar will appear } // last loop: set possibly modified values or reset if new tBody i = 0; headCells = tHead.iterator(); while (headCells.hasNext()) { final HeaderCell hCell = (HeaderCell) headCells.next(); if (isNewBody || hCell.getWidth() == -1) { final int w = widths[i]; setColWidth(i, w); } i++; } if (needsReLayout) { tBody.reLayoutComponents(); } isNewBody = false; if (firstvisible > 0) { // Deferred due some Firefox oddities. IE & Safari could survive // without DeferredCommand.addCommand(new Command() { public void execute() { bodyContainer.setScrollPosition(firstvisible * tBody.getRowHeight()); firstRowInViewPort = firstvisible; } }); } if (enabled) { // Do we need cache rows if (tBody.getLastRendered() + 1 < firstRowInViewPort + pageLength + CACHE_REACT_RATE * pageLength) { if (totalRows - 1 > tBody.getLastRendered()) { // fetch cache rows rowRequestHandler .setReqFirstRow(tBody.getLastRendered() + 1); rowRequestHandler .setReqRows((int) (pageLength * CACHE_RATE)); rowRequestHandler.deferRowFetch(1); } } } initializedAndAttached = true; }
private void sizeInit() { /* * We will use browsers table rendering algorithm to find proper column * widths. If content and header take less space than available, we will * divide extra space relatively to each column which has not width set. * * Overflow pixels are added to last column. */ Iterator headCells = tHead.iterator(); int i = 0; int totalExplicitColumnsWidths = 0; int total = 0; final int[] widths = new int[tHead.visibleCells.size()]; tHead.enableBrowserIntelligence(); // first loop: collect natural widths while (headCells.hasNext()) { final HeaderCell hCell = (HeaderCell) headCells.next(); int w = hCell.getWidth(); if (w > 0) { // server has defined column width explicitly totalExplicitColumnsWidths += w; } else { final int hw = hCell.getOffsetWidth(); final int cw = tBody.getColWidth(i); w = (hw > cw ? hw : cw) + IScrollTableBody.CELL_EXTRA_WIDTH; } widths[i] = w; total += w; i++; } tHead.disableBrowserIntelligence(); // fix "natural" height if height not set if (height == null || "".equals(height)) { bodyContainer.setHeight((tBody.getRowHeight() * pageLength) + "px"); } // fix "natural" width if width not set if (width == null || "".equals(width)) { int w = total; w += getScrollbarWidth(); setContentWidth(w); } int availW = tBody.getAvailableWidth(); // Hey IE, are you really sure about this? availW = tBody.getAvailableWidth(); boolean needsReLayout = false; if (availW > total) { // natural size is smaller than available space int extraSpace = availW - total; int totalWidthR = total - totalExplicitColumnsWidths; if (totalWidthR > 0) { needsReLayout = true; /* * If the table has a relative width and there is enough space * for a scrollbar we reserve this in the last column */ int scrollbarWidth = getScrollbarWidth(); scrollbarWidth = Util.getNativeScrollbarSize(); if (relativeWidth && totalWidthR >= scrollbarWidth) { scrollbarWidthReserved = scrollbarWidth + 1; // widths[tHead.getVisibleCellCount() - 1] += scrollbarWidthReserved; totalWidthR += scrollbarWidthReserved; extraSpace -= scrollbarWidthReserved; scrollbarWidthReservedInColumn = tHead .getVisibleCellCount() - 1; } // now we will share this sum relatively to those without // explicit width headCells = tHead.iterator(); i = 0; HeaderCell hCell; while (headCells.hasNext()) { hCell = (HeaderCell) headCells.next(); if (hCell.getWidth() == -1) { int w = widths[i]; final int newSpace = extraSpace * w / totalWidthR; w += newSpace; widths[i] = w; } i++; } } } else { // bodys size will be more than available and scrollbar will appear } // last loop: set possibly modified values or reset if new tBody i = 0; headCells = tHead.iterator(); while (headCells.hasNext()) { final HeaderCell hCell = (HeaderCell) headCells.next(); if (isNewBody || hCell.getWidth() == -1) { final int w = widths[i]; setColWidth(i, w); } i++; } if (needsReLayout) { tBody.reLayoutComponents(); } isNewBody = false; if (firstvisible > 0) { // Deferred due some Firefox oddities. IE & Safari could survive // without DeferredCommand.addCommand(new Command() { public void execute() { bodyContainer.setScrollPosition(firstvisible * tBody.getRowHeight()); firstRowInViewPort = firstvisible; } }); } if (enabled) { // Do we need cache rows if (tBody.getLastRendered() + 1 < firstRowInViewPort + pageLength + CACHE_REACT_RATE * pageLength) { if (totalRows - 1 > tBody.getLastRendered()) { // fetch cache rows rowRequestHandler .setReqFirstRow(tBody.getLastRendered() + 1); rowRequestHandler .setReqRows((int) (pageLength * CACHE_RATE)); rowRequestHandler.deferRowFetch(1); } } } initializedAndAttached = true; }
diff --git a/src/com/android/gallery3d/filtershow/PanelController.java b/src/com/android/gallery3d/filtershow/PanelController.java index a852632dc..3a24d00aa 100644 --- a/src/com/android/gallery3d/filtershow/PanelController.java +++ b/src/com/android/gallery3d/filtershow/PanelController.java @@ -1,582 +1,583 @@ /* * 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.gallery3d.filtershow; import android.content.Context; import android.text.Html; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewPropertyAnimator; import android.widget.LinearLayout; import android.widget.TextView; import com.android.gallery3d.R; import com.android.gallery3d.filtershow.editors.Editor; import com.android.gallery3d.filtershow.filters.ImageFilter; import com.android.gallery3d.filtershow.filters.ImageFilterTinyPlanet; import com.android.gallery3d.filtershow.imageshow.ImageCrop; import com.android.gallery3d.filtershow.imageshow.ImageShow; import com.android.gallery3d.filtershow.imageshow.MasterImage; import com.android.gallery3d.filtershow.presets.ImagePreset; import com.android.gallery3d.filtershow.ui.FilterIconButton; import com.android.gallery3d.filtershow.ui.FramedTextButton; import java.util.HashMap; import java.util.Vector; public class PanelController implements OnClickListener { private static int PANEL = 0; private static int COMPONENT = 1; private static int VERTICAL_MOVE = 0; private static int HORIZONTAL_MOVE = 1; private static final int ANIM_DURATION = 200; private static final String LOGTAG = "PanelController"; private boolean mDisableFilterButtons = false; private boolean mFixedAspect = false; public void setFixedAspect(boolean t) { mFixedAspect = t; } class Panel { private final View mView; private final View mContainer; private int mPosition = 0; private final Vector<View> mSubviews = new Vector<View>(); public Panel(View view, View container, int position) { mView = view; mContainer = container; mPosition = position; } public void addView(View view) { mSubviews.add(view); } public int getPosition() { return mPosition; } public ViewPropertyAnimator unselect(int newPos, int move) { ViewPropertyAnimator anim = mContainer.animate(); mView.setSelected(false); mContainer.setX(0); mContainer.setY(0); int delta = 0; int w = mRowPanel.getWidth(); int h = mRowPanel.getHeight(); if (move == HORIZONTAL_MOVE) { if (newPos > mPosition) { delta = -w; } else { delta = w; } anim.x(delta); } else if (move == VERTICAL_MOVE) { anim.y(h); } anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() { @Override public void run() { mContainer.setVisibility(View.GONE); } }); return anim; } public ViewPropertyAnimator select(int oldPos, int move) { mView.setSelected(true); mContainer.setVisibility(View.VISIBLE); mContainer.setX(0); mContainer.setY(0); ViewPropertyAnimator anim = mContainer.animate(); int w = mRowPanel.getWidth(); int h = mRowPanel.getHeight(); if (move == HORIZONTAL_MOVE) { if (oldPos < mPosition) { mContainer.setX(w); } else { mContainer.setX(-w); } anim.x(0); } else if (move == VERTICAL_MOVE) { mContainer.setY(h); anim.y(0); } anim.setDuration(ANIM_DURATION).withLayer(); return anim; } } class UtilityPanel { private final Context mContext; private final View mView; private final LinearLayout mAccessoryViewList; private Vector<View> mAccessoryViews = new Vector<View>(); private final TextView mTextView; private boolean mSelected = false; private String mEffectName = null; private int mParameterValue = 0; private boolean mShowParameterValue = false; boolean firstTimeCropDisplayed = true; public UtilityPanel(Context context, View view, View accessoryViewList, View textView) { mContext = context; mView = view; mAccessoryViewList = (LinearLayout) accessoryViewList; mTextView = (TextView) textView; } public boolean selected() { return mSelected; } public void hideAccessoryViews() { int childCount = mAccessoryViewList.getChildCount(); for (int i = 0; i < childCount; i++) { View child = mAccessoryViewList.getChildAt(i); child.setVisibility(View.GONE); } } public void onNewValue(int value) { mParameterValue = value; updateText(); } public void setEffectName(String effectName) { mEffectName = effectName; setShowParameter(true); } public void setShowParameter(boolean s) { mShowParameterValue = s; updateText(); } public void updateText() { String apply = mContext.getString(R.string.apply_effect); if (mShowParameterValue) { mTextView.setText(Html.fromHtml(apply + " " + mEffectName + " " + mParameterValue)); } else { mTextView.setText(Html.fromHtml(apply + " " + mEffectName)); } } public ViewPropertyAnimator unselect() { ViewPropertyAnimator anim = mView.animate(); mView.setX(0); mView.setY(0); int h = mRowPanel.getHeight(); anim.y(-h); anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() { @Override public void run() { mView.setVisibility(View.GONE); } }); mSelected = false; return anim; } public ViewPropertyAnimator select() { mView.setVisibility(View.VISIBLE); int h = mRowPanel.getHeight(); mView.setX(0); mView.setY(-h); updateText(); ViewPropertyAnimator anim = mView.animate(); anim.y(0); anim.setDuration(ANIM_DURATION).withLayer(); mSelected = true; return anim; } } class ViewType { private final int mType; private final View mView; public ViewType(View view, int type) { mView = view; mType = type; } public int type() { return mType; } } private final HashMap<View, Panel> mPanels = new HashMap<View, Panel>(); private final HashMap<View, ViewType> mViews = new HashMap<View, ViewType>(); private final HashMap<String, ImageFilter> mFilters = new HashMap<String, ImageFilter>(); private final Vector<View> mImageViews = new Vector<View>(); private View mCurrentPanel = null; private View mRowPanel = null; private UtilityPanel mUtilityPanel = null; private MasterImage mMasterImage = MasterImage.getImage(); private ImageShow mCurrentImage = null; private Editor mCurrentEditor = null; private FilterShowActivity mActivity = null; private EditorPlaceHolder mEditorPlaceHolder = null; public void setActivity(FilterShowActivity activity) { mActivity = activity; } public void addView(View view) { view.setOnClickListener(this); mViews.put(view, new ViewType(view, COMPONENT)); } public void addPanel(View view, View container, int position) { mPanels.put(view, new Panel(view, container, position)); view.setOnClickListener(this); mViews.put(view, new ViewType(view, PANEL)); } public void addComponent(View aPanel, View component) { Panel panel = mPanels.get(aPanel); if (panel == null) { return; } panel.addView(component); component.setOnClickListener(this); mViews.put(component, new ViewType(component, COMPONENT)); } public void addFilter(ImageFilter filter) { mFilters.put(filter.getName(), filter); } public void addImageView(View view) { mImageViews.add(view); ImageShow imageShow = (ImageShow) view; imageShow.setPanelController(this); } public void resetParameters() { showPanel(mCurrentPanel); if (mCurrentImage != null) { mCurrentImage.resetParameter(); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); } } if (mDisableFilterButtons) { mActivity.enableFilterButtons(); mDisableFilterButtons = false; } } public boolean onBackPressed() { if (mUtilityPanel == null || !mUtilityPanel.selected()) { return true; } HistoryAdapter adapter = mMasterImage.getHistory(); int position = adapter.undo(); mMasterImage.onHistoryItemClick(position); showPanel(mCurrentPanel); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); } if (mDisableFilterButtons) { mActivity.enableFilterButtons(); mActivity.resetHistory(); mDisableFilterButtons = false; } return false; } public void onNewValue(int value) { mUtilityPanel.onNewValue(value); } public void showParameter(boolean s) { mUtilityPanel.setShowParameter(s); } public void setCurrentPanel(View panel) { showPanel(panel); } public void setRowPanel(View rowPanel) { mRowPanel = rowPanel; } public void setUtilityPanel(Context context, View utilityPanel, View accessoryViewList, View textView) { mUtilityPanel = new UtilityPanel(context, utilityPanel, accessoryViewList, textView); } @Override public void onClick(View view) { ViewType type = mViews.get(view); if (type.type() == PANEL) { showPanel(view); } else if (type.type() == COMPONENT) { showComponent(view); } } public ImageShow showImageView(int id) { ImageShow image = null; mActivity.hideImageViews(); for (View view : mImageViews) { if (view.getId() == id) { view.setVisibility(View.VISIBLE); image = (ImageShow) view; } else { view.setVisibility(View.GONE); } } return image; } public void showDefaultImageView() { showImageView(R.id.imageShow).setShowControls(false); mMasterImage.setCurrentFilter(null); mMasterImage.setCurrentFilterRepresentation(null); } public void showPanel(View view) { view.setVisibility(View.VISIBLE); boolean removedUtilityPanel = false; Panel current = mPanels.get(mCurrentPanel); if (mUtilityPanel != null && mUtilityPanel.selected()) { ViewPropertyAnimator anim1 = mUtilityPanel.unselect(); removedUtilityPanel = true; anim1.start(); if (mCurrentPanel == view) { ViewPropertyAnimator anim2 = current.select(-1, VERTICAL_MOVE); anim2.start(); showDefaultImageView(); } } if (mCurrentPanel == view) { return; } Panel panel = mPanels.get(view); if (!removedUtilityPanel) { int currentPos = -1; if (current != null) { currentPos = current.getPosition(); } ViewPropertyAnimator anim1 = panel.select(currentPos, HORIZONTAL_MOVE); anim1.start(); if (current != null) { ViewPropertyAnimator anim2 = current.unselect(panel.getPosition(), HORIZONTAL_MOVE); anim2.start(); } } else { ViewPropertyAnimator anim = panel.select(-1, VERTICAL_MOVE); anim.start(); } showDefaultImageView(); mCurrentPanel = view; } public ImagePreset getImagePreset() { return mMasterImage.getPreset(); } /** public ImageFilter setImagePreset(ImageFilter filter, String name) { ImagePreset copy = new ImagePreset(getImagePreset()); copy.add(filter); copy.setHistoryName(name); copy.setIsFx(false); mMasterImage.setPreset(copy, true); return filter; } */ // TODO: remove this. public void ensureFilter(String name) { /* ImagePreset preset = getImagePreset(); ImageFilter filter = preset.getFilter(name); if (filter != null) { // If we already have a filter, we might still want // to push it onto the history stack. ImagePreset copy = new ImagePreset(getImagePreset()); copy.setHistoryName(name); mMasterImage.setPreset(copy, true); filter = copy.getFilter(name); } if (filter == null) { ImageFilter filterInstance = mFilters.get(name); if (filterInstance != null) { try { ImageFilter newFilter = filterInstance.clone(); newFilter.reset(); filter = setImagePreset(newFilter, name); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } if (filter != null) { mMasterImage.setCurrentFilter(filter); } */ } public void showComponent(View view) { boolean doPanelTransition = true; if (view instanceof FilterIconButton) { ImageFilter f = ((FilterIconButton) view).getImageFilter(); doPanelTransition = f.showUtilityPanel(); } if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) { Panel current = mPanels.get(mCurrentPanel); ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE); anim1.start(); if (mUtilityPanel != null) { ViewPropertyAnimator anim2 = mUtilityPanel.select(); anim2.start(); } } if (mCurrentImage != null) { mCurrentImage.unselect(); } mUtilityPanel.hideAccessoryViews(); if (view instanceof FilterIconButton) { mCurrentEditor = null; FilterIconButton component = (FilterIconButton) view; ImageFilter filter = component.getImageFilter(); if (filter.getEditingViewId() != 0) { if (mEditorPlaceHolder.contains(filter.getEditingViewId())) { mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId()); mCurrentImage = mCurrentEditor.getImageShow(); mCurrentEditor.setPanelController(this); } else { mCurrentImage = showImageView(filter.getEditingViewId()); } mCurrentImage.setShowControls(filter.showEditingControls()); String ename = mCurrentImage.getContext().getString(filter.getTextId()); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(filter.showParameterValue()); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } return; } switch (view.getId()) { case R.id.tinyplanetButton: { mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.tinyplanet); mUtilityPanel.setEffectName(ename); ensureFilter(ename); if (!mDisableFilterButtons) { mActivity.disableFilterButtons(); mDisableFilterButtons = true; } break; } case R.id.straightenButton: { mCurrentImage = showImageView(R.id.imageStraighten); String ename = mCurrentImage.getContext().getString(R.string.straighten); mUtilityPanel.setEffectName(ename); break; } case R.id.cropButton: { mCurrentImage = showImageView(R.id.imageCrop); String ename = mCurrentImage.getContext().getString(R.string.crop); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) { ((ImageCrop) mCurrentImage).clear(); mUtilityPanel.firstTimeCropDisplayed = false; } ((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect); break; } case R.id.rotateButton: { mCurrentImage = showImageView(R.id.imageRotate); String ename = mCurrentImage.getContext().getString(R.string.rotate); mUtilityPanel.setEffectName(ename); break; } case R.id.flipButton: { mCurrentImage = showImageView(R.id.imageFlip); String ename = mCurrentImage.getContext().getString(R.string.mirror); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); break; } case R.id.redEyeButton: { mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.redeye); mUtilityPanel.setEffectName(ename); ensureFilter(ename); break; } case R.id.applyEffect: { if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) { mActivity.saveImage(); } else { if (mCurrentImage instanceof ImageCrop) { ((ImageCrop) mCurrentImage).saveAndSetPreset(); } showPanel(mCurrentPanel); } + MasterImage.getImage().invalidateFiltersOnly(); break; } } mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } public void setEditorPlaceHolder(EditorPlaceHolder editorPlaceHolder) { mEditorPlaceHolder = editorPlaceHolder; } }
true
true
public void showComponent(View view) { boolean doPanelTransition = true; if (view instanceof FilterIconButton) { ImageFilter f = ((FilterIconButton) view).getImageFilter(); doPanelTransition = f.showUtilityPanel(); } if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) { Panel current = mPanels.get(mCurrentPanel); ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE); anim1.start(); if (mUtilityPanel != null) { ViewPropertyAnimator anim2 = mUtilityPanel.select(); anim2.start(); } } if (mCurrentImage != null) { mCurrentImage.unselect(); } mUtilityPanel.hideAccessoryViews(); if (view instanceof FilterIconButton) { mCurrentEditor = null; FilterIconButton component = (FilterIconButton) view; ImageFilter filter = component.getImageFilter(); if (filter.getEditingViewId() != 0) { if (mEditorPlaceHolder.contains(filter.getEditingViewId())) { mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId()); mCurrentImage = mCurrentEditor.getImageShow(); mCurrentEditor.setPanelController(this); } else { mCurrentImage = showImageView(filter.getEditingViewId()); } mCurrentImage.setShowControls(filter.showEditingControls()); String ename = mCurrentImage.getContext().getString(filter.getTextId()); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(filter.showParameterValue()); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } return; } switch (view.getId()) { case R.id.tinyplanetButton: { mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.tinyplanet); mUtilityPanel.setEffectName(ename); ensureFilter(ename); if (!mDisableFilterButtons) { mActivity.disableFilterButtons(); mDisableFilterButtons = true; } break; } case R.id.straightenButton: { mCurrentImage = showImageView(R.id.imageStraighten); String ename = mCurrentImage.getContext().getString(R.string.straighten); mUtilityPanel.setEffectName(ename); break; } case R.id.cropButton: { mCurrentImage = showImageView(R.id.imageCrop); String ename = mCurrentImage.getContext().getString(R.string.crop); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) { ((ImageCrop) mCurrentImage).clear(); mUtilityPanel.firstTimeCropDisplayed = false; } ((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect); break; } case R.id.rotateButton: { mCurrentImage = showImageView(R.id.imageRotate); String ename = mCurrentImage.getContext().getString(R.string.rotate); mUtilityPanel.setEffectName(ename); break; } case R.id.flipButton: { mCurrentImage = showImageView(R.id.imageFlip); String ename = mCurrentImage.getContext().getString(R.string.mirror); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); break; } case R.id.redEyeButton: { mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.redeye); mUtilityPanel.setEffectName(ename); ensureFilter(ename); break; } case R.id.applyEffect: { if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) { mActivity.saveImage(); } else { if (mCurrentImage instanceof ImageCrop) { ((ImageCrop) mCurrentImage).saveAndSetPreset(); } showPanel(mCurrentPanel); } break; } } mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } }
public void showComponent(View view) { boolean doPanelTransition = true; if (view instanceof FilterIconButton) { ImageFilter f = ((FilterIconButton) view).getImageFilter(); doPanelTransition = f.showUtilityPanel(); } if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) { Panel current = mPanels.get(mCurrentPanel); ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE); anim1.start(); if (mUtilityPanel != null) { ViewPropertyAnimator anim2 = mUtilityPanel.select(); anim2.start(); } } if (mCurrentImage != null) { mCurrentImage.unselect(); } mUtilityPanel.hideAccessoryViews(); if (view instanceof FilterIconButton) { mCurrentEditor = null; FilterIconButton component = (FilterIconButton) view; ImageFilter filter = component.getImageFilter(); if (filter.getEditingViewId() != 0) { if (mEditorPlaceHolder.contains(filter.getEditingViewId())) { mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId()); mCurrentImage = mCurrentEditor.getImageShow(); mCurrentEditor.setPanelController(this); } else { mCurrentImage = showImageView(filter.getEditingViewId()); } mCurrentImage.setShowControls(filter.showEditingControls()); String ename = mCurrentImage.getContext().getString(filter.getTextId()); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(filter.showParameterValue()); mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } return; } switch (view.getId()) { case R.id.tinyplanetButton: { mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.tinyplanet); mUtilityPanel.setEffectName(ename); ensureFilter(ename); if (!mDisableFilterButtons) { mActivity.disableFilterButtons(); mDisableFilterButtons = true; } break; } case R.id.straightenButton: { mCurrentImage = showImageView(R.id.imageStraighten); String ename = mCurrentImage.getContext().getString(R.string.straighten); mUtilityPanel.setEffectName(ename); break; } case R.id.cropButton: { mCurrentImage = showImageView(R.id.imageCrop); String ename = mCurrentImage.getContext().getString(R.string.crop); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) { ((ImageCrop) mCurrentImage).clear(); mUtilityPanel.firstTimeCropDisplayed = false; } ((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect); break; } case R.id.rotateButton: { mCurrentImage = showImageView(R.id.imageRotate); String ename = mCurrentImage.getContext().getString(R.string.rotate); mUtilityPanel.setEffectName(ename); break; } case R.id.flipButton: { mCurrentImage = showImageView(R.id.imageFlip); String ename = mCurrentImage.getContext().getString(R.string.mirror); mUtilityPanel.setEffectName(ename); mUtilityPanel.setShowParameter(false); break; } case R.id.redEyeButton: { mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true); String ename = mCurrentImage.getContext().getString(R.string.redeye); mUtilityPanel.setEffectName(ename); ensureFilter(ename); break; } case R.id.applyEffect: { if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) { mActivity.saveImage(); } else { if (mCurrentImage instanceof ImageCrop) { ((ImageCrop) mCurrentImage).saveAndSetPreset(); } showPanel(mCurrentPanel); } MasterImage.getImage().invalidateFiltersOnly(); break; } } mCurrentImage.select(); if (mCurrentEditor != null) { mCurrentEditor.reflectCurrentFilter(); if (mCurrentEditor.useUtilityPanel()) { mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } } else if (mCurrentImage.useUtilityPanel()) { mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList); } }
diff --git a/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/monitoring/rest/MonitoringController.java b/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/monitoring/rest/MonitoringController.java index 4ae01c98..baaee82c 100755 --- a/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/monitoring/rest/MonitoringController.java +++ b/easysoa-registry-v1/easysoa-registry-rest-server/src/main/java/org/easysoa/registry/monitoring/rest/MonitoringController.java @@ -1,255 +1,263 @@ /** * EasySOA Registry * Copyright 2012 Open Wide * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact : [email protected] */ package org.easysoa.registry.monitoring.rest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import org.easysoa.registry.DocumentService; import org.easysoa.registry.indicators.rest.IndicatorValue; import org.easysoa.registry.indicators.rest.IndicatorsController; import org.easysoa.registry.integration.EndpointStateServiceImpl; import org.easysoa.registry.rest.EasysoaModuleRoot; import org.easysoa.registry.rest.integration.EndpointStateService; import org.easysoa.registry.rest.integration.SlaOrOlaIndicator; import org.easysoa.registry.types.ServiceImplementation; import org.easysoa.registry.types.SubprojectNode; import org.easysoa.registry.types.ids.SoaNodeId; import org.easysoa.registry.utils.ContextData; import org.easysoa.registry.utils.NXQLQueryHelper; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.IdRef; import org.nuxeo.ecm.webengine.jaxrs.session.SessionFactory; import org.nuxeo.ecm.webengine.model.Template; import org.nuxeo.ecm.webengine.model.WebObject; import org.nuxeo.runtime.api.Framework; /** * Indicators * * impl : TODO see ServiceDocumentationController, MatchingDashboard... * * @author mdutoo, jguillemotte * */ @WebObject(type = "monitoring") @Path("easysoa/monitoring") public class MonitoringController extends EasysoaModuleRoot { @SuppressWarnings("unused") private static Logger logger = Logger.getLogger(MonitoringController.class); // Number of indicators par page public int RESULTS_PER_PAGE = 10; /** * Default constructor */ public MonitoringController() { } @GET @Produces(MediaType.TEXT_HTML) public Object doGetHTML(@QueryParam("subprojectId") String subprojectId, @QueryParam("visibility") String visibility) throws Exception { CoreSession session = SessionFactory.getSession(request); DocumentService docService = Framework.getService(DocumentService.class); String subprojectCriteria = NXQLQueryHelper.buildSubprojectCriteria(session, subprojectId, visibility); // Get the environments List<String> envs = docService.getEnvironmentsInCriteria(session, subprojectCriteria); // Get the deployed services List<DocumentModel> services = docService.getInformationServicesInCriteria(session, subprojectCriteria); Map<String, List<DocumentModel>> endpoints = new HashMap<String, List<DocumentModel>>(); for(DocumentModel service : services){ // Get the endpoints List<DocumentModel> endpointsList = docService.getEndpointsOfServiceInCriteria(service, subprojectCriteria); endpoints.put(service.getName(), endpointsList); } return getView("dashboard") .arg("envs", envs) // TODO later by (sub)project .arg("endpoints", endpoints) .arg("subprojectId", subprojectId) .arg("visibility", visibility) .arg("contextInfo", ContextData.getVersionData(session, subprojectId)) .arg("new_f", new freemarker.template.utility.ObjectConstructor()); // see http://freemarker.624813.n4.nabble.com/best-practice-to-create-a-java-object-instance-td626021.html // and not "new" else conflicts with Nuxeo's NewMethod helper } @GET @Path("envIndicators/{endpointId:.+}/{page}") // TODO encoding @Produces(MediaType.TEXT_HTML) public Object doGetByPathHTML(@PathParam("endpointId") String endpointId, @PathParam("page") String page, @QueryParam("subprojectId") String subprojectId, @QueryParam("visibility") String visibility) throws Exception { CoreSession session = SessionFactory.getSession(request); DocumentService docService = Framework.getService(DocumentService.class); Pagination pagination = new Pagination(); // Check there is at least on environment if(endpointId == null || "".equals(endpointId)){ throw new IllegalArgumentException("At least one endpointID must be specified"); } // Check page Number int pageNumber; try{ pageNumber = Integer.parseInt(page) - 1; if(pageNumber < 1){ pageNumber = 0; } } catch(Exception ex){ throw new IllegalArgumentException("Page argument must be a positive integer number greater than 0 "); } // Get the enpoints associated with the environment //DocumentModelList endpointsModel = session.query("SELECT * FROM " + Endpoint.DOCTYPE + " WHERE " + Endpoint.XPATH_ENDP_ENVIRONMENT + " = " + envName); // Get the endpoint DocumentModel endpoint = session.getDocument(new IdRef(endpointId)); ///DocumentModel endpoint = docService.query(session, "SELECT * FROM " + Endpoint.DOCTYPE + " WHERE ecm:uuid = '" + endpointId + "'" , true, false).get(0); // Get the service String serviceId = endpoint.getProperty(ServiceImplementation.XPATH_PROVIDED_INFORMATION_SERVICE).getValue(String.class); DocumentModel service = session.getDocument(new IdRef(serviceId)); /// docService.query(session, "SELECT * FROM " + InformationService.DOCTYPE + " WHERE ecm:uuid = '" + serviceId + "'" , true, false).get(0); String slaOrOlaSubprojectId = (String) service.getPropertyValue(SubprojectNode.XPATH_SUBPROJECT); //String serviceFolder = session.getDocument(service.getParentRef()).getPathAsString(); // Get the indicators for the endpoint in the Nuxeo store EndpointStateService endpointStateService = new EndpointStateServiceImpl(); List<SlaOrOlaIndicator> indicators = endpointStateService.getSlaOrOlaIndicators(endpointId, "", null, null, RESULTS_PER_PAGE, pageNumber).getSlaOrOlaIndicatorList(); // Set pagination List<String> endpointIds = new ArrayList<String>(); endpointIds.add(endpointId); int totalIndicatorNumber = endpointStateService.getTotalNumberOfSlaOrOlaindicators(endpointIds, null, null); // To finish : Set data in pagination, add indicators in database to test the pagination - pagination.setTotalPageNumber(totalIndicatorNumber % RESULTS_PER_PAGE); - pagination.setCurrentPage(pageNumber+1); - if(totalIndicatorNumber > RESULTS_PER_PAGE){ + int totalPageNumber = Math.round(totalIndicatorNumber / RESULTS_PER_PAGE); + if(totalIndicatorNumber % RESULTS_PER_PAGE > 0){ + totalPageNumber++; + } + pagination.setTotalPageNumber(totalPageNumber); + if(indicators.size() > 0){ + pagination.setCurrentPage(pageNumber+1); + } else { + pagination.setCurrentPage(0); + } + if(totalIndicatorNumber - ((pageNumber + 1) * RESULTS_PER_PAGE) > 0){ pagination.setHasNextPage(true); } if(pageNumber > 0){ pagination.setHasPreviousPage(true); } // TODO Complete the returned indicators // Complete each indicator with the description / services ... for(SlaOrOlaIndicator indicator : indicators){ indicator.setDescription("Aucune description"); DocumentModel slaOrOla; // Get only the first par of the subprojectID /*String subPath = ""; if(subProjectId != null && !"".equals(subProjectId)){ subPath = subProjectId.substring(0, subProjectId.lastIndexOf("/")); }*/ // Get the SLA or OLA indicator in the Nuxeo registry slaOrOla = docService.findSoaNode(session, new SoaNodeId(slaOrOlaSubprojectId, org.easysoa.registry.types.SlaOrOlaIndicator.SLA_DOCTYPE, indicator.getSlaOrOlaName()), true); if (slaOrOla == null){ slaOrOla = docService.findSoaNode(session, new SoaNodeId(slaOrOlaSubprojectId, org.easysoa.registry.types.SlaOrOlaIndicator.OLA_DOCTYPE, indicator.getSlaOrOlaName()), true); } // Set additionnal indicator informatons if(slaOrOla != null){ indicator.setDescription(slaOrOla.getProperty(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SLA_OR_OLA_DESCRIPTION).getValue(String.class)); indicator.setPath(slaOrOla.getPathAsString()); } } Template view = getView("envIndicators"); // TODO see services.ftl, dashboard/*.ftl... if (indicators != null) { view.arg("indicators", indicators); } view.arg("subprojectId", subprojectId) .arg("visibility", visibility) .arg("contextInfo", ContextData.getVersionData(session, subprojectId)) .arg("service", service) .arg("servicePath", service.getPathAsString()) .arg("endpoint", endpoint) .arg("pagination", pagination) .arg("new_f", new freemarker.template.utility.ObjectConstructor()); // see http://freemarker.624813.n4.nabble.com/best-practice-to-create-a-java-object-instance-td626021.html // and not "new" else conflicts with Nuxeo's NewMethod helper return view; } @GET @Path("usage") // TODO encoding @Produces(MediaType.TEXT_HTML) public Object doGetUsagePageHTML(@QueryParam("subprojectId") String subprojectId, @QueryParam("visibility") String visibility) throws Exception { CoreSession session = SessionFactory.getSession(request); // Indicators IndicatorsController indicatorsController = new IndicatorsController(); Map<String, IndicatorValue> indicators = indicatorsController.computeIndicators(session, null, null, subprojectId, visibility); return getView("usage") .arg("subprojectId", subprojectId) .arg("visibility", visibility) .arg("indicators", indicators) .arg("contextInfo", ContextData.getVersionData(session, subprojectId)) .arg("new_f", new freemarker.template.utility.ObjectConstructor()); // see http://freemarker.624813.n4.nabble.com/best-practice-to-create-a-java-object-instance-td626021.html // and not "new" else conflicts with Nuxeo's NewMethod helper } @GET @Path("jasmine") @Produces(MediaType.TEXT_HTML) public Object doGetJasminePageHTML(@QueryParam("subprojectId") String subProjectId, @QueryParam("visibility") String visibility) throws Exception { CoreSession session = SessionFactory.getSession(request); Template view = getView("jasmine"); view.arg("subprojectId", subProjectId) .arg("visibility", visibility) .arg("contextInfo", ContextData.getVersionData(session, subProjectId)) .arg("new_f", new freemarker.template.utility.ObjectConstructor()); // see http://freemarker.624813.n4.nabble.com/best-practice-to-create-a-java-object-instance-td626021.html // and not "new" else conflicts with Nuxeo's NewMethod helper return view; } }
true
true
public Object doGetByPathHTML(@PathParam("endpointId") String endpointId, @PathParam("page") String page, @QueryParam("subprojectId") String subprojectId, @QueryParam("visibility") String visibility) throws Exception { CoreSession session = SessionFactory.getSession(request); DocumentService docService = Framework.getService(DocumentService.class); Pagination pagination = new Pagination(); // Check there is at least on environment if(endpointId == null || "".equals(endpointId)){ throw new IllegalArgumentException("At least one endpointID must be specified"); } // Check page Number int pageNumber; try{ pageNumber = Integer.parseInt(page) - 1; if(pageNumber < 1){ pageNumber = 0; } } catch(Exception ex){ throw new IllegalArgumentException("Page argument must be a positive integer number greater than 0 "); } // Get the enpoints associated with the environment //DocumentModelList endpointsModel = session.query("SELECT * FROM " + Endpoint.DOCTYPE + " WHERE " + Endpoint.XPATH_ENDP_ENVIRONMENT + " = " + envName); // Get the endpoint DocumentModel endpoint = session.getDocument(new IdRef(endpointId)); ///DocumentModel endpoint = docService.query(session, "SELECT * FROM " + Endpoint.DOCTYPE + " WHERE ecm:uuid = '" + endpointId + "'" , true, false).get(0); // Get the service String serviceId = endpoint.getProperty(ServiceImplementation.XPATH_PROVIDED_INFORMATION_SERVICE).getValue(String.class); DocumentModel service = session.getDocument(new IdRef(serviceId)); /// docService.query(session, "SELECT * FROM " + InformationService.DOCTYPE + " WHERE ecm:uuid = '" + serviceId + "'" , true, false).get(0); String slaOrOlaSubprojectId = (String) service.getPropertyValue(SubprojectNode.XPATH_SUBPROJECT); //String serviceFolder = session.getDocument(service.getParentRef()).getPathAsString(); // Get the indicators for the endpoint in the Nuxeo store EndpointStateService endpointStateService = new EndpointStateServiceImpl(); List<SlaOrOlaIndicator> indicators = endpointStateService.getSlaOrOlaIndicators(endpointId, "", null, null, RESULTS_PER_PAGE, pageNumber).getSlaOrOlaIndicatorList(); // Set pagination List<String> endpointIds = new ArrayList<String>(); endpointIds.add(endpointId); int totalIndicatorNumber = endpointStateService.getTotalNumberOfSlaOrOlaindicators(endpointIds, null, null); // To finish : Set data in pagination, add indicators in database to test the pagination pagination.setTotalPageNumber(totalIndicatorNumber % RESULTS_PER_PAGE); pagination.setCurrentPage(pageNumber+1); if(totalIndicatorNumber > RESULTS_PER_PAGE){ pagination.setHasNextPage(true); } if(pageNumber > 0){ pagination.setHasPreviousPage(true); } // TODO Complete the returned indicators // Complete each indicator with the description / services ... for(SlaOrOlaIndicator indicator : indicators){ indicator.setDescription("Aucune description"); DocumentModel slaOrOla; // Get only the first par of the subprojectID /*String subPath = ""; if(subProjectId != null && !"".equals(subProjectId)){ subPath = subProjectId.substring(0, subProjectId.lastIndexOf("/")); }*/ // Get the SLA or OLA indicator in the Nuxeo registry slaOrOla = docService.findSoaNode(session, new SoaNodeId(slaOrOlaSubprojectId, org.easysoa.registry.types.SlaOrOlaIndicator.SLA_DOCTYPE, indicator.getSlaOrOlaName()), true); if (slaOrOla == null){ slaOrOla = docService.findSoaNode(session, new SoaNodeId(slaOrOlaSubprojectId, org.easysoa.registry.types.SlaOrOlaIndicator.OLA_DOCTYPE, indicator.getSlaOrOlaName()), true); } // Set additionnal indicator informatons if(slaOrOla != null){ indicator.setDescription(slaOrOla.getProperty(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SLA_OR_OLA_DESCRIPTION).getValue(String.class)); indicator.setPath(slaOrOla.getPathAsString()); } } Template view = getView("envIndicators"); // TODO see services.ftl, dashboard/*.ftl... if (indicators != null) { view.arg("indicators", indicators); } view.arg("subprojectId", subprojectId) .arg("visibility", visibility) .arg("contextInfo", ContextData.getVersionData(session, subprojectId)) .arg("service", service) .arg("servicePath", service.getPathAsString()) .arg("endpoint", endpoint) .arg("pagination", pagination) .arg("new_f", new freemarker.template.utility.ObjectConstructor()); // see http://freemarker.624813.n4.nabble.com/best-practice-to-create-a-java-object-instance-td626021.html // and not "new" else conflicts with Nuxeo's NewMethod helper return view; }
public Object doGetByPathHTML(@PathParam("endpointId") String endpointId, @PathParam("page") String page, @QueryParam("subprojectId") String subprojectId, @QueryParam("visibility") String visibility) throws Exception { CoreSession session = SessionFactory.getSession(request); DocumentService docService = Framework.getService(DocumentService.class); Pagination pagination = new Pagination(); // Check there is at least on environment if(endpointId == null || "".equals(endpointId)){ throw new IllegalArgumentException("At least one endpointID must be specified"); } // Check page Number int pageNumber; try{ pageNumber = Integer.parseInt(page) - 1; if(pageNumber < 1){ pageNumber = 0; } } catch(Exception ex){ throw new IllegalArgumentException("Page argument must be a positive integer number greater than 0 "); } // Get the enpoints associated with the environment //DocumentModelList endpointsModel = session.query("SELECT * FROM " + Endpoint.DOCTYPE + " WHERE " + Endpoint.XPATH_ENDP_ENVIRONMENT + " = " + envName); // Get the endpoint DocumentModel endpoint = session.getDocument(new IdRef(endpointId)); ///DocumentModel endpoint = docService.query(session, "SELECT * FROM " + Endpoint.DOCTYPE + " WHERE ecm:uuid = '" + endpointId + "'" , true, false).get(0); // Get the service String serviceId = endpoint.getProperty(ServiceImplementation.XPATH_PROVIDED_INFORMATION_SERVICE).getValue(String.class); DocumentModel service = session.getDocument(new IdRef(serviceId)); /// docService.query(session, "SELECT * FROM " + InformationService.DOCTYPE + " WHERE ecm:uuid = '" + serviceId + "'" , true, false).get(0); String slaOrOlaSubprojectId = (String) service.getPropertyValue(SubprojectNode.XPATH_SUBPROJECT); //String serviceFolder = session.getDocument(service.getParentRef()).getPathAsString(); // Get the indicators for the endpoint in the Nuxeo store EndpointStateService endpointStateService = new EndpointStateServiceImpl(); List<SlaOrOlaIndicator> indicators = endpointStateService.getSlaOrOlaIndicators(endpointId, "", null, null, RESULTS_PER_PAGE, pageNumber).getSlaOrOlaIndicatorList(); // Set pagination List<String> endpointIds = new ArrayList<String>(); endpointIds.add(endpointId); int totalIndicatorNumber = endpointStateService.getTotalNumberOfSlaOrOlaindicators(endpointIds, null, null); // To finish : Set data in pagination, add indicators in database to test the pagination int totalPageNumber = Math.round(totalIndicatorNumber / RESULTS_PER_PAGE); if(totalIndicatorNumber % RESULTS_PER_PAGE > 0){ totalPageNumber++; } pagination.setTotalPageNumber(totalPageNumber); if(indicators.size() > 0){ pagination.setCurrentPage(pageNumber+1); } else { pagination.setCurrentPage(0); } if(totalIndicatorNumber - ((pageNumber + 1) * RESULTS_PER_PAGE) > 0){ pagination.setHasNextPage(true); } if(pageNumber > 0){ pagination.setHasPreviousPage(true); } // TODO Complete the returned indicators // Complete each indicator with the description / services ... for(SlaOrOlaIndicator indicator : indicators){ indicator.setDescription("Aucune description"); DocumentModel slaOrOla; // Get only the first par of the subprojectID /*String subPath = ""; if(subProjectId != null && !"".equals(subProjectId)){ subPath = subProjectId.substring(0, subProjectId.lastIndexOf("/")); }*/ // Get the SLA or OLA indicator in the Nuxeo registry slaOrOla = docService.findSoaNode(session, new SoaNodeId(slaOrOlaSubprojectId, org.easysoa.registry.types.SlaOrOlaIndicator.SLA_DOCTYPE, indicator.getSlaOrOlaName()), true); if (slaOrOla == null){ slaOrOla = docService.findSoaNode(session, new SoaNodeId(slaOrOlaSubprojectId, org.easysoa.registry.types.SlaOrOlaIndicator.OLA_DOCTYPE, indicator.getSlaOrOlaName()), true); } // Set additionnal indicator informatons if(slaOrOla != null){ indicator.setDescription(slaOrOla.getProperty(org.easysoa.registry.types.SlaOrOlaIndicator.XPATH_SLA_OR_OLA_DESCRIPTION).getValue(String.class)); indicator.setPath(slaOrOla.getPathAsString()); } } Template view = getView("envIndicators"); // TODO see services.ftl, dashboard/*.ftl... if (indicators != null) { view.arg("indicators", indicators); } view.arg("subprojectId", subprojectId) .arg("visibility", visibility) .arg("contextInfo", ContextData.getVersionData(session, subprojectId)) .arg("service", service) .arg("servicePath", service.getPathAsString()) .arg("endpoint", endpoint) .arg("pagination", pagination) .arg("new_f", new freemarker.template.utility.ObjectConstructor()); // see http://freemarker.624813.n4.nabble.com/best-practice-to-create-a-java-object-instance-td626021.html // and not "new" else conflicts with Nuxeo's NewMethod helper return view; }
diff --git a/Clock.java b/Clock.java index 0a1aab6..0792228 100644 --- a/Clock.java +++ b/Clock.java @@ -1,168 +1,167 @@ import java.util.*; import java.util.ArrayList; import java.lang.*; import java.io.File; import java.io.*; public class Clock { private static boolean DEBUG = true; // for sterling algor. private boolean DEBUG_OUT = true; // for internal use, comment to false private int missPenalty = 0, dirtyPagePenalty = 0, pageSize = 0, vaBits = 0, paBits = 0, frameCount = 0, numOfProcesses = 0; private String referenceFile; private ArrayList<Process> processList = new ArrayList<Process>(); private Process running = null; private PageTable pageTable = null; public static void main(String... arg) { Clock clock = new Clock(); clock.run(); } public Clock() { readSettings("MemoryManagement.txt"); pageTable = new PageTable(pageSize); readReference(referenceFile); } public void run() { while (processList.size() > 0) { running = processList.get(0); processList.remove(0); // Take O(N) int tmpBurst = running.getBurst(); while (tmpBurst > 0) { --tmpBurst; } // page faults if (running.getNumOfRef() > 0) { running.decNumOfRef(); } else { continue; } // move to the back of the queue processList.add(running); } } private void readReference(String filename) { /* *# of processes * process list * pid * burst, Defined as the number of memory references between I/O requests. * # of references for the process list of references for the process. Each reference indicates whether it was a read or a write */ try { Scanner scan = new Scanner(new File(filename)); if (scan.hasNextLine()) { numOfProcesses = scan.nextInt(); } else { System.out.println("Error: Nothing to read. Reference File.\n"); } for (int i = 0; i < numOfProcesses; ++i) { if (scan.hasNextLine()) { int tmpPid, tmpBurst, tmpNumOfRefs; - //*************************************** problem here, we are not ignoring whitespaces. ! java ! tmpPid = scan.nextInt(); // pid tmpBurst = scan.nextInt(); // burst tmpNumOfRefs = scan.nextInt(); // number of references if(DEBUG_OUT){ System.out.println("\npid: "+tmpPid+ "\nburst: "+tmpBurst+ "\nnum of refs: "+ tmpNumOfRefs ); } ArrayList<Reference> refs = new ArrayList<Reference>(); while (scan.hasNextLine()) { String line = scan.nextLine(); if(line.isEmpty()) continue; if(DEBUG_OUT){ System.out.println("\nline: "+line+ "\nsizeOfLine: "+line.length() ); // output for debug } Scanner scanLine = new Scanner(line); Reference reference = new Reference(scanLine.nextInt(), // address (scanLine.hasNext("R")) // read or write ); refs.add(reference); } processList.add(new Process(tmpPid, tmpBurst, tmpNumOfRefs, refs)); } } } catch (java.io.FileNotFoundException e) { System.out.println("Exception in readReference(), in clock class " ); e.printStackTrace(); } } private void readSettings(String filename) { /*referenceFile=references.txt missPenalty=1 dirtyPagePenalty=0 pageSize=1024 VAbits=16 PAbits=13 frameCount=5 debug=true */ try { Scanner scan = new Scanner(new File(filename)); String line, value, arg; while (scan.hasNextLine()) { line = scan.nextLine(); int indexEquals = line.indexOf("="); arg = line.substring(0, indexEquals); value = line.substring(indexEquals + 1); if(DEBUG_OUT){ System.out.println("in readSetting()\nargnument: "+arg+"\nvalue: "+value); } setValue(arg, value); } } catch (java.io.FileNotFoundException e) { System.out.println("Exception in readSetting(), in clock class " ); e.printStackTrace(); } } private void setValue(String arg, String value) { if (arg.equals("missPenalty")) { missPenalty = Integer.valueOf(value); } else if (arg.equals("debug")) { DEBUG = Boolean.valueOf(value); } else if (arg.equals("referenceFile")) { referenceFile = value; } else if (arg.equals("dirtyPagePenalty")) { dirtyPagePenalty = Integer.valueOf(value); } else if (arg.equals("pageSize")) { pageSize = Integer.valueOf(value); } else if (arg.equals("VAbits")) { vaBits = Integer.valueOf(value); } else if (arg.equals("PAbits")) { paBits = Integer.valueOf(value); } else if (arg.equals("frameCount")) { frameCount = Integer.valueOf(value); } else { System.out.println("Error: Argument not found! \nArgument:" + arg + "\nValue: " + value); } } }
true
true
private void readReference(String filename) { /* *# of processes * process list * pid * burst, Defined as the number of memory references between I/O requests. * # of references for the process list of references for the process. Each reference indicates whether it was a read or a write */ try { Scanner scan = new Scanner(new File(filename)); if (scan.hasNextLine()) { numOfProcesses = scan.nextInt(); } else { System.out.println("Error: Nothing to read. Reference File.\n"); } for (int i = 0; i < numOfProcesses; ++i) { if (scan.hasNextLine()) { int tmpPid, tmpBurst, tmpNumOfRefs; //*************************************** problem here, we are not ignoring whitespaces. ! java ! tmpPid = scan.nextInt(); // pid tmpBurst = scan.nextInt(); // burst tmpNumOfRefs = scan.nextInt(); // number of references if(DEBUG_OUT){ System.out.println("\npid: "+tmpPid+ "\nburst: "+tmpBurst+ "\nnum of refs: "+ tmpNumOfRefs ); } ArrayList<Reference> refs = new ArrayList<Reference>(); while (scan.hasNextLine()) { String line = scan.nextLine(); if(line.isEmpty()) continue; if(DEBUG_OUT){ System.out.println("\nline: "+line+ "\nsizeOfLine: "+line.length() ); // output for debug } Scanner scanLine = new Scanner(line); Reference reference = new Reference(scanLine.nextInt(), // address (scanLine.hasNext("R")) // read or write ); refs.add(reference); } processList.add(new Process(tmpPid, tmpBurst, tmpNumOfRefs, refs)); } } } catch (java.io.FileNotFoundException e) { System.out.println("Exception in readReference(), in clock class " ); e.printStackTrace(); } }
private void readReference(String filename) { /* *# of processes * process list * pid * burst, Defined as the number of memory references between I/O requests. * # of references for the process list of references for the process. Each reference indicates whether it was a read or a write */ try { Scanner scan = new Scanner(new File(filename)); if (scan.hasNextLine()) { numOfProcesses = scan.nextInt(); } else { System.out.println("Error: Nothing to read. Reference File.\n"); } for (int i = 0; i < numOfProcesses; ++i) { if (scan.hasNextLine()) { int tmpPid, tmpBurst, tmpNumOfRefs; tmpPid = scan.nextInt(); // pid tmpBurst = scan.nextInt(); // burst tmpNumOfRefs = scan.nextInt(); // number of references if(DEBUG_OUT){ System.out.println("\npid: "+tmpPid+ "\nburst: "+tmpBurst+ "\nnum of refs: "+ tmpNumOfRefs ); } ArrayList<Reference> refs = new ArrayList<Reference>(); while (scan.hasNextLine()) { String line = scan.nextLine(); if(line.isEmpty()) continue; if(DEBUG_OUT){ System.out.println("\nline: "+line+ "\nsizeOfLine: "+line.length() ); // output for debug } Scanner scanLine = new Scanner(line); Reference reference = new Reference(scanLine.nextInt(), // address (scanLine.hasNext("R")) // read or write ); refs.add(reference); } processList.add(new Process(tmpPid, tmpBurst, tmpNumOfRefs, refs)); } } } catch (java.io.FileNotFoundException e) { System.out.println("Exception in readReference(), in clock class " ); e.printStackTrace(); } }
diff --git a/pax-logging-service/src/main/java/org/apache/log4j/sift/MDCSiftingAppender.java b/pax-logging-service/src/main/java/org/apache/log4j/sift/MDCSiftingAppender.java index 11f8fbb..6a77bf2 100644 --- a/pax-logging-service/src/main/java/org/apache/log4j/sift/MDCSiftingAppender.java +++ b/pax-logging-service/src/main/java/org/apache/log4j/sift/MDCSiftingAppender.java @@ -1,164 +1,163 @@ /* * Copyright 2010 Guillaume Nodet. * * 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.log4j.sift; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.apache.log4j.Appender; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.OptionFactory; /** * A log4j appender which splits the output based on an MDC key */ public class MDCSiftingAppender extends AppenderSkeleton { private String key; private String defaultValue = "default"; private OptionFactory appender; private Map appenders = new HashMap(); private Node head = null; private Node tail = null; private long lastCheck; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDefault() { return defaultValue; } public void setDefault(String defaultValue) { this.defaultValue = defaultValue; } public OptionFactory getAppender() { return appender; } public void setAppender(OptionFactory appender) { this.appender = appender; } protected void append(LoggingEvent event) { Object value = event.getMDC(key); String valStr = value == null ? defaultValue : value.toString(); Appender app = getAppender(valStr); app.doAppend(event); } public synchronized void close() { for (Iterator it = appenders.values().iterator(); it.hasNext();) { Node node = (Node) it.next(); node.appender.close(); } appenders.clear(); } public boolean requiresLayout() { return false; } protected synchronized Appender getAppender(String valStr) { long timestamp = System.currentTimeMillis(); Node node = (Node) appenders.get(valStr); if (node == null) { node = new Node(); node.key = valStr; Properties props = new Properties(); props.put(key, valStr); node.next = head; node.prev = null; node.appender = (Appender) appender.create(props); node.appender.setName(getName() + "[" + valStr + "]"); node.timestamp = timestamp; - head.prev = node; head = node; if (tail == null) { tail = node; } appenders.put(valStr, node); } else { Node p = node.prev; Node n = node.next; node.next = head; node.prev = null; head = node; if (p != null) { p.next = n; } if (n != null) { n.prev = p; } else { tail = p; } node.timestamp = timestamp; } // Do not check too often if (timestamp - lastCheck > 1000) { lastCheck = timestamp; Node n = tail; while (n != null && timestamp - n.timestamp > 30 * 60 * 1000) { n.appender.close(); appenders.remove(n.key); n = n.prev; } if (n == null) { tail = head = null; } else { n.next = null; tail = n; } } return node.appender; } protected static class Node { String key; Node next; Node prev; Appender appender; long timestamp; } }
true
true
protected synchronized Appender getAppender(String valStr) { long timestamp = System.currentTimeMillis(); Node node = (Node) appenders.get(valStr); if (node == null) { node = new Node(); node.key = valStr; Properties props = new Properties(); props.put(key, valStr); node.next = head; node.prev = null; node.appender = (Appender) appender.create(props); node.appender.setName(getName() + "[" + valStr + "]"); node.timestamp = timestamp; head.prev = node; head = node; if (tail == null) { tail = node; } appenders.put(valStr, node); } else { Node p = node.prev; Node n = node.next; node.next = head; node.prev = null; head = node; if (p != null) { p.next = n; } if (n != null) { n.prev = p; } else { tail = p; } node.timestamp = timestamp; } // Do not check too often if (timestamp - lastCheck > 1000) { lastCheck = timestamp; Node n = tail; while (n != null && timestamp - n.timestamp > 30 * 60 * 1000) { n.appender.close(); appenders.remove(n.key); n = n.prev; } if (n == null) { tail = head = null; } else { n.next = null; tail = n; } } return node.appender; }
protected synchronized Appender getAppender(String valStr) { long timestamp = System.currentTimeMillis(); Node node = (Node) appenders.get(valStr); if (node == null) { node = new Node(); node.key = valStr; Properties props = new Properties(); props.put(key, valStr); node.next = head; node.prev = null; node.appender = (Appender) appender.create(props); node.appender.setName(getName() + "[" + valStr + "]"); node.timestamp = timestamp; head = node; if (tail == null) { tail = node; } appenders.put(valStr, node); } else { Node p = node.prev; Node n = node.next; node.next = head; node.prev = null; head = node; if (p != null) { p.next = n; } if (n != null) { n.prev = p; } else { tail = p; } node.timestamp = timestamp; } // Do not check too often if (timestamp - lastCheck > 1000) { lastCheck = timestamp; Node n = tail; while (n != null && timestamp - n.timestamp > 30 * 60 * 1000) { n.appender.close(); appenders.remove(n.key); n = n.prev; } if (n == null) { tail = head = null; } else { n.next = null; tail = n; } } return node.appender; }