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/tregmine/src/info/tregmine/Tregmine.java b/tregmine/src/info/tregmine/Tregmine.java
index 98c3ab5..1b6f794 100644
--- a/tregmine/src/info/tregmine/Tregmine.java
+++ b/tregmine/src/info/tregmine/Tregmine.java
@@ -1,627 +1,627 @@
package info.tregmine;
import info.tregmine.api.TregminePlayer;
import info.tregmine.currency.Wallet;
import info.tregmine.database.ConnectionPool;
import info.tregmine.listeners.TregmineBlockListener;
import info.tregmine.listeners.TregmineEntityListener;
import info.tregmine.listeners.TregminePlayerListener;
import info.tregmine.listeners.TregmineWeatherListener;
import info.tregmine.stats.BlockStats;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
//import org.bukkit.Color;
//import org.bukkit.FireworkEffect;
//import org.bukkit.Location;
import org.bukkit.Material;
//import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author Ein Andersson - www.tregmine.info
* @version 0.8
*/
public class Tregmine extends JavaPlugin
{
public final Logger log = Logger.getLogger("Minecraft");
public final BlockStats blockStats = new BlockStats(this);
public Map<String, TregminePlayer> tregminePlayer = new HashMap<String, TregminePlayer>();
// public Map<String, Boolean> hasVoted = new HashMap<String, Boolean>();
public LinkedList <String> hasVoted = new LinkedList<String>();
public int version = 0;
public int amount = 0;
@Override
public void onEnable() {
WorldCreator citadelCreator = new WorldCreator("citadel");
citadelCreator.environment(Environment.NORMAL);
citadelCreator.createWorld();
WorldCreator world = new WorldCreator("world");
world.environment(Environment.NORMAL);
world.createWorld();
WorldCreator NETHER = new WorldCreator("world_nether");
NETHER.environment(Environment.NETHER);
NETHER.createWorld();
getServer().getPluginManager().registerEvents(new info.tregmine.lookup.LookupPlayer(this), this);
getServer().getPluginManager().registerEvents(new TregminePlayerListener(this), this);
getServer().getPluginManager().registerEvents(new TregmineBlockListener(this), this);
getServer().getPluginManager().registerEvents(new TregmineEntityListener(this), this);
getServer().getPluginManager().registerEvents(new TregmineWeatherListener(this), this);
getServer().getPluginManager().registerEvents(new info.tregmine.invis.InvisPlayer(this), this);
getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathEntity(this), this);
getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathPlayer(this), this);
getServer().getPluginManager().registerEvents(new info.tregmine.chat.Chat(this), this);
getServer().getPluginManager().registerEvents(new info.tregmine.vote.voter(this), this);
getServer().getPluginManager().registerEvents(new info.tregmine.sign.Color(), this);
}
@Override
public void onDisable() { //run when plugin is disabled
this.getServer().getScheduler().cancelTasks(this);
Player[] players = this.getServer().getOnlinePlayers();
for (Player player : players) {
player.sendMessage(ChatColor.AQUA + "Tregmine successfully unloaded build: " + this.getDescription().getVersion() );
}
}
@Override
public void onLoad()
{
Player[] players = this.getServer().getOnlinePlayers();
for (Player player : players) {
String onlineName = player.getName();
TregminePlayer tregPlayer = new TregminePlayer(player, onlineName);
tregPlayer.load();
this.tregminePlayer.put(onlineName, tregPlayer);
player.sendMessage(ChatColor.GRAY + "Tregmine successfully loaded to build: " + this.getDescription().getVersion() );
// player.sendMessage(ChatColor.GRAY + "Version explanation: X.Y.Z.G");
// player.sendMessage(ChatColor.GRAY + "X new stuff added, When i make a brand new thing");
// player.sendMessage(ChatColor.GRAY + "Y new function added, when i extend what current stuff can do");
// player.sendMessage(ChatColor.GRAY + "Z bugfix that may change how function and stuff works");
// player.sendMessage(ChatColor.GRAY + "G small bugfix like spelling errors");
}
this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
while(hasVoted.size() > 0) {
String name = hasVoted.removeFirst();
getServer().broadcastMessage(ChatColor.YELLOW + name + " has voted and will now receive 2,000 Tregs");
getServer().broadcastMessage(ChatColor.YELLOW + name + " Read more at http://treg.co/82 what you can get");
Wallet wallet = new Wallet(name);
wallet.add(2000);
log.info(name + " got " + name + " Tregs for VOTING");
// getPlayer(name).setMetaInt("votecount", getPlayer(name).getMetaInt("votecount")+1);
}
}
},100L,20L);
}
public TregminePlayer getPlayer(String name) {
return tregminePlayer.get(name);
}
public TregminePlayer getPlayer(Player player) {
return tregminePlayer.get(player.getName());
}
@SuppressWarnings("deprecation")
public boolean onCommand(CommandSender sender, Command command, String commandLabel, final String[] args) {
String commandName = command.getName().toLowerCase();
Player from = null;
TregminePlayer player = null;
if(!(sender instanceof Player)) {
if(commandName.equals("say")) {
StringBuffer buf = new StringBuffer();
buf.append(args[0]);
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
this.log.info("CONSOLE: <GOD> " + buffMsg);
return true;
}
return false;
} else {
from = (Player) sender;
player = this.getPlayer(from);
}
if("book".matches(commandName)) {
if("player".matches(args[0]) && player.isOp()) {
final TregminePlayer fPlayer = player;
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
fPlayer.sendMessage(ChatColor.YELLOW + "Starting to generate book for " + args[1] );
ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1);
BookMeta bookmeta = (BookMeta) book.getItemMeta();
// TregminePlayer p = getPlayer(args[1]);
long placed = 0;
long destroyed = 0;
long total = 0;
int id = 0;
String joinDate = "";
bookmeta.setAuthor("Tregmine");
bookmeta.setTitle(ChatColor.GREEN + args[1] + "'s Profile");
bookmeta.addPage(ChatColor.GREEN + args[1] + "'s profile" + '\n' + "date:"+'\n'+ date.toString());
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=?");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
total = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=1");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
placed = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=0");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
destroyed = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT * FROM user WHERE player=?");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
joinDate = rs.getDate("time").toString();
id = rs.getInt("uid");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
bookmeta.addPage(
ChatColor.BLUE + "ID:" +'\n' +
ChatColor.BLACK + id +'\n' +
ChatColor.BLUE + "JOIN-TIME (GMT):" +'\n' +
ChatColor.BLACK + joinDate +'\n' +
ChatColor.BLUE + "BLOCK DESTROYED:" +'\n' +
ChatColor.BLACK + destroyed +'\n' +
ChatColor.BLUE + "BLOCK PLACED:" +'\n' +
ChatColor.BLACK + placed +'\n' +
ChatColor.BLUE + "TOTAL:" +'\n' +
ChatColor.BLACK + total +'\n' +
"EOF");
book.setItemMeta(bookmeta);
PlayerInventory inv = fPlayer.getInventory();
inv.addItem(book);
}
},20L);
}
}
if("blackout".matches(commandName) && player.isAdmin()) {
Player target = getServer().getPlayer(args[1]);
player.sendMessage("blackout");
- if ("blind".matches(args[2])) {
+ if ("blind".matches(args[0])) {
PotionEffect ef = new PotionEffect(PotionEffectType.BLINDNESS, 60, 10);
target.getPlayer().addPotionEffect(ef);
player.sendMessage("Blind");
}
- if ("confuse".matches(args[2])) {
+ if ("confuse".matches(args[0])) {
PotionEffect ef = new PotionEffect(PotionEffectType.CONFUSION, 60, 10);
target.getPlayer().addPotionEffect(ef);
player.sendMessage("Confuse");
}
}
if("te".matches(commandName) && player.isOp()) {
ItemStack item = new ItemStack(Material.PAPER, 1);
PlayerInventory inv = player.getInventory();
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString());
TregminePlayer p = this.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getName() );
lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" );
meta.setLore(lore);
meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon");
item.setItemMeta(meta);
inv.addItem(item);
player.updateInventory();
}
if ("TregDev".matches(this.getServer().getServerName())) {
if("te".matches(commandName)) {
ItemStack item = new ItemStack(Material.PAPER, amount, (byte) 0);
PlayerInventory inv = player.getInventory();
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString());
TregminePlayer p = this.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getName() );
lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" );
meta.setLore(lore);
meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon");
item.setItemMeta(meta);
}
if("op".matches(commandName)) {
player.setMetaBoolean("admin", true);
player.setMetaBoolean("donator", true);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.RED + player.getName());
player.setAllowFlight(true);
player.setMetaString("color", ""+ChatColor.RED);
}
if("donator".matches(commandName)) {
player.setAllowFlight(true);
player.setMetaBoolean("admin", false);
player.setMetaBoolean("donator", true);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.GOLD + player.getName());
player.setMetaString("color", ""+ChatColor.GOLD);
}
if("settler".matches(commandName)) {
player.setAllowFlight(true);
player.setMetaBoolean("admin", false);
player.setMetaBoolean("donator", false);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.GREEN + player.getName());
player.setMetaString("color", ""+ChatColor.GREEN);
}
}
if("invis".matches(commandName) && player.isOp()) {
if ("off".matches(args[0])) {
for (Player p : this.getServer().getOnlinePlayers()) {
p.showPlayer(player.getPlayer());
}
player.setMetaBoolean("invis", false);
player.sendMessage(ChatColor.YELLOW + "You can now be seen!");
} else if ("on".matches(args[0])) {
for (Player p : this.getServer().getOnlinePlayers()) {
if (!p.isOp()) {
p.hidePlayer(player.getPlayer());
} else {
p.showPlayer(player.getPlayer());
}
}
player.setMetaBoolean("invis", true);
player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!");
} else {
player.sendMessage("Try /invis [on|off]");
}
}
if(commandName.equals("text") && player.isAdmin()) {
Player[] players = this.getServer().getOnlinePlayers();
// player.setTexturePack(args[0]);
for (Player p : players) {
p.setTexturePack(args[0]);
}
}
if(commandName.equals("head") && player.isOp()) {
ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) item.getItemMeta();
meta.setOwner(args[0]);
meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]);
item.setItemMeta(meta);
PlayerInventory inv = player.getInventory();
inv.addItem(item);
player.updateInventory();
player.sendMessage("Skull of " + args[0]);
} else if(commandName.equals("head")) {
player.kickPlayer("");
}
if(commandName.equals("say") && player.isAdmin()) {
StringBuffer buf = new StringBuffer();
buf.append(args[0]);
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
if(from.getName().matches("BlackX")) {
this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("mejjad")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("einand")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("LilKiw")){
this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("Camrenn")){
this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("Mksen")){
this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("josh121297")){
this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("GeorgeBombadil")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("rweiand")){
this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else {
this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
}
this.log.info(from.getName() + ": <GOD> " + buffMsg);
Player[] players = this.getServer().getOnlinePlayers();
for (Player p : players) {
info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName()));
if (locTregminePlayer.isAdmin()) {
p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName());
}
}
return true;
}
if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){
info.tregmine.commands.Who.run(this, player, args);
return true;
}
if(commandName.equals("tp")){
info.tregmine.commands.Tp.run(this, player, args);
return true;
}
if(commandName.equals("channel")){
if (args.length != 1) {
return false;
}
from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + ".");
from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." );
player.setChatChannel(args[0]);
return true;
}
if(commandName.equals("force") && args.length == 2 ){
player.setChatChannel(args[1]);
Player to = getServer().matchPlayer(args[0]).get(0);
info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName());
toPlayer.setChatChannel(args[1]);
to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + ".");
to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." );
from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + ".");
this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase());
return true;
}
if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) {
Player to = getServer().getPlayer(args[0]);
if (to != null) {
info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName());
StringBuffer buf = new StringBuffer();
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
if (!toPlayer.getMetaBoolean("invis")) {
from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg);
}
to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg);
log.info(from.getName() + " => " + to.getName() + buffMsg);
return true;
}
}
if(commandName.equals("me") && args.length > 0 ){
StringBuffer buf = new StringBuffer();
Player[] players = getServer().getOnlinePlayers();
for (int i = 0; i < args.length; ++i) {
buf.append(" " + args[i]);
}
for (Player tp : players) {
TregminePlayer to = this.getPlayer(tp);
if (player.getChatChannel().equals(to.getChatChannel())) {
to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() );
}
}
return true;
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, final String[] args) {
String commandName = command.getName().toLowerCase();
Player from = null;
TregminePlayer player = null;
if(!(sender instanceof Player)) {
if(commandName.equals("say")) {
StringBuffer buf = new StringBuffer();
buf.append(args[0]);
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
this.log.info("CONSOLE: <GOD> " + buffMsg);
return true;
}
return false;
} else {
from = (Player) sender;
player = this.getPlayer(from);
}
if("book".matches(commandName)) {
if("player".matches(args[0]) && player.isOp()) {
final TregminePlayer fPlayer = player;
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
fPlayer.sendMessage(ChatColor.YELLOW + "Starting to generate book for " + args[1] );
ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1);
BookMeta bookmeta = (BookMeta) book.getItemMeta();
// TregminePlayer p = getPlayer(args[1]);
long placed = 0;
long destroyed = 0;
long total = 0;
int id = 0;
String joinDate = "";
bookmeta.setAuthor("Tregmine");
bookmeta.setTitle(ChatColor.GREEN + args[1] + "'s Profile");
bookmeta.addPage(ChatColor.GREEN + args[1] + "'s profile" + '\n' + "date:"+'\n'+ date.toString());
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=?");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
total = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=1");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
placed = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=0");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
destroyed = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT * FROM user WHERE player=?");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
joinDate = rs.getDate("time").toString();
id = rs.getInt("uid");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
bookmeta.addPage(
ChatColor.BLUE + "ID:" +'\n' +
ChatColor.BLACK + id +'\n' +
ChatColor.BLUE + "JOIN-TIME (GMT):" +'\n' +
ChatColor.BLACK + joinDate +'\n' +
ChatColor.BLUE + "BLOCK DESTROYED:" +'\n' +
ChatColor.BLACK + destroyed +'\n' +
ChatColor.BLUE + "BLOCK PLACED:" +'\n' +
ChatColor.BLACK + placed +'\n' +
ChatColor.BLUE + "TOTAL:" +'\n' +
ChatColor.BLACK + total +'\n' +
"EOF");
book.setItemMeta(bookmeta);
PlayerInventory inv = fPlayer.getInventory();
inv.addItem(book);
}
},20L);
}
}
if("blackout".matches(commandName) && player.isAdmin()) {
Player target = getServer().getPlayer(args[1]);
player.sendMessage("blackout");
if ("blind".matches(args[2])) {
PotionEffect ef = new PotionEffect(PotionEffectType.BLINDNESS, 60, 10);
target.getPlayer().addPotionEffect(ef);
player.sendMessage("Blind");
}
if ("confuse".matches(args[2])) {
PotionEffect ef = new PotionEffect(PotionEffectType.CONFUSION, 60, 10);
target.getPlayer().addPotionEffect(ef);
player.sendMessage("Confuse");
}
}
if("te".matches(commandName) && player.isOp()) {
ItemStack item = new ItemStack(Material.PAPER, 1);
PlayerInventory inv = player.getInventory();
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString());
TregminePlayer p = this.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getName() );
lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" );
meta.setLore(lore);
meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon");
item.setItemMeta(meta);
inv.addItem(item);
player.updateInventory();
}
if ("TregDev".matches(this.getServer().getServerName())) {
if("te".matches(commandName)) {
ItemStack item = new ItemStack(Material.PAPER, amount, (byte) 0);
PlayerInventory inv = player.getInventory();
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString());
TregminePlayer p = this.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getName() );
lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" );
meta.setLore(lore);
meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon");
item.setItemMeta(meta);
}
if("op".matches(commandName)) {
player.setMetaBoolean("admin", true);
player.setMetaBoolean("donator", true);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.RED + player.getName());
player.setAllowFlight(true);
player.setMetaString("color", ""+ChatColor.RED);
}
if("donator".matches(commandName)) {
player.setAllowFlight(true);
player.setMetaBoolean("admin", false);
player.setMetaBoolean("donator", true);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.GOLD + player.getName());
player.setMetaString("color", ""+ChatColor.GOLD);
}
if("settler".matches(commandName)) {
player.setAllowFlight(true);
player.setMetaBoolean("admin", false);
player.setMetaBoolean("donator", false);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.GREEN + player.getName());
player.setMetaString("color", ""+ChatColor.GREEN);
}
}
if("invis".matches(commandName) && player.isOp()) {
if ("off".matches(args[0])) {
for (Player p : this.getServer().getOnlinePlayers()) {
p.showPlayer(player.getPlayer());
}
player.setMetaBoolean("invis", false);
player.sendMessage(ChatColor.YELLOW + "You can now be seen!");
} else if ("on".matches(args[0])) {
for (Player p : this.getServer().getOnlinePlayers()) {
if (!p.isOp()) {
p.hidePlayer(player.getPlayer());
} else {
p.showPlayer(player.getPlayer());
}
}
player.setMetaBoolean("invis", true);
player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!");
} else {
player.sendMessage("Try /invis [on|off]");
}
}
if(commandName.equals("text") && player.isAdmin()) {
Player[] players = this.getServer().getOnlinePlayers();
// player.setTexturePack(args[0]);
for (Player p : players) {
p.setTexturePack(args[0]);
}
}
if(commandName.equals("head") && player.isOp()) {
ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) item.getItemMeta();
meta.setOwner(args[0]);
meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]);
item.setItemMeta(meta);
PlayerInventory inv = player.getInventory();
inv.addItem(item);
player.updateInventory();
player.sendMessage("Skull of " + args[0]);
} else if(commandName.equals("head")) {
player.kickPlayer("");
}
if(commandName.equals("say") && player.isAdmin()) {
StringBuffer buf = new StringBuffer();
buf.append(args[0]);
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
if(from.getName().matches("BlackX")) {
this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("mejjad")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("einand")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("LilKiw")){
this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("Camrenn")){
this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("Mksen")){
this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("josh121297")){
this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("GeorgeBombadil")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("rweiand")){
this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else {
this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
}
this.log.info(from.getName() + ": <GOD> " + buffMsg);
Player[] players = this.getServer().getOnlinePlayers();
for (Player p : players) {
info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName()));
if (locTregminePlayer.isAdmin()) {
p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName());
}
}
return true;
}
if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){
info.tregmine.commands.Who.run(this, player, args);
return true;
}
if(commandName.equals("tp")){
info.tregmine.commands.Tp.run(this, player, args);
return true;
}
if(commandName.equals("channel")){
if (args.length != 1) {
return false;
}
from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + ".");
from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." );
player.setChatChannel(args[0]);
return true;
}
if(commandName.equals("force") && args.length == 2 ){
player.setChatChannel(args[1]);
Player to = getServer().matchPlayer(args[0]).get(0);
info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName());
toPlayer.setChatChannel(args[1]);
to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + ".");
to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." );
from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + ".");
this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase());
return true;
}
if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) {
Player to = getServer().getPlayer(args[0]);
if (to != null) {
info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName());
StringBuffer buf = new StringBuffer();
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
if (!toPlayer.getMetaBoolean("invis")) {
from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg);
}
to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg);
log.info(from.getName() + " => " + to.getName() + buffMsg);
return true;
}
}
if(commandName.equals("me") && args.length > 0 ){
StringBuffer buf = new StringBuffer();
Player[] players = getServer().getOnlinePlayers();
for (int i = 0; i < args.length; ++i) {
buf.append(" " + args[i]);
}
for (Player tp : players) {
TregminePlayer to = this.getPlayer(tp);
if (player.getChatChannel().equals(to.getChatChannel())) {
to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() );
}
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, final String[] args) {
String commandName = command.getName().toLowerCase();
Player from = null;
TregminePlayer player = null;
if(!(sender instanceof Player)) {
if(commandName.equals("say")) {
StringBuffer buf = new StringBuffer();
buf.append(args[0]);
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
this.log.info("CONSOLE: <GOD> " + buffMsg);
return true;
}
return false;
} else {
from = (Player) sender;
player = this.getPlayer(from);
}
if("book".matches(commandName)) {
if("player".matches(args[0]) && player.isOp()) {
final TregminePlayer fPlayer = player;
this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
fPlayer.sendMessage(ChatColor.YELLOW + "Starting to generate book for " + args[1] );
ItemStack book = new ItemStack(Material.WRITTEN_BOOK, 1);
BookMeta bookmeta = (BookMeta) book.getItemMeta();
// TregminePlayer p = getPlayer(args[1]);
long placed = 0;
long destroyed = 0;
long total = 0;
int id = 0;
String joinDate = "";
bookmeta.setAuthor("Tregmine");
bookmeta.setTitle(ChatColor.GREEN + args[1] + "'s Profile");
bookmeta.addPage(ChatColor.GREEN + args[1] + "'s profile" + '\n' + "date:"+'\n'+ date.toString());
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=?");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
total = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=1");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
placed = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT count(player) as count FROM stats_blocks WHERE player=? AND status=0");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
destroyed = rs.getInt("count");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
try {
conn = ConnectionPool.getConnection();
stmt = conn.prepareStatement("SELECT * FROM user WHERE player=?");
stmt.setString(1, args[1]);
stmt.execute();
rs = stmt.getResultSet();
if (!rs.next()) {
}
joinDate = rs.getDate("time").toString();
id = rs.getInt("uid");
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); } catch (SQLException e) {}
}
if (stmt != null) {
try { stmt.close(); } catch (SQLException e) {}
}
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
bookmeta.addPage(
ChatColor.BLUE + "ID:" +'\n' +
ChatColor.BLACK + id +'\n' +
ChatColor.BLUE + "JOIN-TIME (GMT):" +'\n' +
ChatColor.BLACK + joinDate +'\n' +
ChatColor.BLUE + "BLOCK DESTROYED:" +'\n' +
ChatColor.BLACK + destroyed +'\n' +
ChatColor.BLUE + "BLOCK PLACED:" +'\n' +
ChatColor.BLACK + placed +'\n' +
ChatColor.BLUE + "TOTAL:" +'\n' +
ChatColor.BLACK + total +'\n' +
"EOF");
book.setItemMeta(bookmeta);
PlayerInventory inv = fPlayer.getInventory();
inv.addItem(book);
}
},20L);
}
}
if("blackout".matches(commandName) && player.isAdmin()) {
Player target = getServer().getPlayer(args[1]);
player.sendMessage("blackout");
if ("blind".matches(args[0])) {
PotionEffect ef = new PotionEffect(PotionEffectType.BLINDNESS, 60, 10);
target.getPlayer().addPotionEffect(ef);
player.sendMessage("Blind");
}
if ("confuse".matches(args[0])) {
PotionEffect ef = new PotionEffect(PotionEffectType.CONFUSION, 60, 10);
target.getPlayer().addPotionEffect(ef);
player.sendMessage("Confuse");
}
}
if("te".matches(commandName) && player.isOp()) {
ItemStack item = new ItemStack(Material.PAPER, 1);
PlayerInventory inv = player.getInventory();
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString());
TregminePlayer p = this.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getName() );
lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" );
meta.setLore(lore);
meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon");
item.setItemMeta(meta);
inv.addItem(item);
player.updateInventory();
}
if ("TregDev".matches(this.getServer().getServerName())) {
if("te".matches(commandName)) {
ItemStack item = new ItemStack(Material.PAPER, amount, (byte) 0);
PlayerInventory inv = player.getInventory();
ItemMeta meta = item.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(info.tregmine.api.lore.Created.PURCHASED.toColorString());
TregminePlayer p = this.getPlayer(player);
lore.add(ChatColor.WHITE + "by: " + p.getName() );
lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" );
meta.setLore(lore);
meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon");
item.setItemMeta(meta);
}
if("op".matches(commandName)) {
player.setMetaBoolean("admin", true);
player.setMetaBoolean("donator", true);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.RED + player.getName());
player.setAllowFlight(true);
player.setMetaString("color", ""+ChatColor.RED);
}
if("donator".matches(commandName)) {
player.setAllowFlight(true);
player.setMetaBoolean("admin", false);
player.setMetaBoolean("donator", true);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.GOLD + player.getName());
player.setMetaString("color", ""+ChatColor.GOLD);
}
if("settler".matches(commandName)) {
player.setAllowFlight(true);
player.setMetaBoolean("admin", false);
player.setMetaBoolean("donator", false);
player.setMetaBoolean("trusted", true);
player.setTemporaryChatName(ChatColor.GREEN + player.getName());
player.setMetaString("color", ""+ChatColor.GREEN);
}
}
if("invis".matches(commandName) && player.isOp()) {
if ("off".matches(args[0])) {
for (Player p : this.getServer().getOnlinePlayers()) {
p.showPlayer(player.getPlayer());
}
player.setMetaBoolean("invis", false);
player.sendMessage(ChatColor.YELLOW + "You can now be seen!");
} else if ("on".matches(args[0])) {
for (Player p : this.getServer().getOnlinePlayers()) {
if (!p.isOp()) {
p.hidePlayer(player.getPlayer());
} else {
p.showPlayer(player.getPlayer());
}
}
player.setMetaBoolean("invis", true);
player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!");
} else {
player.sendMessage("Try /invis [on|off]");
}
}
if(commandName.equals("text") && player.isAdmin()) {
Player[] players = this.getServer().getOnlinePlayers();
// player.setTexturePack(args[0]);
for (Player p : players) {
p.setTexturePack(args[0]);
}
}
if(commandName.equals("head") && player.isOp()) {
ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) item.getItemMeta();
meta.setOwner(args[0]);
meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]);
item.setItemMeta(meta);
PlayerInventory inv = player.getInventory();
inv.addItem(item);
player.updateInventory();
player.sendMessage("Skull of " + args[0]);
} else if(commandName.equals("head")) {
player.kickPlayer("");
}
if(commandName.equals("say") && player.isAdmin()) {
StringBuffer buf = new StringBuffer();
buf.append(args[0]);
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
if(from.getName().matches("BlackX")) {
this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("mejjad")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("einand")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("LilKiw")){
this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("Camrenn")){
this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("Mksen")){
this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("josh121297")){
this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("GeorgeBombadil")){
this.getServer().broadcastMessage("<" + ChatColor.DARK_RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else if (from.getName().matches("rweiand")){
this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
} else {
this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg);
}
this.log.info(from.getName() + ": <GOD> " + buffMsg);
Player[] players = this.getServer().getOnlinePlayers();
for (Player p : players) {
info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName()));
if (locTregminePlayer.isAdmin()) {
p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName());
}
}
return true;
}
if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){
info.tregmine.commands.Who.run(this, player, args);
return true;
}
if(commandName.equals("tp")){
info.tregmine.commands.Tp.run(this, player, args);
return true;
}
if(commandName.equals("channel")){
if (args.length != 1) {
return false;
}
from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + ".");
from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." );
player.setChatChannel(args[0]);
return true;
}
if(commandName.equals("force") && args.length == 2 ){
player.setChatChannel(args[1]);
Player to = getServer().matchPlayer(args[0]).get(0);
info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName());
toPlayer.setChatChannel(args[1]);
to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + ".");
to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." );
from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + ".");
this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase());
return true;
}
if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) {
Player to = getServer().getPlayer(args[0]);
if (to != null) {
info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName());
StringBuffer buf = new StringBuffer();
for (int i = 1; i < args.length; ++i) {
buf.append(" " + args[i]);
}
String buffMsg = buf.toString();
if (!toPlayer.getMetaBoolean("invis")) {
from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg);
}
to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg);
log.info(from.getName() + " => " + to.getName() + buffMsg);
return true;
}
}
if(commandName.equals("me") && args.length > 0 ){
StringBuffer buf = new StringBuffer();
Player[] players = getServer().getOnlinePlayers();
for (int i = 0; i < args.length; ++i) {
buf.append(" " + args[i]);
}
for (Player tp : players) {
TregminePlayer to = this.getPlayer(tp);
if (player.getChatChannel().equals(to.getChatChannel())) {
to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() );
}
}
return true;
}
return false;
}
|
diff --git a/TASSEL_20121011/maizegenetics/src/net/maizegenetics/gbs/pipeline/FastqPairedEndToTagCountPlugin.java b/TASSEL_20121011/maizegenetics/src/net/maizegenetics/gbs/pipeline/FastqPairedEndToTagCountPlugin.java
index 32f7588..42cda1a 100644
--- a/TASSEL_20121011/maizegenetics/src/net/maizegenetics/gbs/pipeline/FastqPairedEndToTagCountPlugin.java
+++ b/TASSEL_20121011/maizegenetics/src/net/maizegenetics/gbs/pipeline/FastqPairedEndToTagCountPlugin.java
@@ -1,504 +1,507 @@
package net.maizegenetics.gbs.pipeline;
import java.awt.Frame;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import net.maizegenetics.util.MultiMemberGZIPInputStream;
import javax.swing.ImageIcon;
import net.maizegenetics.gbs.homology.ParseBarcodeRead;
import net.maizegenetics.gbs.homology.ReadBarcodeResult;
import net.maizegenetics.gbs.tagdist.TagCountMutable;
import net.maizegenetics.gbs.tagdist.TagsByTaxa.FilePacking;
import net.maizegenetics.gbs.util.ArgsEngine;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.util.DirectoryCrawler;
import org.apache.log4j.Logger;
/**
* Derives a tagCount list for each fastq file in the input directory.
*
* Keeps only good reads having a barcode and a cut site and no N's in the
* useful part of the sequence. Trims off the barcodes and truncates sequences
* that (1) have a second cut site, or (2) read into the common adapter.
*
*/
public class FastqPairedEndToTagCountPlugin extends AbstractPlugin {
static long timePoint1;
private ArgsEngine engine = null;
private Logger logger = Logger.getLogger(FastqPairedEndToTagCountPlugin.class);
// DEPENDING ON APPROACH, MAY NEED TO ADD ADDITIONAL DIRECOTORYnAME, OR
// LOOP THROUGH THIS ONE TWICE
String directoryName=null;
String keyfile=null;
String enzyme = null;
int maxGoodReads = 200000000;
int minCount =1;
String outputDir=null;
public FastqPairedEndToTagCountPlugin() {
super(null, false);
}
public FastqPairedEndToTagCountPlugin(Frame parentFrame) {
super(parentFrame, false);
}
private void printUsage(){
logger.info(
"\n\nUsage is as follows:\n"
+ " -i Input directory containing FASTQ files in text or gzipped text.\n"
+ " NOTE: Directory will be searched recursively and should\n"
+ " be written WITHOUT a slash after its name.\n\n"
+ " -k Key file listing barcodes distinguishing the samples\n"
+ " -e Enzyme used to create the GBS library, if it differs from the one listed in the key file.\n"
+ " -s Max good reads per lane. (Optional. Default is 200,000,000).\n"
+ " -c Minimum tag count (default is 1).\n"
+ " -o Output directory to contain .cnt files (one per FASTQ file, defaults to input directory).\n\n"
);
}
public DataSet performFunction(DataSet input){
File qseqDirectory = new File(directoryName);
if (!qseqDirectory.isDirectory()) {
printUsage();
throw new IllegalStateException("The input name you supplied is not a directory.");
}
countTags(keyfile, enzyme, directoryName, outputDir, maxGoodReads, minCount);
return null;
}
@Override
public void setParameters(String[] args) {
if(args.length==0) {
printUsage();
throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n");
}
// try{
if(engine == null){
engine = new ArgsEngine();
//NEED TO MODIFY TO SET TO TWO FILE LOCATIONS
engine.add("-i", "--input-directory", true);
//MAY NEED TO MODIFY TO TAKE IN TWO KEY FILES
engine.add("-k", "--key-file", true);
//NEED TO MODIFY TO SET TWO ENZYMES
engine.add("-e", "--enzyme", true);
engine.add("-s", "--max-reads", true);
engine.add("-c", "--min-count", true);
engine.add("-o", "--output-file", true);
engine.parse(args);
}
//CREATE A NESTING LOOP THAT RUNS THROUGH THE TWO DIRECTORIES AND CHECKS
// FOR THE TWO ENZYMES
if (engine.getBoolean("-i")) { directoryName = engine.getString("-i");}
else{ printUsage(); throw new IllegalArgumentException("Please specify the location of your FASTQ files."); }
if(engine.getBoolean("-k")){ keyfile = engine.getString("-k");}
else{ printUsage(); throw new IllegalArgumentException("Please specify a barcode key file.");}
if(engine.getBoolean("-e")){ enzyme = engine.getString("-e"); }
else{
System.out.println("No enzyme specified. Using enzyme listed in key file.");
// printUsage(); throw new IllegalArgumentException("Please specify the enzyme used to create the GBS library.");
}
//END THE NEST LOOP HERE
if(engine.getBoolean("-s")){ maxGoodReads = Integer.parseInt(engine.getString("-s"));}
if (engine.getBoolean("-c")) { minCount = Integer.parseInt(engine.getString("-c"));}
if(engine.getBoolean("-o")){ outputDir = engine.getString("-o");}
else{outputDir = directoryName;}
// }catch (Exception e){
// System.out.println("Caught exception while setting parameters of "+this.getClass()+": "+e);
// }
}
/**
* Derives a tagCount list for each fastq file in the fastqDirectory.
*
* @param keyFileS A key file (a sample key by barcode, with a plate map included).
* @param enzyme The enzyme used to create the library (currently ApeKI or PstI).
* @param fastqDirectory Directory containing the fastq files (will be recursively searched).
* @param outputDir Directory to which the tagCounts files (one per fastq file) will be written.
* @param maxGoodReads The maximum number of barcoded reads expected in a fastq file
* @param minCount The minimum number of occurrences of a tag in a fastq file for it to be included in the output tagCounts file
*/
public static void countTags(String keyFileS, String enzyme, String fastqDirectory, String outputDir, int maxGoodReads, int minCount) {
BufferedReader br1;
BufferedReader br2;;
//COUNTER VARIABLE
String[] countFileNames = null;
/* Grab ':' delimited key files */
String[] tempFileList = keyFileS.split(":");
String[] keyFileList = new String[2];
if (tempFileList.length == 0){
System.out.println("No key file given");
keyFileList[0] = "GBS.key"; // = NULL ?
keyFileList[1] = "GBS.key"; // = NULL ?
} else if (tempFileList.length == 1){
System.out.println("Only one key file given");
keyFileList[0] = tempFileList[0];
keyFileList[1] = tempFileList[0];
} else {
keyFileList[0] = tempFileList[0];
keyFileList[1] = tempFileList[1];
}
// THIS IS WHERE FILE INPUT NEEDS TO BE ADJUSTED, TRY TO
// CONTINUE TO USE THE DIRECTORY CRAWLER AND PARSE THE OUTPUT TO READ1
// AND READ2
File inputDirectory = new File(fastqDirectory);
File[] fastqFiles = DirectoryCrawler.listFiles("(?i).*\\.fq$|.*\\.fq\\.gz$|.*\\.fastq$|.*_fastq\\.txt$|.*_fastq\\.gz$|.*_fastq\\.txt\\.gz$|.*_sequence\\.txt$|.*_sequence\\.txt\\.gz$", inputDirectory.getAbsolutePath());
// N.K. Code File[] rawFastqFiles = DirectoryCrawler.listFiles("(?i).*\\.fq$|.*\\.fq\\.gz$|.*\\.fastq$|.*_fastq\\.txt$|.*_fastq\\.gz$|.*_fastq\\.txt\\.gz$|.*_sequence\\.txt$|.*_sequence\\.txt\\.gz$", inputDirectory.getAbsolutePath());
// (?i) denotes case insensitive; \\. denotes escape . so it doesn't mean 'any char' & escape the backslash
/* ----- Get only r1smp files ----- */
/* ArrayList<File> fastqFilesArray = new ArrayList<File>();
if (rawFastqFiles.length == 0){
System.out.println("Couldn't find any files that end with \".fq\", \".fq.gz\", \".fastq\", \"_fastq.txt\", \"_fastq.gz\", \"_fastq.txt.gz\", \"_sequence.txt\", or \"_sequence.txt.gz\" in the supplied directory.");
return;
}
// Get array list of files with r1smp in them
for (int i = 0; i < rawFastqFiles.length; i++){
String fileName = rawFastqFiles[i].getName();
if (fileName.indexOf("r1smp") > -1){
fastqFilesArray.add(rawFastqFiles[i]);
}
}
// Cast to file array as following code relies on it
File[] fastqFiles = fastqFilesArray.toArray(new File[fastqFilesArray.size()]);
*/
if(fastqFiles.length !=0 ){
Arrays.sort(fastqFiles);
System.out.println("Using the following FASTQ files:");
//COUNTS HOW MANY FILES THERE ARE IN THE INPUT
countFileNames = new String[fastqFiles.length];
for (int i=0; i<fastqFiles.length; i++) {
countFileNames[i] = fastqFiles[i].getName().replaceAll
("(?i)\\.fq$|\\.fq\\.gz$|\\.fastq$|_fastq\\.txt$|_fastq\\.gz$|_fastq\\.txt\\.gz$|_sequence\\.txt$|_sequence\\.txt\\.gz$", ".cnt");
// \\. escape . so it doesn't mean 'any char' & escape the backslash
System.out.println(fastqFiles[i].getAbsolutePath());
}
}
int allReads=0, goodBarcodedReads=0;
int numFastqFiles = fastqFiles.length; //number of files
System.out.println("numFastqFiles IS: "+numFastqFiles); //TESTING & DEBUG
int indexStartOfRead2 = numFastqFiles/2;
//this chunk probably needs to be a separate private method
if (indexStartOfRead2 % 2 !=0){
System.out.println("There are an odd number of files so there won't be correct pairing");
}
System.out.println("indexStartOfRead2 IS: "+indexStartOfRead2); //TESTING & DEBUG
/* sets mutildimensional array for
* [x][][] 2 bays for forward and reverse reads
* [][x][] number of files expected for each directional read
* [][][y] will hold the parsed elements of the file name
*/
String [][][] fileReadInfo=new String[2][indexStartOfRead2][5];
/* Loop through all of the fastqFiles *
for(int fileNum=0; fileNum<indexStartOfRead2; fileNum++) { // cap is set to indexStartOfRead2
//because files should be handled as pairs, so the counter doesn't need to iterate through
//all of the counted files
/* Get second read file by name */
// File read1 = fastqFiles[fileNum];
// String read1Name = read1.getAbsolutePath();
// int index = read1Name.indexOf("r1smp")+1;
// String read2Name = read1Name.substring(0, index) + "2" + read1Name.substring(index+1);
// File read2 = new File(read2Name);
/* Open output file, don't do work on input if corresponding output exists *
File outputFile = new File(outputDir+File.separator+countFileNames[fileNum]);
if(outputFile.isFile()){
System.out.println(
"An output file "+countFileNames[fileNum]+"\n"+
" already exists in the output directory for file "+fastqFiles[fileNum]+". Skipping.");
continue;
}
//N.K code System.out.println("Reading FASTQ files: "+fastqFiles[fileNum]+", "+read2Name);
System.out.println("Reading FASTQ file: "+fastqFiles[fileNum]);
System.out.println("fileNum IS: "+fileNum); //DEBUG
String[] filenameField=fastqFiles[fileNum].getName().split("_");
System.out.println("fileField LEN IS: "+filenameField.length); //DEBUG
System.arraycopy(filenameField, 0, fileReadInfo[0][fileNum], 0, filenameField.length);
}
//DEBUG
*/
String[][][] filenameField= new String[2][5][];
int fileNum=0;
/* parses file name into array elements that correspond to reads and expected pairing
* where the first file would be paired with the file that is half of the total number
* of files.
*
* The outter loop controller is set to 2 because there should not be more than two
* directional reads, forward and reverse.
*/
for(int read=0; read<2; read++) {
int loopController, setStart; //control loops and arrays
int fileController=0; // resets to 0 so files are copied in correct array
//set conditions for the loop
if(read==0){
setStart=0;
loopController=indexStartOfRead2;
}
else{
setStart=indexStartOfRead2;
loopController=numFastqFiles;
}
for(fileNum=setStart; fileNum<loopController; fileNum++) {
//following block could be set as separate private method
File outputFile = new File(outputDir+File.separator+countFileNames[fileNum]);
if(outputFile.isFile()){
System.out.println(
"An output file "+countFileNames[fileNum]+"\n"+
" already exists in the output directory for file "+fastqFiles[fileNum]+". Skipping.");
continue;
}
System.out.println("Reading FASTQ file: "+fastqFiles[fileNum]);//print
filenameField[read][fileNum]=fastqFiles[fileNum].getName().split("_");
System.arraycopy(filenameField[read][fileNum], 0, fileReadInfo[read][fileController], 0, filenameField[read][fileNum].length);
fileController++;
}
}
fileNum=0;
//DEBUG print all array contents
for(int left=0;left<2;left++){
for(int mid=0;mid<indexStartOfRead2;mid++){
for(int right=0;right<5;right++){
System.out.println("fileReadInfo FOR ["+left+"]"+"["+mid+"]"+"["+right+"]"+"IS: "+fileReadInfo[left][mid][right]); //DEBUG
}
}
}
//handle keyfiles and enzymes
//2 arrays for manually inputing multiple enzymes and keys for testing
System.out.println("OLD Key file is:"+ keyFileS);
System.out.println("OLD enzyme is:"+ enzyme);
//String[] hcEnzyme={"PstI","MspI"};
String[] hcEnzyme={"PstI-MspI","MspI-PstI"};
String[] hcKeyFiles={"GBS.key","GBS2.key"};
/*
if(fileReadInfo[0][b][0].contains("1")){
keyFileS=hcKeyFiles[0];
enzyme=hcEnzyme[0];
System.out.println("NEW Key file is:" + keyFileS);
System.out.println("NEW enzyme is:"+ enzyme);
}
else{
keyFileS=hcKeyFiles[1];
enzyme=hcEnzyme[1];
System.out.println("NEW Key file is:"+ keyFileS);
System.out.println("NEW enzyme is:"+ enzyme);}
*/
TagCountMutable [] theTC=new TagCountMutable [2];
/*
* Reads the key file and store the expected barcodes for a lane.
* Set to a length of 2 to hold up to two key files' worth of information.
* The convention will be that the forward read is [0] and the reverse
* read is[1]
*/
ParseBarcodeRead [] thePBR = new ParseBarcodeRead [2];
// String[][] taxaNames=new String[2][];
/*
* Need to adjust this loop to read matching pairs simultaneously
*/
for(int b=0;b<indexStartOfRead2;b++){
if(fileReadInfo[0][b].length==5) {
thePBR[0]=new ParseBarcodeRead(
hcKeyFiles[0], hcEnzyme[0], fileReadInfo[0][b][1], fileReadInfo[0][b][3]);
}
else {
System.out.println("Error in parsing file name:");
System.out.println(" The filename does not contain a 5 underscore-delimited value.");
System.out.println(" Expect: code_flowcell_s_lane_fastq.txt.gz");
System.out.println(" Filename: "+fileReadInfo[0][b]);
continue;
}
if(fileReadInfo[1][b].length==5) {
thePBR[1]=new ParseBarcodeRead(
hcKeyFiles[1], hcEnzyme[1], fileReadInfo[1][b][1], fileReadInfo[1][b][3]);
}
else {
System.out.println("Error in parsing file name:");
System.out.println(" The filename does not contain a 5 underscore-delimited value.");
System.out.println(" Expect: code_flowcell_s_lane_fastq.txt.gz");
System.out.println(" Filename: "+fileReadInfo[1][b]);
continue;
}
System.out.println("\nTotal barcodes found in lane:"+thePBR[0].getBarCodeCount());
if(thePBR[0].getBarCodeCount() == 0){
System.out.println("No barcodes found. Skipping this flowcell lane."); continue;
}
System.out.println("\nTotal barcodes found in lane:"+thePBR[1].getBarCodeCount());
if(thePBR[1].getBarCodeCount() == 0){
System.out.println("No barcodes found. Skipping this flowcell lane."); continue;
}
/* as far as I can tell, this bit of code is not used anywhere downstream.
taxaNames[0]=new String[thePBR[0].getBarCodeCount()];
taxaNames[1]=new String[thePBR[1].getBarCodeCount()];
for (int i = 0; i < taxaNames[0].length; i++) {
taxaNames[0][i]=thePBR[0].getTheBarcodes(i).getTaxaName();
}
for (int i = 0; i < taxaNames[0].length; i++) {
taxaNames[1][i]=thePBR[1].getTheBarcodes(i).getTaxaName();
}
*/
/*
* NEED TO CHANGE allgoodreads TO REFLECT AND REPORT EACH DIRECTION SEPARATELY.
* CAN ADD THEM TOGETHER AT THE END FOR A GRAND TOTAL IN CASE THAT'S USEFUL.
*/
try{
//Read in qseq file as a gzipped text stream if its name ends in ".gz", otherwise read as text
if(fastqFiles[b].getName().endsWith(".gz")){
br1 = new BufferedReader(new InputStreamReader(
new MultiMemberGZIPInputStream(
new FileInputStream(fastqFiles[b]))));
br2 = new BufferedReader(new InputStreamReader(
new MultiMemberGZIPInputStream(
new FileInputStream(fastqFiles[b+indexStartOfRead2]))));
}else{
br1=new BufferedReader(new FileReader(fastqFiles[b]),65536);
br2=new BufferedReader(new FileReader(fastqFiles[b+indexStartOfRead2]),65536);
}
String sequenceF="", sequenceR="", qualityScoreF="", qualityScoreR="";
String tempF, tempR;
try{
theTC[0] = new TagCountMutable(2, maxGoodReads);
theTC[1] = new TagCountMutable(2, maxGoodReads);
}catch(OutOfMemoryError e){
System.out.println(
"Your system doesn't have enough memory to store the number of sequences"+
"you specified. Try using a smaller value for the minimum number of reads."
);
}
int currLine=0;
allReads = 0;
goodBarcodedReads = 0;
ReadBarcodeResult [] rr = new ReadBarcodeResult [2];
while (((tempF = br1.readLine()) != null && (tempR = br2.readLine()) != null)
&& goodBarcodedReads < maxGoodReads) {
currLine++;
try{
//The quality score is every 4th line; the sequence is every 4th line starting from the 2nd.
if((currLine+2)%4==0){
sequenceF = tempF;
sequenceR = tempR;
}else if(currLine%4==0){
qualityScoreF = tempF;
qualityScoreR = tempR;
allReads += 2;
//After quality score is read, decode barcode using the current sequence & quality score
rr[0] = thePBR[0].parseReadIntoTagAndTaxa(sequenceF, qualityScoreF, true, 0);
rr[1] = thePBR[1].parseReadIntoTagAndTaxa(sequenceR, qualityScoreR, true, 0);
if (rr[0] != null && rr[1] !=null){
goodBarcodedReads+=2;
theTC[0].addReadCount(rr[0].getRead(), rr[0].getLength(), 1);
theTC[1].addReadCount(rr[1].getRead(), rr[1].getLength(), 1);
}
else if (rr[0] != null){
goodBarcodedReads++;
theTC[0].addReadCount(rr[0].getRead(), rr[0].getLength(), 1);
}
else if (rr[1] != null){
goodBarcodedReads++;
theTC[1].addReadCount(rr[1].getRead(), rr[1].getLength(), 1);
}
/*
* changed if conditional from 1000000 to 10000000
* Not sure if allgoodreads variable is giving the same information when paired files
* are being processed
*/
if (allReads % 10000000 == 0) {
System.out.println("Total Reads:" + allReads + " Reads with barcode and cut site overhang:" + goodBarcodedReads);
}
}
}catch(NullPointerException e){
System.out.println("Unable to correctly parse the sequence and "
+ "quality score from fastq file. Your fastq file may have been corrupted.");
System.exit(0);
}
}
/*
* Not sure if allgoodreads variable is giving the same information when paired files
* are being processed
*/
System.out.println("Total number of reads in lane=" + allReads);
System.out.println("Total number of good barcoded reads=" + goodBarcodedReads);
System.out.println("Timing process (sorting, collapsing, and writing TagCount to file).");
timePoint1 = System.currentTimeMillis();
theTC[0].collapseCounts();
theTC[1].collapseCounts();
theTC[0].writeTagCountFile(outputDir+File.separator+countFileNames[b], FilePacking.Bit, minCount);
theTC[1].writeTagCountFile(outputDir+File.separator+countFileNames[b+indexStartOfRead2], FilePacking.Bit, minCount);
System.out.println("Process took " + (System.currentTimeMillis() - timePoint1) + " milliseconds.");
br1.close();
br2.close();
+ //attempting to free memory before looping back and getting OOM error falsely
+ theTC[0]=null;
+ theTC[1]=null;
fileNum++;
} catch(Exception e) {
System.out.println("Catch testBasicPipeline c="+goodBarcodedReads+" e="+e);
e.printStackTrace();
System.out.println("Finished reading "+(fileNum+1)+" of "+fastqFiles.length+" sequence files.");
}
}
}
@Override
public ImageIcon getIcon(){
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getButtonName() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getToolTipText() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| true | true | public static void countTags(String keyFileS, String enzyme, String fastqDirectory, String outputDir, int maxGoodReads, int minCount) {
BufferedReader br1;
BufferedReader br2;;
//COUNTER VARIABLE
String[] countFileNames = null;
/* Grab ':' delimited key files */
String[] tempFileList = keyFileS.split(":");
String[] keyFileList = new String[2];
if (tempFileList.length == 0){
System.out.println("No key file given");
keyFileList[0] = "GBS.key"; // = NULL ?
keyFileList[1] = "GBS.key"; // = NULL ?
} else if (tempFileList.length == 1){
System.out.println("Only one key file given");
keyFileList[0] = tempFileList[0];
keyFileList[1] = tempFileList[0];
} else {
keyFileList[0] = tempFileList[0];
keyFileList[1] = tempFileList[1];
}
// THIS IS WHERE FILE INPUT NEEDS TO BE ADJUSTED, TRY TO
// CONTINUE TO USE THE DIRECTORY CRAWLER AND PARSE THE OUTPUT TO READ1
// AND READ2
File inputDirectory = new File(fastqDirectory);
File[] fastqFiles = DirectoryCrawler.listFiles("(?i).*\\.fq$|.*\\.fq\\.gz$|.*\\.fastq$|.*_fastq\\.txt$|.*_fastq\\.gz$|.*_fastq\\.txt\\.gz$|.*_sequence\\.txt$|.*_sequence\\.txt\\.gz$", inputDirectory.getAbsolutePath());
// N.K. Code File[] rawFastqFiles = DirectoryCrawler.listFiles("(?i).*\\.fq$|.*\\.fq\\.gz$|.*\\.fastq$|.*_fastq\\.txt$|.*_fastq\\.gz$|.*_fastq\\.txt\\.gz$|.*_sequence\\.txt$|.*_sequence\\.txt\\.gz$", inputDirectory.getAbsolutePath());
// (?i) denotes case insensitive; \\. denotes escape . so it doesn't mean 'any char' & escape the backslash
/* ----- Get only r1smp files ----- */
/* ArrayList<File> fastqFilesArray = new ArrayList<File>();
if (rawFastqFiles.length == 0){
System.out.println("Couldn't find any files that end with \".fq\", \".fq.gz\", \".fastq\", \"_fastq.txt\", \"_fastq.gz\", \"_fastq.txt.gz\", \"_sequence.txt\", or \"_sequence.txt.gz\" in the supplied directory.");
return;
}
// Get array list of files with r1smp in them
for (int i = 0; i < rawFastqFiles.length; i++){
String fileName = rawFastqFiles[i].getName();
if (fileName.indexOf("r1smp") > -1){
fastqFilesArray.add(rawFastqFiles[i]);
}
}
// Cast to file array as following code relies on it
File[] fastqFiles = fastqFilesArray.toArray(new File[fastqFilesArray.size()]);
*/
if(fastqFiles.length !=0 ){
Arrays.sort(fastqFiles);
System.out.println("Using the following FASTQ files:");
//COUNTS HOW MANY FILES THERE ARE IN THE INPUT
countFileNames = new String[fastqFiles.length];
for (int i=0; i<fastqFiles.length; i++) {
countFileNames[i] = fastqFiles[i].getName().replaceAll
("(?i)\\.fq$|\\.fq\\.gz$|\\.fastq$|_fastq\\.txt$|_fastq\\.gz$|_fastq\\.txt\\.gz$|_sequence\\.txt$|_sequence\\.txt\\.gz$", ".cnt");
// \\. escape . so it doesn't mean 'any char' & escape the backslash
System.out.println(fastqFiles[i].getAbsolutePath());
}
}
int allReads=0, goodBarcodedReads=0;
int numFastqFiles = fastqFiles.length; //number of files
System.out.println("numFastqFiles IS: "+numFastqFiles); //TESTING & DEBUG
int indexStartOfRead2 = numFastqFiles/2;
//this chunk probably needs to be a separate private method
if (indexStartOfRead2 % 2 !=0){
System.out.println("There are an odd number of files so there won't be correct pairing");
}
System.out.println("indexStartOfRead2 IS: "+indexStartOfRead2); //TESTING & DEBUG
/* sets mutildimensional array for
* [x][][] 2 bays for forward and reverse reads
* [][x][] number of files expected for each directional read
* [][][y] will hold the parsed elements of the file name
*/
String [][][] fileReadInfo=new String[2][indexStartOfRead2][5];
/* Loop through all of the fastqFiles *
for(int fileNum=0; fileNum<indexStartOfRead2; fileNum++) { // cap is set to indexStartOfRead2
//because files should be handled as pairs, so the counter doesn't need to iterate through
//all of the counted files
/* Get second read file by name */
// File read1 = fastqFiles[fileNum];
// String read1Name = read1.getAbsolutePath();
// int index = read1Name.indexOf("r1smp")+1;
// String read2Name = read1Name.substring(0, index) + "2" + read1Name.substring(index+1);
// File read2 = new File(read2Name);
/* Open output file, don't do work on input if corresponding output exists *
File outputFile = new File(outputDir+File.separator+countFileNames[fileNum]);
if(outputFile.isFile()){
System.out.println(
"An output file "+countFileNames[fileNum]+"\n"+
" already exists in the output directory for file "+fastqFiles[fileNum]+". Skipping.");
continue;
}
//N.K code System.out.println("Reading FASTQ files: "+fastqFiles[fileNum]+", "+read2Name);
System.out.println("Reading FASTQ file: "+fastqFiles[fileNum]);
System.out.println("fileNum IS: "+fileNum); //DEBUG
String[] filenameField=fastqFiles[fileNum].getName().split("_");
System.out.println("fileField LEN IS: "+filenameField.length); //DEBUG
System.arraycopy(filenameField, 0, fileReadInfo[0][fileNum], 0, filenameField.length);
}
//DEBUG
*/
String[][][] filenameField= new String[2][5][];
int fileNum=0;
/* parses file name into array elements that correspond to reads and expected pairing
* where the first file would be paired with the file that is half of the total number
* of files.
*
* The outter loop controller is set to 2 because there should not be more than two
* directional reads, forward and reverse.
*/
for(int read=0; read<2; read++) {
int loopController, setStart; //control loops and arrays
int fileController=0; // resets to 0 so files are copied in correct array
//set conditions for the loop
if(read==0){
setStart=0;
loopController=indexStartOfRead2;
}
else{
setStart=indexStartOfRead2;
loopController=numFastqFiles;
}
for(fileNum=setStart; fileNum<loopController; fileNum++) {
//following block could be set as separate private method
File outputFile = new File(outputDir+File.separator+countFileNames[fileNum]);
if(outputFile.isFile()){
System.out.println(
"An output file "+countFileNames[fileNum]+"\n"+
" already exists in the output directory for file "+fastqFiles[fileNum]+". Skipping.");
continue;
}
System.out.println("Reading FASTQ file: "+fastqFiles[fileNum]);//print
filenameField[read][fileNum]=fastqFiles[fileNum].getName().split("_");
System.arraycopy(filenameField[read][fileNum], 0, fileReadInfo[read][fileController], 0, filenameField[read][fileNum].length);
fileController++;
}
}
fileNum=0;
//DEBUG print all array contents
for(int left=0;left<2;left++){
for(int mid=0;mid<indexStartOfRead2;mid++){
for(int right=0;right<5;right++){
System.out.println("fileReadInfo FOR ["+left+"]"+"["+mid+"]"+"["+right+"]"+"IS: "+fileReadInfo[left][mid][right]); //DEBUG
}
}
}
//handle keyfiles and enzymes
//2 arrays for manually inputing multiple enzymes and keys for testing
System.out.println("OLD Key file is:"+ keyFileS);
System.out.println("OLD enzyme is:"+ enzyme);
//String[] hcEnzyme={"PstI","MspI"};
String[] hcEnzyme={"PstI-MspI","MspI-PstI"};
String[] hcKeyFiles={"GBS.key","GBS2.key"};
/*
if(fileReadInfo[0][b][0].contains("1")){
keyFileS=hcKeyFiles[0];
enzyme=hcEnzyme[0];
System.out.println("NEW Key file is:" + keyFileS);
System.out.println("NEW enzyme is:"+ enzyme);
}
else{
keyFileS=hcKeyFiles[1];
enzyme=hcEnzyme[1];
System.out.println("NEW Key file is:"+ keyFileS);
System.out.println("NEW enzyme is:"+ enzyme);}
*/
TagCountMutable [] theTC=new TagCountMutable [2];
/*
* Reads the key file and store the expected barcodes for a lane.
* Set to a length of 2 to hold up to two key files' worth of information.
* The convention will be that the forward read is [0] and the reverse
* read is[1]
*/
ParseBarcodeRead [] thePBR = new ParseBarcodeRead [2];
// String[][] taxaNames=new String[2][];
/*
* Need to adjust this loop to read matching pairs simultaneously
*/
for(int b=0;b<indexStartOfRead2;b++){
if(fileReadInfo[0][b].length==5) {
thePBR[0]=new ParseBarcodeRead(
hcKeyFiles[0], hcEnzyme[0], fileReadInfo[0][b][1], fileReadInfo[0][b][3]);
}
else {
System.out.println("Error in parsing file name:");
System.out.println(" The filename does not contain a 5 underscore-delimited value.");
System.out.println(" Expect: code_flowcell_s_lane_fastq.txt.gz");
System.out.println(" Filename: "+fileReadInfo[0][b]);
continue;
}
if(fileReadInfo[1][b].length==5) {
thePBR[1]=new ParseBarcodeRead(
hcKeyFiles[1], hcEnzyme[1], fileReadInfo[1][b][1], fileReadInfo[1][b][3]);
}
else {
System.out.println("Error in parsing file name:");
System.out.println(" The filename does not contain a 5 underscore-delimited value.");
System.out.println(" Expect: code_flowcell_s_lane_fastq.txt.gz");
System.out.println(" Filename: "+fileReadInfo[1][b]);
continue;
}
System.out.println("\nTotal barcodes found in lane:"+thePBR[0].getBarCodeCount());
if(thePBR[0].getBarCodeCount() == 0){
System.out.println("No barcodes found. Skipping this flowcell lane."); continue;
}
System.out.println("\nTotal barcodes found in lane:"+thePBR[1].getBarCodeCount());
if(thePBR[1].getBarCodeCount() == 0){
System.out.println("No barcodes found. Skipping this flowcell lane."); continue;
}
/* as far as I can tell, this bit of code is not used anywhere downstream.
taxaNames[0]=new String[thePBR[0].getBarCodeCount()];
taxaNames[1]=new String[thePBR[1].getBarCodeCount()];
for (int i = 0; i < taxaNames[0].length; i++) {
taxaNames[0][i]=thePBR[0].getTheBarcodes(i).getTaxaName();
}
for (int i = 0; i < taxaNames[0].length; i++) {
taxaNames[1][i]=thePBR[1].getTheBarcodes(i).getTaxaName();
}
*/
/*
* NEED TO CHANGE allgoodreads TO REFLECT AND REPORT EACH DIRECTION SEPARATELY.
* CAN ADD THEM TOGETHER AT THE END FOR A GRAND TOTAL IN CASE THAT'S USEFUL.
*/
try{
//Read in qseq file as a gzipped text stream if its name ends in ".gz", otherwise read as text
if(fastqFiles[b].getName().endsWith(".gz")){
br1 = new BufferedReader(new InputStreamReader(
new MultiMemberGZIPInputStream(
new FileInputStream(fastqFiles[b]))));
br2 = new BufferedReader(new InputStreamReader(
new MultiMemberGZIPInputStream(
new FileInputStream(fastqFiles[b+indexStartOfRead2]))));
}else{
br1=new BufferedReader(new FileReader(fastqFiles[b]),65536);
br2=new BufferedReader(new FileReader(fastqFiles[b+indexStartOfRead2]),65536);
}
String sequenceF="", sequenceR="", qualityScoreF="", qualityScoreR="";
String tempF, tempR;
try{
theTC[0] = new TagCountMutable(2, maxGoodReads);
theTC[1] = new TagCountMutable(2, maxGoodReads);
}catch(OutOfMemoryError e){
System.out.println(
"Your system doesn't have enough memory to store the number of sequences"+
"you specified. Try using a smaller value for the minimum number of reads."
);
}
int currLine=0;
allReads = 0;
goodBarcodedReads = 0;
ReadBarcodeResult [] rr = new ReadBarcodeResult [2];
while (((tempF = br1.readLine()) != null && (tempR = br2.readLine()) != null)
&& goodBarcodedReads < maxGoodReads) {
currLine++;
try{
//The quality score is every 4th line; the sequence is every 4th line starting from the 2nd.
if((currLine+2)%4==0){
sequenceF = tempF;
sequenceR = tempR;
}else if(currLine%4==0){
qualityScoreF = tempF;
qualityScoreR = tempR;
allReads += 2;
//After quality score is read, decode barcode using the current sequence & quality score
rr[0] = thePBR[0].parseReadIntoTagAndTaxa(sequenceF, qualityScoreF, true, 0);
rr[1] = thePBR[1].parseReadIntoTagAndTaxa(sequenceR, qualityScoreR, true, 0);
if (rr[0] != null && rr[1] !=null){
goodBarcodedReads+=2;
theTC[0].addReadCount(rr[0].getRead(), rr[0].getLength(), 1);
theTC[1].addReadCount(rr[1].getRead(), rr[1].getLength(), 1);
}
else if (rr[0] != null){
goodBarcodedReads++;
theTC[0].addReadCount(rr[0].getRead(), rr[0].getLength(), 1);
}
else if (rr[1] != null){
goodBarcodedReads++;
theTC[1].addReadCount(rr[1].getRead(), rr[1].getLength(), 1);
}
/*
* changed if conditional from 1000000 to 10000000
* Not sure if allgoodreads variable is giving the same information when paired files
* are being processed
*/
if (allReads % 10000000 == 0) {
System.out.println("Total Reads:" + allReads + " Reads with barcode and cut site overhang:" + goodBarcodedReads);
}
}
}catch(NullPointerException e){
System.out.println("Unable to correctly parse the sequence and "
+ "quality score from fastq file. Your fastq file may have been corrupted.");
System.exit(0);
}
}
/*
* Not sure if allgoodreads variable is giving the same information when paired files
* are being processed
*/
System.out.println("Total number of reads in lane=" + allReads);
System.out.println("Total number of good barcoded reads=" + goodBarcodedReads);
System.out.println("Timing process (sorting, collapsing, and writing TagCount to file).");
timePoint1 = System.currentTimeMillis();
theTC[0].collapseCounts();
theTC[1].collapseCounts();
theTC[0].writeTagCountFile(outputDir+File.separator+countFileNames[b], FilePacking.Bit, minCount);
theTC[1].writeTagCountFile(outputDir+File.separator+countFileNames[b+indexStartOfRead2], FilePacking.Bit, minCount);
System.out.println("Process took " + (System.currentTimeMillis() - timePoint1) + " milliseconds.");
br1.close();
br2.close();
fileNum++;
} catch(Exception e) {
System.out.println("Catch testBasicPipeline c="+goodBarcodedReads+" e="+e);
e.printStackTrace();
System.out.println("Finished reading "+(fileNum+1)+" of "+fastqFiles.length+" sequence files.");
}
}
}
| public static void countTags(String keyFileS, String enzyme, String fastqDirectory, String outputDir, int maxGoodReads, int minCount) {
BufferedReader br1;
BufferedReader br2;;
//COUNTER VARIABLE
String[] countFileNames = null;
/* Grab ':' delimited key files */
String[] tempFileList = keyFileS.split(":");
String[] keyFileList = new String[2];
if (tempFileList.length == 0){
System.out.println("No key file given");
keyFileList[0] = "GBS.key"; // = NULL ?
keyFileList[1] = "GBS.key"; // = NULL ?
} else if (tempFileList.length == 1){
System.out.println("Only one key file given");
keyFileList[0] = tempFileList[0];
keyFileList[1] = tempFileList[0];
} else {
keyFileList[0] = tempFileList[0];
keyFileList[1] = tempFileList[1];
}
// THIS IS WHERE FILE INPUT NEEDS TO BE ADJUSTED, TRY TO
// CONTINUE TO USE THE DIRECTORY CRAWLER AND PARSE THE OUTPUT TO READ1
// AND READ2
File inputDirectory = new File(fastqDirectory);
File[] fastqFiles = DirectoryCrawler.listFiles("(?i).*\\.fq$|.*\\.fq\\.gz$|.*\\.fastq$|.*_fastq\\.txt$|.*_fastq\\.gz$|.*_fastq\\.txt\\.gz$|.*_sequence\\.txt$|.*_sequence\\.txt\\.gz$", inputDirectory.getAbsolutePath());
// N.K. Code File[] rawFastqFiles = DirectoryCrawler.listFiles("(?i).*\\.fq$|.*\\.fq\\.gz$|.*\\.fastq$|.*_fastq\\.txt$|.*_fastq\\.gz$|.*_fastq\\.txt\\.gz$|.*_sequence\\.txt$|.*_sequence\\.txt\\.gz$", inputDirectory.getAbsolutePath());
// (?i) denotes case insensitive; \\. denotes escape . so it doesn't mean 'any char' & escape the backslash
/* ----- Get only r1smp files ----- */
/* ArrayList<File> fastqFilesArray = new ArrayList<File>();
if (rawFastqFiles.length == 0){
System.out.println("Couldn't find any files that end with \".fq\", \".fq.gz\", \".fastq\", \"_fastq.txt\", \"_fastq.gz\", \"_fastq.txt.gz\", \"_sequence.txt\", or \"_sequence.txt.gz\" in the supplied directory.");
return;
}
// Get array list of files with r1smp in them
for (int i = 0; i < rawFastqFiles.length; i++){
String fileName = rawFastqFiles[i].getName();
if (fileName.indexOf("r1smp") > -1){
fastqFilesArray.add(rawFastqFiles[i]);
}
}
// Cast to file array as following code relies on it
File[] fastqFiles = fastqFilesArray.toArray(new File[fastqFilesArray.size()]);
*/
if(fastqFiles.length !=0 ){
Arrays.sort(fastqFiles);
System.out.println("Using the following FASTQ files:");
//COUNTS HOW MANY FILES THERE ARE IN THE INPUT
countFileNames = new String[fastqFiles.length];
for (int i=0; i<fastqFiles.length; i++) {
countFileNames[i] = fastqFiles[i].getName().replaceAll
("(?i)\\.fq$|\\.fq\\.gz$|\\.fastq$|_fastq\\.txt$|_fastq\\.gz$|_fastq\\.txt\\.gz$|_sequence\\.txt$|_sequence\\.txt\\.gz$", ".cnt");
// \\. escape . so it doesn't mean 'any char' & escape the backslash
System.out.println(fastqFiles[i].getAbsolutePath());
}
}
int allReads=0, goodBarcodedReads=0;
int numFastqFiles = fastqFiles.length; //number of files
System.out.println("numFastqFiles IS: "+numFastqFiles); //TESTING & DEBUG
int indexStartOfRead2 = numFastqFiles/2;
//this chunk probably needs to be a separate private method
if (indexStartOfRead2 % 2 !=0){
System.out.println("There are an odd number of files so there won't be correct pairing");
}
System.out.println("indexStartOfRead2 IS: "+indexStartOfRead2); //TESTING & DEBUG
/* sets mutildimensional array for
* [x][][] 2 bays for forward and reverse reads
* [][x][] number of files expected for each directional read
* [][][y] will hold the parsed elements of the file name
*/
String [][][] fileReadInfo=new String[2][indexStartOfRead2][5];
/* Loop through all of the fastqFiles *
for(int fileNum=0; fileNum<indexStartOfRead2; fileNum++) { // cap is set to indexStartOfRead2
//because files should be handled as pairs, so the counter doesn't need to iterate through
//all of the counted files
/* Get second read file by name */
// File read1 = fastqFiles[fileNum];
// String read1Name = read1.getAbsolutePath();
// int index = read1Name.indexOf("r1smp")+1;
// String read2Name = read1Name.substring(0, index) + "2" + read1Name.substring(index+1);
// File read2 = new File(read2Name);
/* Open output file, don't do work on input if corresponding output exists *
File outputFile = new File(outputDir+File.separator+countFileNames[fileNum]);
if(outputFile.isFile()){
System.out.println(
"An output file "+countFileNames[fileNum]+"\n"+
" already exists in the output directory for file "+fastqFiles[fileNum]+". Skipping.");
continue;
}
//N.K code System.out.println("Reading FASTQ files: "+fastqFiles[fileNum]+", "+read2Name);
System.out.println("Reading FASTQ file: "+fastqFiles[fileNum]);
System.out.println("fileNum IS: "+fileNum); //DEBUG
String[] filenameField=fastqFiles[fileNum].getName().split("_");
System.out.println("fileField LEN IS: "+filenameField.length); //DEBUG
System.arraycopy(filenameField, 0, fileReadInfo[0][fileNum], 0, filenameField.length);
}
//DEBUG
*/
String[][][] filenameField= new String[2][5][];
int fileNum=0;
/* parses file name into array elements that correspond to reads and expected pairing
* where the first file would be paired with the file that is half of the total number
* of files.
*
* The outter loop controller is set to 2 because there should not be more than two
* directional reads, forward and reverse.
*/
for(int read=0; read<2; read++) {
int loopController, setStart; //control loops and arrays
int fileController=0; // resets to 0 so files are copied in correct array
//set conditions for the loop
if(read==0){
setStart=0;
loopController=indexStartOfRead2;
}
else{
setStart=indexStartOfRead2;
loopController=numFastqFiles;
}
for(fileNum=setStart; fileNum<loopController; fileNum++) {
//following block could be set as separate private method
File outputFile = new File(outputDir+File.separator+countFileNames[fileNum]);
if(outputFile.isFile()){
System.out.println(
"An output file "+countFileNames[fileNum]+"\n"+
" already exists in the output directory for file "+fastqFiles[fileNum]+". Skipping.");
continue;
}
System.out.println("Reading FASTQ file: "+fastqFiles[fileNum]);//print
filenameField[read][fileNum]=fastqFiles[fileNum].getName().split("_");
System.arraycopy(filenameField[read][fileNum], 0, fileReadInfo[read][fileController], 0, filenameField[read][fileNum].length);
fileController++;
}
}
fileNum=0;
//DEBUG print all array contents
for(int left=0;left<2;left++){
for(int mid=0;mid<indexStartOfRead2;mid++){
for(int right=0;right<5;right++){
System.out.println("fileReadInfo FOR ["+left+"]"+"["+mid+"]"+"["+right+"]"+"IS: "+fileReadInfo[left][mid][right]); //DEBUG
}
}
}
//handle keyfiles and enzymes
//2 arrays for manually inputing multiple enzymes and keys for testing
System.out.println("OLD Key file is:"+ keyFileS);
System.out.println("OLD enzyme is:"+ enzyme);
//String[] hcEnzyme={"PstI","MspI"};
String[] hcEnzyme={"PstI-MspI","MspI-PstI"};
String[] hcKeyFiles={"GBS.key","GBS2.key"};
/*
if(fileReadInfo[0][b][0].contains("1")){
keyFileS=hcKeyFiles[0];
enzyme=hcEnzyme[0];
System.out.println("NEW Key file is:" + keyFileS);
System.out.println("NEW enzyme is:"+ enzyme);
}
else{
keyFileS=hcKeyFiles[1];
enzyme=hcEnzyme[1];
System.out.println("NEW Key file is:"+ keyFileS);
System.out.println("NEW enzyme is:"+ enzyme);}
*/
TagCountMutable [] theTC=new TagCountMutable [2];
/*
* Reads the key file and store the expected barcodes for a lane.
* Set to a length of 2 to hold up to two key files' worth of information.
* The convention will be that the forward read is [0] and the reverse
* read is[1]
*/
ParseBarcodeRead [] thePBR = new ParseBarcodeRead [2];
// String[][] taxaNames=new String[2][];
/*
* Need to adjust this loop to read matching pairs simultaneously
*/
for(int b=0;b<indexStartOfRead2;b++){
if(fileReadInfo[0][b].length==5) {
thePBR[0]=new ParseBarcodeRead(
hcKeyFiles[0], hcEnzyme[0], fileReadInfo[0][b][1], fileReadInfo[0][b][3]);
}
else {
System.out.println("Error in parsing file name:");
System.out.println(" The filename does not contain a 5 underscore-delimited value.");
System.out.println(" Expect: code_flowcell_s_lane_fastq.txt.gz");
System.out.println(" Filename: "+fileReadInfo[0][b]);
continue;
}
if(fileReadInfo[1][b].length==5) {
thePBR[1]=new ParseBarcodeRead(
hcKeyFiles[1], hcEnzyme[1], fileReadInfo[1][b][1], fileReadInfo[1][b][3]);
}
else {
System.out.println("Error in parsing file name:");
System.out.println(" The filename does not contain a 5 underscore-delimited value.");
System.out.println(" Expect: code_flowcell_s_lane_fastq.txt.gz");
System.out.println(" Filename: "+fileReadInfo[1][b]);
continue;
}
System.out.println("\nTotal barcodes found in lane:"+thePBR[0].getBarCodeCount());
if(thePBR[0].getBarCodeCount() == 0){
System.out.println("No barcodes found. Skipping this flowcell lane."); continue;
}
System.out.println("\nTotal barcodes found in lane:"+thePBR[1].getBarCodeCount());
if(thePBR[1].getBarCodeCount() == 0){
System.out.println("No barcodes found. Skipping this flowcell lane."); continue;
}
/* as far as I can tell, this bit of code is not used anywhere downstream.
taxaNames[0]=new String[thePBR[0].getBarCodeCount()];
taxaNames[1]=new String[thePBR[1].getBarCodeCount()];
for (int i = 0; i < taxaNames[0].length; i++) {
taxaNames[0][i]=thePBR[0].getTheBarcodes(i).getTaxaName();
}
for (int i = 0; i < taxaNames[0].length; i++) {
taxaNames[1][i]=thePBR[1].getTheBarcodes(i).getTaxaName();
}
*/
/*
* NEED TO CHANGE allgoodreads TO REFLECT AND REPORT EACH DIRECTION SEPARATELY.
* CAN ADD THEM TOGETHER AT THE END FOR A GRAND TOTAL IN CASE THAT'S USEFUL.
*/
try{
//Read in qseq file as a gzipped text stream if its name ends in ".gz", otherwise read as text
if(fastqFiles[b].getName().endsWith(".gz")){
br1 = new BufferedReader(new InputStreamReader(
new MultiMemberGZIPInputStream(
new FileInputStream(fastqFiles[b]))));
br2 = new BufferedReader(new InputStreamReader(
new MultiMemberGZIPInputStream(
new FileInputStream(fastqFiles[b+indexStartOfRead2]))));
}else{
br1=new BufferedReader(new FileReader(fastqFiles[b]),65536);
br2=new BufferedReader(new FileReader(fastqFiles[b+indexStartOfRead2]),65536);
}
String sequenceF="", sequenceR="", qualityScoreF="", qualityScoreR="";
String tempF, tempR;
try{
theTC[0] = new TagCountMutable(2, maxGoodReads);
theTC[1] = new TagCountMutable(2, maxGoodReads);
}catch(OutOfMemoryError e){
System.out.println(
"Your system doesn't have enough memory to store the number of sequences"+
"you specified. Try using a smaller value for the minimum number of reads."
);
}
int currLine=0;
allReads = 0;
goodBarcodedReads = 0;
ReadBarcodeResult [] rr = new ReadBarcodeResult [2];
while (((tempF = br1.readLine()) != null && (tempR = br2.readLine()) != null)
&& goodBarcodedReads < maxGoodReads) {
currLine++;
try{
//The quality score is every 4th line; the sequence is every 4th line starting from the 2nd.
if((currLine+2)%4==0){
sequenceF = tempF;
sequenceR = tempR;
}else if(currLine%4==0){
qualityScoreF = tempF;
qualityScoreR = tempR;
allReads += 2;
//After quality score is read, decode barcode using the current sequence & quality score
rr[0] = thePBR[0].parseReadIntoTagAndTaxa(sequenceF, qualityScoreF, true, 0);
rr[1] = thePBR[1].parseReadIntoTagAndTaxa(sequenceR, qualityScoreR, true, 0);
if (rr[0] != null && rr[1] !=null){
goodBarcodedReads+=2;
theTC[0].addReadCount(rr[0].getRead(), rr[0].getLength(), 1);
theTC[1].addReadCount(rr[1].getRead(), rr[1].getLength(), 1);
}
else if (rr[0] != null){
goodBarcodedReads++;
theTC[0].addReadCount(rr[0].getRead(), rr[0].getLength(), 1);
}
else if (rr[1] != null){
goodBarcodedReads++;
theTC[1].addReadCount(rr[1].getRead(), rr[1].getLength(), 1);
}
/*
* changed if conditional from 1000000 to 10000000
* Not sure if allgoodreads variable is giving the same information when paired files
* are being processed
*/
if (allReads % 10000000 == 0) {
System.out.println("Total Reads:" + allReads + " Reads with barcode and cut site overhang:" + goodBarcodedReads);
}
}
}catch(NullPointerException e){
System.out.println("Unable to correctly parse the sequence and "
+ "quality score from fastq file. Your fastq file may have been corrupted.");
System.exit(0);
}
}
/*
* Not sure if allgoodreads variable is giving the same information when paired files
* are being processed
*/
System.out.println("Total number of reads in lane=" + allReads);
System.out.println("Total number of good barcoded reads=" + goodBarcodedReads);
System.out.println("Timing process (sorting, collapsing, and writing TagCount to file).");
timePoint1 = System.currentTimeMillis();
theTC[0].collapseCounts();
theTC[1].collapseCounts();
theTC[0].writeTagCountFile(outputDir+File.separator+countFileNames[b], FilePacking.Bit, minCount);
theTC[1].writeTagCountFile(outputDir+File.separator+countFileNames[b+indexStartOfRead2], FilePacking.Bit, minCount);
System.out.println("Process took " + (System.currentTimeMillis() - timePoint1) + " milliseconds.");
br1.close();
br2.close();
//attempting to free memory before looping back and getting OOM error falsely
theTC[0]=null;
theTC[1]=null;
fileNum++;
} catch(Exception e) {
System.out.println("Catch testBasicPipeline c="+goodBarcodedReads+" e="+e);
e.printStackTrace();
System.out.println("Finished reading "+(fileNum+1)+" of "+fastqFiles.length+" sequence files.");
}
}
}
|
diff --git a/src/main/java/com/ontometrics/scraper/extraction/SimpleSourceExtractor.java b/src/main/java/com/ontometrics/scraper/extraction/SimpleSourceExtractor.java
index b58fbdd..40f550a 100644
--- a/src/main/java/com/ontometrics/scraper/extraction/SimpleSourceExtractor.java
+++ b/src/main/java/com/ontometrics/scraper/extraction/SimpleSourceExtractor.java
@@ -1,26 +1,26 @@
package com.ontometrics.scraper.extraction;
import java.io.IOException;
import java.net.URL;
import net.htmlparser.jericho.Source;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleSourceExtractor implements SourceExtractor {
private Logger log = LoggerFactory.getLogger(SimpleSourceExtractor.class);
@Override
public Source getSource(URL url) {
Source source = null;
try {
source = new Source(url);
} catch (IOException e) {
- log.error("Error extracting source", e);
+ log.error("Error extracting source: {}", e.toString());
}
return source;
}
}
| true | true | public Source getSource(URL url) {
Source source = null;
try {
source = new Source(url);
} catch (IOException e) {
log.error("Error extracting source", e);
}
return source;
}
| public Source getSource(URL url) {
Source source = null;
try {
source = new Source(url);
} catch (IOException e) {
log.error("Error extracting source: {}", e.toString());
}
return source;
}
|
diff --git a/src/main/java/com/zotyo/diary/web/DiaryServlet.java b/src/main/java/com/zotyo/diary/web/DiaryServlet.java
index c714ea9..a865bcf 100644
--- a/src/main/java/com/zotyo/diary/web/DiaryServlet.java
+++ b/src/main/java/com/zotyo/diary/web/DiaryServlet.java
@@ -1,261 +1,259 @@
package com.zotyo.diary.web;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.MessageContext;
import org.apache.log4j.Logger;
import com.zotyo.diary.client.Day;
import com.zotyo.diary.client.Event;
import com.zotyo.diary.client.Diary;
import com.zotyo.diary.client.DiaryImplService;
public class DiaryServlet extends HttpServlet {
private static Logger logger = Logger.getLogger(DiaryServlet.class);
private Diary diary;
private DiaryHelper diaryHelper;
private DatatypeFactory df;
private String keyword;
private DiaryCache diaryCache;
public void init() throws ServletException {
try {
InputStream inputStream = ClassLoader.getSystemResourceAsStream("diary.properties");
Properties props = new Properties();
props.load(inputStream);
keyword = props.getProperty("keyword");
URL wsdlURL = new URL(props.getProperty("wsdlURL"));
DiaryImplService diaryService = new DiaryImplService(wsdlURL, new QName("http://ws.diary.zotyo.com/", "DiaryImplService"));
diary = diaryService.getDiaryImplPort();
diaryHelper = new DiaryHelper();
df = DatatypeFactory.newInstance();
diaryCache = DiaryCache.getInstance();
} catch(IOException ioex) {
ioex.printStackTrace();
} catch (DatatypeConfigurationException dce) {
throw new IllegalStateException("Exception while obtaining DatatypeFactory instance", dce);
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String theDayString = request.getParameter("theDay");
String command = request.getParameter("cmd");
if ("addday".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/addday.jsp");
rd.forward(request, response);
return;
}
if ("addevent".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/addevent.jsp");
rd.forward(request, response);
return;
}
if ("allday".equals(command)) {
List<Day> days = new ArrayList<Day>();
String yearString = request.getParameter("year");
String monthString = request.getParameter("months");
if (yearString != null && yearString.length() > 0 && monthString != null && monthString.length() > 0) {
int year = Integer.parseInt(yearString);
int months = Integer.parseInt(monthString);
days = diary.getDaysForAMonth(year, months);
request.setAttribute("year", year);
request.setAttribute("months", months);
}
else {
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(new Date());
days = diary.getDaysForAMonth(theDayCal.get(Calendar.YEAR), theDayCal.get(Calendar.MONTH));
request.setAttribute("year", theDayCal.get(Calendar.YEAR));
request.setAttribute("months", theDayCal.get(Calendar.MONTH));
}
request.setAttribute("alldays", days);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/alldays.jsp");
rd.forward(request, response);
return;
}
if ("latests".equals(command)) {
List<Event> events = diary.getAllEvents();
List<Event> latests = new ArrayList<Event>();
for (int i=0; i<5; i++) {
latests.add(events.get(i));
}
request.setAttribute("latests", latests);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/latests.jsp");
rd.forward(request, response);
return;
}
if ("videos".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/videos.jsp");
rd.forward(request, response);
return;
}
if ("search".equals(command)) {
String searchTerm = request.getParameter("searchTerm");
List<Event> result = diary.searchEvents(searchTerm);
request.setAttribute("result", result);
request.setAttribute("searchTerm", searchTerm);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/result.jsp");
rd.forward(request, response);
return;
}
if ("getDays".equals(command)) {
String key = request.getParameter("key");
List<Integer> days = diaryCache.getEventDays(key, diary);
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < days.size(); i++) {
- sb.append("\"");
sb.append(days.get(i));
- sb.append("\"");
if (i != days.size() - 1) {
sb.append(",");
}
}
sb.append("]");
request.setAttribute("days", sb.toString());
RequestDispatcher rd = getServletContext().getRequestDispatcher("/calendardays.jsp");
rd.forward(request, response);
return;
}
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
if (theDayString != null && theDayString.length() > 0) {
Date theDay = null;
try {
theDay = format.parse(request.getParameter("theDay"));
} catch (ParseException e) {
logger.error(e);
}
if (theDay == null) theDay = new Date();
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(theDay);
Day d = diary.getDay(df.newXMLGregorianCalendar(theDayCal));
if (d != null) {
request.setAttribute("eventsOfTheDay", d.getEventsOfTheDay());
request.setAttribute("descriptionOfTheDay", d.getDescriptionOfTheDay());
} else {
request.setAttribute("eventsOfTheDay", new ArrayList<Event>());
}
request.setAttribute("theDay", theDayString);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/events.jsp");
rd.forward(request, response);
}
else {
Date theDay = new Date();
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(theDay);
Day d = diary.getDay(df.newXMLGregorianCalendar(theDayCal));
if (d != null) {
theDayString = format.format(new Date());
request.setAttribute("theDay", theDayString);
request.setAttribute("eventsOfTheDay", d.getEventsOfTheDay());
request.setAttribute("descriptionOfTheDay", d.getDescriptionOfTheDay());
} else {
request.setAttribute("eventsOfTheDay", new ArrayList<Event>());
}
RequestDispatcher rd = getServletContext().getRequestDispatcher("/diary.jsp");
rd.forward(request, response);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String key = request.getParameter("keyword");
if (!diaryHelper.md5(key).equals(keyword)) {
response.sendRedirect("/diaryweb");
return;
}
String action = request.getParameter("action");
String theDay = request.getParameter("theDay");
String descriptionOfTheDay = request.getParameter("descriptionOfTheDay");
String duration = request.getParameter("duration");
String initialEvent = request.getParameter("initialEvent");
String startDate = request.getParameter("startDate");
if ("add_day".equals(action)) {
if (theDay != null && theDay.length() > 0) {
Day day = new Day();
GregorianCalendar theDayCal = diaryHelper.getDayCal(theDay);
day.setTheDay(df.newXMLGregorianCalendar(theDayCal));
day.setDescriptionOfTheDay(descriptionOfTheDay);
Event event = new Event();
event.setDescription(initialEvent);
event.setDuration(diaryHelper.getDuration(duration));
GregorianCalendar startDateCal = diaryHelper.getStartDateCal(startDate);
event.setStartTime(df.newXMLGregorianCalendar(startDateCal));
day.getEventsOfTheDay().add(event);
//addKeyword(key, ((BindingProvider)diary).getRequestContext());
((BindingProvider)diary).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
Collections.singletonMap("keyword",Collections.singletonList(key)));
diary.addDay(day);
}
} else if ("add_event".equals(action)) {
GregorianCalendar theDayCal = diaryHelper.getDayCal(theDay);
Event event = new Event();
event.setDescription(initialEvent);
event.setDuration(diaryHelper.getDuration(duration));
GregorianCalendar startDateCal = diaryHelper.getStartDateCal(startDate);
event.setStartTime(df.newXMLGregorianCalendar(startDateCal));
//addKeyword(key, ((BindingProvider)diary).getRequestContext());
((BindingProvider)diary).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
Collections.singletonMap("keyword",Collections.singletonList(key)));
diary.addEvent(df.newXMLGregorianCalendar(theDayCal), event);
}
response.sendRedirect("/diaryweb");
}
private void addKeyword(String key, Map<String, Object> requestContext) {
Map<String, List<String>> header = new HashMap<String, List<String>>();
header.put("keyword", Collections.singletonList(key));
requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, header);
}
}
| false | true | public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String theDayString = request.getParameter("theDay");
String command = request.getParameter("cmd");
if ("addday".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/addday.jsp");
rd.forward(request, response);
return;
}
if ("addevent".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/addevent.jsp");
rd.forward(request, response);
return;
}
if ("allday".equals(command)) {
List<Day> days = new ArrayList<Day>();
String yearString = request.getParameter("year");
String monthString = request.getParameter("months");
if (yearString != null && yearString.length() > 0 && monthString != null && monthString.length() > 0) {
int year = Integer.parseInt(yearString);
int months = Integer.parseInt(monthString);
days = diary.getDaysForAMonth(year, months);
request.setAttribute("year", year);
request.setAttribute("months", months);
}
else {
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(new Date());
days = diary.getDaysForAMonth(theDayCal.get(Calendar.YEAR), theDayCal.get(Calendar.MONTH));
request.setAttribute("year", theDayCal.get(Calendar.YEAR));
request.setAttribute("months", theDayCal.get(Calendar.MONTH));
}
request.setAttribute("alldays", days);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/alldays.jsp");
rd.forward(request, response);
return;
}
if ("latests".equals(command)) {
List<Event> events = diary.getAllEvents();
List<Event> latests = new ArrayList<Event>();
for (int i=0; i<5; i++) {
latests.add(events.get(i));
}
request.setAttribute("latests", latests);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/latests.jsp");
rd.forward(request, response);
return;
}
if ("videos".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/videos.jsp");
rd.forward(request, response);
return;
}
if ("search".equals(command)) {
String searchTerm = request.getParameter("searchTerm");
List<Event> result = diary.searchEvents(searchTerm);
request.setAttribute("result", result);
request.setAttribute("searchTerm", searchTerm);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/result.jsp");
rd.forward(request, response);
return;
}
if ("getDays".equals(command)) {
String key = request.getParameter("key");
List<Integer> days = diaryCache.getEventDays(key, diary);
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < days.size(); i++) {
sb.append("\"");
sb.append(days.get(i));
sb.append("\"");
if (i != days.size() - 1) {
sb.append(",");
}
}
sb.append("]");
request.setAttribute("days", sb.toString());
RequestDispatcher rd = getServletContext().getRequestDispatcher("/calendardays.jsp");
rd.forward(request, response);
return;
}
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
if (theDayString != null && theDayString.length() > 0) {
Date theDay = null;
try {
theDay = format.parse(request.getParameter("theDay"));
} catch (ParseException e) {
logger.error(e);
}
if (theDay == null) theDay = new Date();
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(theDay);
Day d = diary.getDay(df.newXMLGregorianCalendar(theDayCal));
if (d != null) {
request.setAttribute("eventsOfTheDay", d.getEventsOfTheDay());
request.setAttribute("descriptionOfTheDay", d.getDescriptionOfTheDay());
} else {
request.setAttribute("eventsOfTheDay", new ArrayList<Event>());
}
request.setAttribute("theDay", theDayString);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/events.jsp");
rd.forward(request, response);
}
else {
Date theDay = new Date();
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(theDay);
Day d = diary.getDay(df.newXMLGregorianCalendar(theDayCal));
if (d != null) {
theDayString = format.format(new Date());
request.setAttribute("theDay", theDayString);
request.setAttribute("eventsOfTheDay", d.getEventsOfTheDay());
request.setAttribute("descriptionOfTheDay", d.getDescriptionOfTheDay());
} else {
request.setAttribute("eventsOfTheDay", new ArrayList<Event>());
}
RequestDispatcher rd = getServletContext().getRequestDispatcher("/diary.jsp");
rd.forward(request, response);
}
}
| public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String theDayString = request.getParameter("theDay");
String command = request.getParameter("cmd");
if ("addday".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/addday.jsp");
rd.forward(request, response);
return;
}
if ("addevent".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/addevent.jsp");
rd.forward(request, response);
return;
}
if ("allday".equals(command)) {
List<Day> days = new ArrayList<Day>();
String yearString = request.getParameter("year");
String monthString = request.getParameter("months");
if (yearString != null && yearString.length() > 0 && monthString != null && monthString.length() > 0) {
int year = Integer.parseInt(yearString);
int months = Integer.parseInt(monthString);
days = diary.getDaysForAMonth(year, months);
request.setAttribute("year", year);
request.setAttribute("months", months);
}
else {
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(new Date());
days = diary.getDaysForAMonth(theDayCal.get(Calendar.YEAR), theDayCal.get(Calendar.MONTH));
request.setAttribute("year", theDayCal.get(Calendar.YEAR));
request.setAttribute("months", theDayCal.get(Calendar.MONTH));
}
request.setAttribute("alldays", days);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/alldays.jsp");
rd.forward(request, response);
return;
}
if ("latests".equals(command)) {
List<Event> events = diary.getAllEvents();
List<Event> latests = new ArrayList<Event>();
for (int i=0; i<5; i++) {
latests.add(events.get(i));
}
request.setAttribute("latests", latests);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/latests.jsp");
rd.forward(request, response);
return;
}
if ("videos".equals(command)) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/videos.jsp");
rd.forward(request, response);
return;
}
if ("search".equals(command)) {
String searchTerm = request.getParameter("searchTerm");
List<Event> result = diary.searchEvents(searchTerm);
request.setAttribute("result", result);
request.setAttribute("searchTerm", searchTerm);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/result.jsp");
rd.forward(request, response);
return;
}
if ("getDays".equals(command)) {
String key = request.getParameter("key");
List<Integer> days = diaryCache.getEventDays(key, diary);
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < days.size(); i++) {
sb.append(days.get(i));
if (i != days.size() - 1) {
sb.append(",");
}
}
sb.append("]");
request.setAttribute("days", sb.toString());
RequestDispatcher rd = getServletContext().getRequestDispatcher("/calendardays.jsp");
rd.forward(request, response);
return;
}
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
if (theDayString != null && theDayString.length() > 0) {
Date theDay = null;
try {
theDay = format.parse(request.getParameter("theDay"));
} catch (ParseException e) {
logger.error(e);
}
if (theDay == null) theDay = new Date();
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(theDay);
Day d = diary.getDay(df.newXMLGregorianCalendar(theDayCal));
if (d != null) {
request.setAttribute("eventsOfTheDay", d.getEventsOfTheDay());
request.setAttribute("descriptionOfTheDay", d.getDescriptionOfTheDay());
} else {
request.setAttribute("eventsOfTheDay", new ArrayList<Event>());
}
request.setAttribute("theDay", theDayString);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/events.jsp");
rd.forward(request, response);
}
else {
Date theDay = new Date();
GregorianCalendar theDayCal = new GregorianCalendar();
theDayCal.setTime(theDay);
Day d = diary.getDay(df.newXMLGregorianCalendar(theDayCal));
if (d != null) {
theDayString = format.format(new Date());
request.setAttribute("theDay", theDayString);
request.setAttribute("eventsOfTheDay", d.getEventsOfTheDay());
request.setAttribute("descriptionOfTheDay", d.getDescriptionOfTheDay());
} else {
request.setAttribute("eventsOfTheDay", new ArrayList<Event>());
}
RequestDispatcher rd = getServletContext().getRequestDispatcher("/diary.jsp");
rd.forward(request, response);
}
}
|
diff --git a/src/confdb/converter/ascii/AsciiConfigurationWriter.java b/src/confdb/converter/ascii/AsciiConfigurationWriter.java
index 41cbfe6c..b1bb586f 100644
--- a/src/confdb/converter/ascii/AsciiConfigurationWriter.java
+++ b/src/confdb/converter/ascii/AsciiConfigurationWriter.java
@@ -1,126 +1,126 @@
package confdb.converter.ascii;
import java.util.Iterator;
import confdb.converter.ConverterEngine;
import confdb.converter.ConverterException;
import confdb.converter.IConfigurationWriter;
import confdb.converter.IEDSourceWriter;
import confdb.converter.IESSourceWriter;
import confdb.converter.IESModuleWriter;
import confdb.converter.IModuleWriter;
import confdb.converter.IParameterWriter;
import confdb.converter.IPathWriter;
import confdb.converter.ISequenceWriter;
import confdb.converter.IServiceWriter;
import confdb.data.Block;
import confdb.data.IConfiguration;
import confdb.data.EDSourceInstance;
import confdb.data.ESSourceInstance;
import confdb.data.ESModuleInstance;
import confdb.data.ModuleInstance;
import confdb.data.Parameter;
import confdb.data.Path;
import confdb.data.Sequence;
import confdb.data.ServiceInstance;
public class AsciiConfigurationWriter implements IConfigurationWriter
{
protected ConverterEngine converterEngine = null;
public String toString( IConfiguration conf, WriteProcess writeProcess ) throws ConverterException
{
String indent = " ";
StringBuffer str = new StringBuffer( 100000 );
String fullName = conf.parentDir().name() + "/" + conf.name() + "/V" + conf.version() ;
str.append( "// " + fullName
+ " (" + conf.releaseTag() + ")" + converterEngine.getNewline() + converterEngine.getNewline() );
if ( writeProcess == WriteProcess.YES )
str.append( "process " + conf.processName() + " = {" + converterEngine.getNewline() );
else
indent = "";
ISequenceWriter sequenceWriter = converterEngine.getSequenceWriter();
for ( int i = 0; i < conf.sequenceCount(); i++ )
{
Sequence sequence = conf.sequence(i);
str.append( sequenceWriter.toString(sequence, converterEngine, indent ) );
}
IPathWriter pathWriter = converterEngine.getPathWriter();
for ( int i = 0; i < conf.pathCount(); i++ )
{
Path path = conf.path(i);
str.append( pathWriter.toString( path, converterEngine, indent ) );
}
IParameterWriter parameterWriter = converterEngine.getParameterWriter();
for ( int i = 0; i < conf.psetCount(); i++ )
{
Parameter pset = conf.pset(i);
str.append( parameterWriter.toString( pset, converterEngine, indent ) );
}
IEDSourceWriter edsourceWriter = converterEngine.getEDSourceWriter();
for ( int i = 0; i < conf.edsourceCount(); i++ )
{
EDSourceInstance edsource = conf.edsource(i);
str.append( edsourceWriter.toString(edsource, converterEngine, indent ) );
}
IESSourceWriter essourceWriter = converterEngine.getESSourceWriter();
for ( int i = 0; i < conf.essourceCount(); i++ )
{
ESSourceInstance essource = conf.essource(i);
str.append( essourceWriter.toString(essource, converterEngine, indent ) );
}
IESModuleWriter esmoduleWriter = converterEngine.getESModuleWriter();
for ( int i = 0; i < conf.esmoduleCount(); i++ )
{
ESModuleInstance esmodule = conf.esmodule(i);
str.append( esmoduleWriter.toString( esmodule, converterEngine, indent ) );
}
IServiceWriter serviceWriter = converterEngine.getServiceWriter();
for ( int i = 0; i < conf.serviceCount(); i++ )
{
ServiceInstance service = conf.service(i);
str.append( serviceWriter.toString( service, converterEngine, indent ) );
}
IModuleWriter moduleWriter = converterEngine.getModuleWriter();
for ( int i = 0; i < conf.moduleCount(); i++ )
{
ModuleInstance module = conf.module(i);
str.append( moduleWriter.toString( module ) );
}
Iterator<Block> blockIterator = conf.blockIterator();
while ( blockIterator.hasNext() )
{
Block block = blockIterator.next();
- str.append( indent + "block " + block.name() + " {\n" );
+ str.append( indent + "block " + block.name() + " = {\n" );
Iterator<Parameter> parameterIterator = block.parameterIterator();
while ( parameterIterator.hasNext() )
{
str.append( parameterWriter.toString( parameterIterator.next(), converterEngine, indent + " " ) );
}
str.append( indent + "}\n" );
}
if ( writeProcess == WriteProcess.YES )
str.append( converterEngine.getConfigurationTrailer() );
return str.toString();
}
public void setConverterEngine( ConverterEngine converterEngine )
{
this.converterEngine = converterEngine;
}
}
| true | true | public String toString( IConfiguration conf, WriteProcess writeProcess ) throws ConverterException
{
String indent = " ";
StringBuffer str = new StringBuffer( 100000 );
String fullName = conf.parentDir().name() + "/" + conf.name() + "/V" + conf.version() ;
str.append( "// " + fullName
+ " (" + conf.releaseTag() + ")" + converterEngine.getNewline() + converterEngine.getNewline() );
if ( writeProcess == WriteProcess.YES )
str.append( "process " + conf.processName() + " = {" + converterEngine.getNewline() );
else
indent = "";
ISequenceWriter sequenceWriter = converterEngine.getSequenceWriter();
for ( int i = 0; i < conf.sequenceCount(); i++ )
{
Sequence sequence = conf.sequence(i);
str.append( sequenceWriter.toString(sequence, converterEngine, indent ) );
}
IPathWriter pathWriter = converterEngine.getPathWriter();
for ( int i = 0; i < conf.pathCount(); i++ )
{
Path path = conf.path(i);
str.append( pathWriter.toString( path, converterEngine, indent ) );
}
IParameterWriter parameterWriter = converterEngine.getParameterWriter();
for ( int i = 0; i < conf.psetCount(); i++ )
{
Parameter pset = conf.pset(i);
str.append( parameterWriter.toString( pset, converterEngine, indent ) );
}
IEDSourceWriter edsourceWriter = converterEngine.getEDSourceWriter();
for ( int i = 0; i < conf.edsourceCount(); i++ )
{
EDSourceInstance edsource = conf.edsource(i);
str.append( edsourceWriter.toString(edsource, converterEngine, indent ) );
}
IESSourceWriter essourceWriter = converterEngine.getESSourceWriter();
for ( int i = 0; i < conf.essourceCount(); i++ )
{
ESSourceInstance essource = conf.essource(i);
str.append( essourceWriter.toString(essource, converterEngine, indent ) );
}
IESModuleWriter esmoduleWriter = converterEngine.getESModuleWriter();
for ( int i = 0; i < conf.esmoduleCount(); i++ )
{
ESModuleInstance esmodule = conf.esmodule(i);
str.append( esmoduleWriter.toString( esmodule, converterEngine, indent ) );
}
IServiceWriter serviceWriter = converterEngine.getServiceWriter();
for ( int i = 0; i < conf.serviceCount(); i++ )
{
ServiceInstance service = conf.service(i);
str.append( serviceWriter.toString( service, converterEngine, indent ) );
}
IModuleWriter moduleWriter = converterEngine.getModuleWriter();
for ( int i = 0; i < conf.moduleCount(); i++ )
{
ModuleInstance module = conf.module(i);
str.append( moduleWriter.toString( module ) );
}
Iterator<Block> blockIterator = conf.blockIterator();
while ( blockIterator.hasNext() )
{
Block block = blockIterator.next();
str.append( indent + "block " + block.name() + " {\n" );
Iterator<Parameter> parameterIterator = block.parameterIterator();
while ( parameterIterator.hasNext() )
{
str.append( parameterWriter.toString( parameterIterator.next(), converterEngine, indent + " " ) );
}
str.append( indent + "}\n" );
}
if ( writeProcess == WriteProcess.YES )
str.append( converterEngine.getConfigurationTrailer() );
return str.toString();
}
| public String toString( IConfiguration conf, WriteProcess writeProcess ) throws ConverterException
{
String indent = " ";
StringBuffer str = new StringBuffer( 100000 );
String fullName = conf.parentDir().name() + "/" + conf.name() + "/V" + conf.version() ;
str.append( "// " + fullName
+ " (" + conf.releaseTag() + ")" + converterEngine.getNewline() + converterEngine.getNewline() );
if ( writeProcess == WriteProcess.YES )
str.append( "process " + conf.processName() + " = {" + converterEngine.getNewline() );
else
indent = "";
ISequenceWriter sequenceWriter = converterEngine.getSequenceWriter();
for ( int i = 0; i < conf.sequenceCount(); i++ )
{
Sequence sequence = conf.sequence(i);
str.append( sequenceWriter.toString(sequence, converterEngine, indent ) );
}
IPathWriter pathWriter = converterEngine.getPathWriter();
for ( int i = 0; i < conf.pathCount(); i++ )
{
Path path = conf.path(i);
str.append( pathWriter.toString( path, converterEngine, indent ) );
}
IParameterWriter parameterWriter = converterEngine.getParameterWriter();
for ( int i = 0; i < conf.psetCount(); i++ )
{
Parameter pset = conf.pset(i);
str.append( parameterWriter.toString( pset, converterEngine, indent ) );
}
IEDSourceWriter edsourceWriter = converterEngine.getEDSourceWriter();
for ( int i = 0; i < conf.edsourceCount(); i++ )
{
EDSourceInstance edsource = conf.edsource(i);
str.append( edsourceWriter.toString(edsource, converterEngine, indent ) );
}
IESSourceWriter essourceWriter = converterEngine.getESSourceWriter();
for ( int i = 0; i < conf.essourceCount(); i++ )
{
ESSourceInstance essource = conf.essource(i);
str.append( essourceWriter.toString(essource, converterEngine, indent ) );
}
IESModuleWriter esmoduleWriter = converterEngine.getESModuleWriter();
for ( int i = 0; i < conf.esmoduleCount(); i++ )
{
ESModuleInstance esmodule = conf.esmodule(i);
str.append( esmoduleWriter.toString( esmodule, converterEngine, indent ) );
}
IServiceWriter serviceWriter = converterEngine.getServiceWriter();
for ( int i = 0; i < conf.serviceCount(); i++ )
{
ServiceInstance service = conf.service(i);
str.append( serviceWriter.toString( service, converterEngine, indent ) );
}
IModuleWriter moduleWriter = converterEngine.getModuleWriter();
for ( int i = 0; i < conf.moduleCount(); i++ )
{
ModuleInstance module = conf.module(i);
str.append( moduleWriter.toString( module ) );
}
Iterator<Block> blockIterator = conf.blockIterator();
while ( blockIterator.hasNext() )
{
Block block = blockIterator.next();
str.append( indent + "block " + block.name() + " = {\n" );
Iterator<Parameter> parameterIterator = block.parameterIterator();
while ( parameterIterator.hasNext() )
{
str.append( parameterWriter.toString( parameterIterator.next(), converterEngine, indent + " " ) );
}
str.append( indent + "}\n" );
}
if ( writeProcess == WriteProcess.YES )
str.append( converterEngine.getConfigurationTrailer() );
return str.toString();
}
|
diff --git a/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java b/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java
index 1c0b488..ca8f00c 100644
--- a/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java
+++ b/Library/src/com/tonicartos/widget/stickygridheaders/StickyGridHeadersGridView.java
@@ -1,975 +1,977 @@
/*
Copyright 2013 Tonic Artos
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.tonicartos.widget.stickygridheaders;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersBaseAdapterWrapper.HeaderFillerView;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersBaseAdapterWrapper.ReferenceView;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.ListAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* GridView that displays items in sections with headers that stick to the top
* of the view.
*
* @author Tonic Artos, Emil Sjölander
*/
public class StickyGridHeadersGridView extends GridView implements
OnScrollListener, OnItemClickListener, OnItemSelectedListener,
OnItemLongClickListener {
private static final int MATCHED_STICKIED_HEADER = -2;
private static final int NO_MATCHED_HEADER = -1;
protected static final int TOUCH_MODE_DONE_WAITING = 2;
protected static final int TOUCH_MODE_DOWN = 0;
protected static final int TOUCH_MODE_FINISHED_LONG_PRESS = -2;
protected static final int TOUCH_MODE_REST = -1;
protected static final int TOUCH_MODE_TAP = 1;
public CheckForHeaderLongPress mPendingCheckForLongPress;
public CheckForHeaderTap mPendingCheckForTap;
private boolean mAreHeadersSticky = true;
private final Rect mClippingRect = new Rect();
private boolean mClippingToPadding;
private boolean mClipToPaddingHasBeenSet;
private int mColumnWidth;
private long mCurrentHeaderId = -1;
private DataSetObserver mDataSetObserver = new DataSetObserver() {
@Override
public void onChanged() {
reset();
}
@Override
public void onInvalidated() {
reset();
}
};
private int mHeaderBottomPosition;
private int mHorizontalSpacing;
private float mMotionY;
/**
* Must be set from the wrapped GridView in the constructor.
*/
private int mNumColumns;
private boolean mNumColumnsSet;
private int mNumMeasuredColumns = 1;
private OnHeaderClickListener mOnHeaderClickListener;
private OnHeaderLongClickListener mOnHeaderLongClickListener;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
private OnItemSelectedListener mOnItemSelectedListener;
private PerformHeaderClick mPerformHeaderClick;
private OnScrollListener mScrollListener;
private int mScrollState = SCROLL_STATE_IDLE;
private View mStickiedHeader;
private Runnable mTouchModeReset;
private int mTouchSlop;
private int mVerticalSpacing;
protected StickyGridHeadersBaseAdapterWrapper mAdapter;
protected boolean mDataChanged;
protected int mMotionHeaderPosition;
protected int mTouchMode;
private boolean mMaskStickyHeaderRegion = true;
public StickyGridHeadersGridView(Context context) {
this(context, null);
}
public StickyGridHeadersGridView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.gridViewStyle);
}
public StickyGridHeadersGridView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
super.setOnScrollListener(this);
setVerticalFadingEdgeEnabled(false);
if (!mNumColumnsSet) {
mNumColumns = AUTO_FIT;
}
ViewConfiguration vc = ViewConfiguration.get(context);
mTouchSlop = vc.getScaledTouchSlop();
}
public boolean areHeadersSticky() {
return mAreHeadersSticky;
}
/**
* Gets the header at an item position. However, the position must be that
* of a HeaderFiller.
*
* @param position Position of HeaderFiller.
* @return Header View wrapped in HeaderFiller or null if no header was
* found.
*/
public View getHeaderAt(int position) {
if (position == MATCHED_STICKIED_HEADER) {
return mStickiedHeader;
}
try {
return (View)getChildAt(position).getTag();
} catch (Exception e) {
}
return null;
}
/**
* Get the currently stickied header.
*
* @return Current stickied header.
*/
public View getStickiedHeader() {
return mStickiedHeader;
}
public boolean getStickyHeaderIsTranscluent() {
return !mMaskStickyHeaderRegion;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mOnItemClickListener.onItemClick(parent, view,
mAdapter.translatePosition(position).mPosition, id);
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
return mOnItemLongClickListener.onItemLongClick(parent, view,
mAdapter.translatePosition(position).mPosition, id);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
mOnItemSelectedListener.onItemSelected(parent, view,
mAdapter.translatePosition(position).mPosition, id);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mOnItemSelectedListener.onNothingSelected(parent);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState)state;
super.onRestoreInstanceState(ss.getSuperState());
mAreHeadersSticky = ss.areHeadersSticky;
requestLayout();
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.areHeadersSticky = mAreHeadersSticky;
return ss;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mScrollListener != null) {
mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
totalItemCount);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
scrollChanged(firstVisibleItem);
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mScrollListener != null) {
mScrollListener.onScrollStateChanged(view, scrollState);
}
mScrollState = scrollState;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForHeaderTap();
}
postDelayed(mPendingCheckForTap,
ViewConfiguration.getTapTimeout());
final int y = (int)ev.getY();
mMotionY = y;
mMotionHeaderPosition = findMotionHeader(y);
if (mMotionHeaderPosition == NO_MATCHED_HEADER
|| mScrollState == SCROLL_STATE_FLING) {
// Don't consume the event and pass it to super because we
// can't handle it yet.
break;
}
mTouchMode = TOUCH_MODE_DOWN;
return true;
case MotionEvent.ACTION_MOVE:
if (mMotionHeaderPosition != NO_MATCHED_HEADER
&& Math.abs(ev.getY() - mMotionY) > mTouchSlop) {
// Detected scroll initiation so cancel touch completion on
// header.
mTouchMode = TOUCH_MODE_REST;
final View header = getHeaderAt(mMotionHeaderPosition);
if (header != null) {
header.setPressed(false);
}
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mPendingCheckForLongPress);
}
mMotionHeaderPosition = NO_MATCHED_HEADER;
}
break;
case MotionEvent.ACTION_UP:
if (mTouchMode == TOUCH_MODE_FINISHED_LONG_PRESS) {
return true;
}
if (mTouchMode == TOUCH_MODE_REST
|| mMotionHeaderPosition == NO_MATCHED_HEADER) {
break;
}
final View header = getHeaderAt(mMotionHeaderPosition);
if (header != null && !header.hasFocusable()) {
if (mTouchMode != TOUCH_MODE_DOWN) {
header.setPressed(false);
}
if (mPerformHeaderClick == null) {
mPerformHeaderClick = new PerformHeaderClick();
}
final PerformHeaderClick performHeaderClick = mPerformHeaderClick;
performHeaderClick.mClickMotionPosition = mMotionHeaderPosition;
performHeaderClick.rememberWindowAttachCount();
if (mTouchMode != TOUCH_MODE_DOWN
|| mTouchMode != TOUCH_MODE_TAP) {
final Handler handler = getHandler();
if (handler != null) {
handler.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ? mPendingCheckForTap
: mPendingCheckForLongPress);
}
if (!mDataChanged) {
// Got here so must be a tap. The long press would
// have trigger on the callback handler. Probably.
mTouchMode = TOUCH_MODE_TAP;
header.setPressed(true);
setPressed(true);
if (mTouchModeReset != null) {
removeCallbacks(mTouchModeReset);
}
mTouchModeReset = new Runnable() {
@Override
public void run() {
mTouchMode = TOUCH_MODE_REST;
header.setPressed(false);
setPressed(false);
if (!mDataChanged) {
performHeaderClick.run();
}
}
};
postDelayed(mTouchModeReset,
ViewConfiguration.getPressedStateDuration());
} else {
mTouchMode = TOUCH_MODE_REST;
}
} else if (!mDataChanged) {
performHeaderClick.run();
}
}
mTouchMode = TOUCH_MODE_REST;
return true;
}
return super.onTouchEvent(ev);
}
public boolean performHeaderClick(View view, long id) {
if (mOnHeaderClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
if (view != null) {
view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
}
mOnHeaderClickListener.onHeaderClick(this, view, id);
return true;
}
return false;
}
public boolean performHeaderLongPress(View view, long id) {
boolean handled = false;
if (mOnHeaderLongClickListener != null) {
handled = mOnHeaderLongClickListener.onHeaderLongClick(this, view,
id);
}
if (handled) {
if (view != null) {
view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
}
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
@Override
public void setAdapter(ListAdapter adapter) {
if (mAdapter != null && mDataSetObserver != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (!mClipToPaddingHasBeenSet) {
mClippingToPadding = true;
}
StickyGridHeadersBaseAdapter baseAdapter;
if (adapter instanceof StickyGridHeadersBaseAdapter) {
baseAdapter = (StickyGridHeadersBaseAdapter)adapter;
} else if (adapter instanceof StickyGridHeadersSimpleAdapter) {
// Wrap up simple adapter to auto-generate the data we need.
baseAdapter = new StickyGridHeadersSimpleAdapterWrapper(
(StickyGridHeadersSimpleAdapter)adapter);
} else {
// Wrap up a list adapter so it is an adapter with zero headers.
baseAdapter = new StickyGridHeadersListAdapterWrapper(adapter);
}
this.mAdapter = new StickyGridHeadersBaseAdapterWrapper(getContext(),
this, baseAdapter);
this.mAdapter.registerDataSetObserver(mDataSetObserver);
reset();
super.setAdapter(this.mAdapter);
}
public void setAreHeadersSticky(boolean useStickyHeaders) {
if (useStickyHeaders != mAreHeadersSticky) {
mAreHeadersSticky = useStickyHeaders;
requestLayout();
}
}
@Override
public void setClipToPadding(boolean clipToPadding) {
super.setClipToPadding(clipToPadding);
mClippingToPadding = clipToPadding;
mClipToPaddingHasBeenSet = true;
}
@Override
public void setColumnWidth(int columnWidth) {
super.setColumnWidth(columnWidth);
mColumnWidth = columnWidth;
}
@Override
public void setHorizontalSpacing(int horizontalSpacing) {
super.setHorizontalSpacing(horizontalSpacing);
mHorizontalSpacing = horizontalSpacing;
}
@Override
public void setNumColumns(int numColumns) {
super.setNumColumns(numColumns);
mNumColumnsSet = true;
this.mNumColumns = numColumns;
if (numColumns != AUTO_FIT && mAdapter != null) {
mAdapter.setNumColumns(numColumns);
}
}
public void setOnHeaderClickListener(OnHeaderClickListener listener) {
mOnHeaderClickListener = listener;
}
public void setOnHeaderLongClickListener(OnHeaderLongClickListener listener) {
if (!isLongClickable()) {
setLongClickable(true);
}
mOnHeaderLongClickListener = listener;
}
@Override
public void setOnItemClickListener(
android.widget.AdapterView.OnItemClickListener listener) {
this.mOnItemClickListener = listener;
super.setOnItemClickListener(this);
}
@Override
public void setOnItemLongClickListener(
android.widget.AdapterView.OnItemLongClickListener listener) {
this.mOnItemLongClickListener = listener;
super.setOnItemLongClickListener(this);
}
@Override
public void setOnItemSelectedListener(
android.widget.AdapterView.OnItemSelectedListener listener) {
this.mOnItemSelectedListener = listener;
super.setOnItemSelectedListener(this);
}
@Override
public void setOnScrollListener(OnScrollListener listener) {
this.mScrollListener = listener;
}
public void setStickyHeaderIsTranscluent(boolean isTranscluent) {
mMaskStickyHeaderRegion = !isTranscluent;
}
@Override
public void setVerticalSpacing(int verticalSpacing) {
super.setVerticalSpacing(verticalSpacing);
mVerticalSpacing = verticalSpacing;
}
private int findMotionHeader(float y) {
if (mStickiedHeader != null && y <= mStickiedHeader.getBottom()) {
return MATCHED_STICKIED_HEADER;
}
int vi = 0;
for (int i = getFirstVisiblePosition(); i <= getLastVisiblePosition();) {
long id = getItemIdAtPosition(i);
if (id == StickyGridHeadersBaseAdapterWrapper.ID_HEADER) {
View headerWrapper = getChildAt(vi);
int bottom = headerWrapper.getBottom();
int top = headerWrapper.getTop();
if (y <= bottom && y >= top) {
return vi;
}
}
i += mNumMeasuredColumns;
vi += mNumMeasuredColumns;
}
return NO_MATCHED_HEADER;
}
private int getHeaderHeight() {
if (mStickiedHeader != null) {
return mStickiedHeader.getMeasuredHeight();
}
return 0;
}
private long headerViewPositionToId(int pos) {
if (pos == MATCHED_STICKIED_HEADER) {
return mCurrentHeaderId;
}
return mAdapter.getHeaderId(getFirstVisiblePosition() + pos);
}
private void measureHeader() {
if (mStickiedHeader == null) {
return;
}
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth()
- getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY);
int heightMeasureSpec = 0;
ViewGroup.LayoutParams params = mStickiedHeader.getLayoutParams();
if (params != null && params.height > 0) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(params.height,
MeasureSpec.EXACTLY);
} else {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
mStickiedHeader.measure(widthMeasureSpec, heightMeasureSpec);
mStickiedHeader.layout(getLeft() + getPaddingLeft(), 0, getRight()
- getPaddingRight(), mStickiedHeader.getMeasuredHeight());
}
private void reset() {
mHeaderBottomPosition = 0;
mStickiedHeader = null;
mCurrentHeaderId = INVALID_ROW_ID;
}
private void scrollChanged(int firstVisibleItem) {
if (mAdapter == null || mAdapter.getCount() == 0 || !mAreHeadersSticky) {
return;
}
ReferenceView firstItem = (ReferenceView)getChildAt(0);
if (firstItem == null) {
return;
}
long newHeaderId;
int selectedHeaderPosition = firstVisibleItem;
int beforeRowPosition = firstVisibleItem - mNumMeasuredColumns;
if (beforeRowPosition < 0) {
beforeRowPosition = firstVisibleItem;
}
int secondRowPosition = firstVisibleItem + mNumMeasuredColumns;
if (secondRowPosition >= mAdapter.getCount()) {
secondRowPosition = firstVisibleItem;
}
if (mVerticalSpacing == 0) {
newHeaderId = mAdapter.getHeaderId(firstVisibleItem);
} else if (mVerticalSpacing < 0) {
newHeaderId = mAdapter.getHeaderId(firstVisibleItem);
View firstSecondRowView = getChildAt(mNumMeasuredColumns);
if (firstSecondRowView.getTop() <= 0) {
newHeaderId = mAdapter.getHeaderId(secondRowPosition);
selectedHeaderPosition = secondRowPosition;
} else {
newHeaderId = mAdapter.getHeaderId(firstVisibleItem);
}
} else {
int margin = getChildAt(0).getTop();
if (0 < margin && margin < mVerticalSpacing) {
newHeaderId = mAdapter.getHeaderId(beforeRowPosition);
selectedHeaderPosition = beforeRowPosition;
} else {
newHeaderId = mAdapter.getHeaderId(firstVisibleItem);
}
}
if (mCurrentHeaderId != newHeaderId) {
mStickiedHeader = mAdapter.getHeaderView(selectedHeaderPosition,
mStickiedHeader, this);
measureHeader();
mCurrentHeaderId = newHeaderId;
}
final int childCount = getChildCount();
if (childCount != 0) {
View viewToWatch = null;
int watchingChildDistance = 99999;
// Find the next header after the stickied one.
for (int i = 0; i < childCount; i += mNumMeasuredColumns) {
ReferenceView child = (ReferenceView)super.getChildAt(i);
int childDistance;
if (mClippingToPadding) {
childDistance = child.getTop() - getPaddingTop();
} else {
childDistance = child.getTop();
}
if (childDistance < 0) {
continue;
}
if (child.getView() instanceof HeaderFillerView
&& childDistance < watchingChildDistance) {
viewToWatch = child;
watchingChildDistance = childDistance;
}
}
int headerHeight = getHeaderHeight();
// Work out where to draw stickied header using synchronised
// scrolling.
if (viewToWatch != null) {
if (firstVisibleItem == 0 && super.getChildAt(0).getTop() > 0
&& !mClippingToPadding) {
mHeaderBottomPosition = 0;
} else {
if (mClippingToPadding) {
mHeaderBottomPosition = Math.min(viewToWatch.getTop(),
headerHeight + getPaddingTop());
mHeaderBottomPosition = mHeaderBottomPosition < getPaddingTop() ? headerHeight
+ getPaddingTop()
: mHeaderBottomPosition;
} else {
mHeaderBottomPosition = Math.min(viewToWatch.getTop(),
headerHeight);
mHeaderBottomPosition = mHeaderBottomPosition < 0 ? headerHeight
: mHeaderBottomPosition;
}
}
} else {
mHeaderBottomPosition = headerHeight;
if (mClippingToPadding) {
mHeaderBottomPosition += getPaddingTop();
}
}
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
scrollChanged(getFirstVisiblePosition());
}
boolean drawStickiedHeader = mStickiedHeader != null
&& mAreHeadersSticky
&& mStickiedHeader.getVisibility() == View.VISIBLE;
int headerHeight = getHeaderHeight();
int top = mHeaderBottomPosition - headerHeight;
// Mask the region where we will draw the header later, but only if we
// will draw a header and masking is requested.
if (drawStickiedHeader && mMaskStickyHeaderRegion) {
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.top = mHeaderBottomPosition;
mClippingRect.bottom = getHeight();
canvas.save();
canvas.clipRect(mClippingRect);
}
// ...and draw the grid view.
super.dispatchDraw(canvas);
// Find headers.
List<Integer> headerPositions = new ArrayList<Integer>();
int vi = 0;
for (int i = getFirstVisiblePosition(); i <= getLastVisiblePosition();) {
long id = getItemIdAtPosition(i);
if (id == StickyGridHeadersBaseAdapterWrapper.ID_HEADER) {
headerPositions.add(vi);
}
i += mNumMeasuredColumns;
vi += mNumMeasuredColumns;
}
// Draw headers in list.
for (int i = 0; i < headerPositions.size(); i++) {
ReferenceView frame = (ReferenceView)getChildAt(headerPositions
.get(i));
View header;
try {
header = (View)frame.getTag();
} catch (Exception e) {
return;
}
boolean headerIsStickied = ((HeaderFillerView)frame.getChildAt(0))
- .getHeaderId() == mCurrentHeaderId && frame.getTop() <= 0;
+ .getHeaderId() == mCurrentHeaderId
+ && frame.getTop() <= 0
+ && mAreHeadersSticky;
if (header.getVisibility() != View.VISIBLE || headerIsStickied) {
continue;
}
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(),
MeasureSpec.EXACTLY - getPaddingLeft() - getPaddingRight());
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
header.measure(widthMeasureSpec, heightMeasureSpec);
header.layout(getLeft() + getPaddingLeft(), 0, getRight()
- getPaddingRight(), frame.getHeight());
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.bottom = frame.getBottom();
mClippingRect.top = frame.getTop();
canvas.save();
canvas.clipRect(mClippingRect);
canvas.translate(getPaddingLeft(), frame.getTop());
header.draw(canvas);
canvas.restore();
}
if (drawStickiedHeader && mMaskStickyHeaderRegion) {
canvas.restore();
} else if (!drawStickiedHeader) {
// Done.
return;
}
// Draw stickied header.
if (mStickiedHeader.getWidth() != getWidth() - getPaddingLeft()
- getPaddingRight()) {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(),
MeasureSpec.EXACTLY - getPaddingLeft() - getPaddingRight());
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
mStickiedHeader.measure(widthMeasureSpec, heightMeasureSpec);
mStickiedHeader.layout(getLeft() + getPaddingLeft(), 0, getRight()
- getPaddingRight(), mStickiedHeader.getHeight());
}
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.bottom = top + headerHeight;
if (mClippingToPadding) {
mClippingRect.top = getPaddingTop();
} else {
mClippingRect.top = 0;
}
canvas.save();
canvas.clipRect(mClippingRect);
canvas.translate(getPaddingLeft(), top);
canvas.saveLayerAlpha(0, 0, canvas.getWidth(), canvas.getHeight(),
(int)(0xff * (float)mHeaderBottomPosition / headerHeight),
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
mStickiedHeader.draw(canvas);
canvas.restore();
canvas.restore();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mNumColumns == AUTO_FIT) {
int numFittedColumns;
if (mColumnWidth > 0) {
int gridWidth = Math.max(MeasureSpec.getSize(widthMeasureSpec)
- getPaddingLeft() - getPaddingRight(), 0);
numFittedColumns = gridWidth / mColumnWidth;
// Calculate measured columns accounting for requested grid
// spacing.
if (numFittedColumns > 0) {
while (numFittedColumns != 1) {
if (numFittedColumns * mColumnWidth
+ (numFittedColumns - 1) * mHorizontalSpacing > gridWidth) {
numFittedColumns--;
} else {
break;
}
}
} else {
// Could not fit any columns in grid width, so default to a
// single column.
numFittedColumns = 1;
}
} else {
// Mimic vanilla GridView behaviour where there is not enough
// information to auto-fit columns.
numFittedColumns = 2;
}
mNumMeasuredColumns = numFittedColumns;
} else {
// There were some number of columns requested so we will try to
// fulfil the request.
mNumMeasuredColumns = mNumColumns;
}
// Update adapter with number of columns.
if (mAdapter != null) {
mAdapter.setNumColumns(mNumMeasuredColumns);
}
measureHeader();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public interface OnHeaderClickListener {
void onHeaderClick(AdapterView<?> parent, View view, long id);
}
public interface OnHeaderLongClickListener {
boolean onHeaderLongClick(AdapterView<?> parent, View view, long id);
}
private class CheckForHeaderLongPress extends WindowRunnable implements
Runnable {
@Override
public void run() {
final View child = getHeaderAt(mMotionHeaderPosition);
if (child != null) {
final long longPressId = headerViewPositionToId(mMotionHeaderPosition);
boolean handled = false;
if (sameWindow() && !mDataChanged) {
handled = performHeaderLongPress(child, longPressId);
}
if (handled) {
mTouchMode = TOUCH_MODE_FINISHED_LONG_PRESS;
setPressed(false);
child.setPressed(false);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
private class PerformHeaderClick extends WindowRunnable implements Runnable {
int mClickMotionPosition;
@Override
public void run() {
// The data has changed since we posted this action to the event
// queue, bail out before bad things happen.
if (mDataChanged)
return;
if (mAdapter != null && mAdapter.getCount() > 0
&& mClickMotionPosition != INVALID_POSITION
&& mClickMotionPosition < mAdapter.getCount()
&& sameWindow()) {
final View view = getHeaderAt(mClickMotionPosition);
// If there is no view then something bad happened, the view
// probably scrolled off the screen, and we should cancel the
// click.
if (view != null) {
performHeaderClick(view,
headerViewPositionToId(mClickMotionPosition));
}
}
}
}
/**
* A base class for Runnables that will check that their view is still
* attached to the original window as when the Runnable was created.
*/
private class WindowRunnable {
private int mOriginalAttachCount;
public void rememberWindowAttachCount() {
mOriginalAttachCount = getWindowAttachCount();
}
public boolean sameWindow() {
return hasWindowFocus()
&& getWindowAttachCount() == mOriginalAttachCount;
}
}
final class CheckForHeaderTap implements Runnable {
@Override
public void run() {
if (mTouchMode == TOUCH_MODE_DOWN) {
mTouchMode = TOUCH_MODE_TAP;
final View header = getHeaderAt(mMotionHeaderPosition);
if (header != null && !header.hasFocusable()) {
if (!mDataChanged) {
header.setPressed(true);
setPressed(true);
refreshDrawableState();
final int longPressTimeout = ViewConfiguration
.getLongPressTimeout();
final boolean longClickable = isLongClickable();
if (longClickable) {
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForHeaderLongPress();
}
mPendingCheckForLongPress
.rememberWindowAttachCount();
postDelayed(mPendingCheckForLongPress,
longPressTimeout);
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
} else {
mTouchMode = TOUCH_MODE_DONE_WAITING;
}
}
}
}
}
/**
* Constructor called from {@link #CREATOR}
*/
static class SavedState extends BaseSavedState {
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
boolean areHeadersSticky;
public SavedState(Parcelable superState) {
super(superState);
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
areHeadersSticky = in.readByte() != 0;
}
@Override
public String toString() {
return "StickyGridHeadersGridView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " areHeadersSticky=" + areHeadersSticky + "}";
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeByte((byte)(areHeadersSticky ? 1 : 0));
}
}
}
| true | true | protected void dispatchDraw(Canvas canvas) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
scrollChanged(getFirstVisiblePosition());
}
boolean drawStickiedHeader = mStickiedHeader != null
&& mAreHeadersSticky
&& mStickiedHeader.getVisibility() == View.VISIBLE;
int headerHeight = getHeaderHeight();
int top = mHeaderBottomPosition - headerHeight;
// Mask the region where we will draw the header later, but only if we
// will draw a header and masking is requested.
if (drawStickiedHeader && mMaskStickyHeaderRegion) {
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.top = mHeaderBottomPosition;
mClippingRect.bottom = getHeight();
canvas.save();
canvas.clipRect(mClippingRect);
}
// ...and draw the grid view.
super.dispatchDraw(canvas);
// Find headers.
List<Integer> headerPositions = new ArrayList<Integer>();
int vi = 0;
for (int i = getFirstVisiblePosition(); i <= getLastVisiblePosition();) {
long id = getItemIdAtPosition(i);
if (id == StickyGridHeadersBaseAdapterWrapper.ID_HEADER) {
headerPositions.add(vi);
}
i += mNumMeasuredColumns;
vi += mNumMeasuredColumns;
}
// Draw headers in list.
for (int i = 0; i < headerPositions.size(); i++) {
ReferenceView frame = (ReferenceView)getChildAt(headerPositions
.get(i));
View header;
try {
header = (View)frame.getTag();
} catch (Exception e) {
return;
}
boolean headerIsStickied = ((HeaderFillerView)frame.getChildAt(0))
.getHeaderId() == mCurrentHeaderId && frame.getTop() <= 0;
if (header.getVisibility() != View.VISIBLE || headerIsStickied) {
continue;
}
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(),
MeasureSpec.EXACTLY - getPaddingLeft() - getPaddingRight());
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
header.measure(widthMeasureSpec, heightMeasureSpec);
header.layout(getLeft() + getPaddingLeft(), 0, getRight()
- getPaddingRight(), frame.getHeight());
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.bottom = frame.getBottom();
mClippingRect.top = frame.getTop();
canvas.save();
canvas.clipRect(mClippingRect);
canvas.translate(getPaddingLeft(), frame.getTop());
header.draw(canvas);
canvas.restore();
}
if (drawStickiedHeader && mMaskStickyHeaderRegion) {
canvas.restore();
} else if (!drawStickiedHeader) {
// Done.
return;
}
// Draw stickied header.
if (mStickiedHeader.getWidth() != getWidth() - getPaddingLeft()
- getPaddingRight()) {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(),
MeasureSpec.EXACTLY - getPaddingLeft() - getPaddingRight());
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
mStickiedHeader.measure(widthMeasureSpec, heightMeasureSpec);
mStickiedHeader.layout(getLeft() + getPaddingLeft(), 0, getRight()
- getPaddingRight(), mStickiedHeader.getHeight());
}
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.bottom = top + headerHeight;
if (mClippingToPadding) {
mClippingRect.top = getPaddingTop();
} else {
mClippingRect.top = 0;
}
canvas.save();
canvas.clipRect(mClippingRect);
canvas.translate(getPaddingLeft(), top);
canvas.saveLayerAlpha(0, 0, canvas.getWidth(), canvas.getHeight(),
(int)(0xff * (float)mHeaderBottomPosition / headerHeight),
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
mStickiedHeader.draw(canvas);
canvas.restore();
canvas.restore();
}
| protected void dispatchDraw(Canvas canvas) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
scrollChanged(getFirstVisiblePosition());
}
boolean drawStickiedHeader = mStickiedHeader != null
&& mAreHeadersSticky
&& mStickiedHeader.getVisibility() == View.VISIBLE;
int headerHeight = getHeaderHeight();
int top = mHeaderBottomPosition - headerHeight;
// Mask the region where we will draw the header later, but only if we
// will draw a header and masking is requested.
if (drawStickiedHeader && mMaskStickyHeaderRegion) {
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.top = mHeaderBottomPosition;
mClippingRect.bottom = getHeight();
canvas.save();
canvas.clipRect(mClippingRect);
}
// ...and draw the grid view.
super.dispatchDraw(canvas);
// Find headers.
List<Integer> headerPositions = new ArrayList<Integer>();
int vi = 0;
for (int i = getFirstVisiblePosition(); i <= getLastVisiblePosition();) {
long id = getItemIdAtPosition(i);
if (id == StickyGridHeadersBaseAdapterWrapper.ID_HEADER) {
headerPositions.add(vi);
}
i += mNumMeasuredColumns;
vi += mNumMeasuredColumns;
}
// Draw headers in list.
for (int i = 0; i < headerPositions.size(); i++) {
ReferenceView frame = (ReferenceView)getChildAt(headerPositions
.get(i));
View header;
try {
header = (View)frame.getTag();
} catch (Exception e) {
return;
}
boolean headerIsStickied = ((HeaderFillerView)frame.getChildAt(0))
.getHeaderId() == mCurrentHeaderId
&& frame.getTop() <= 0
&& mAreHeadersSticky;
if (header.getVisibility() != View.VISIBLE || headerIsStickied) {
continue;
}
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(),
MeasureSpec.EXACTLY - getPaddingLeft() - getPaddingRight());
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
header.measure(widthMeasureSpec, heightMeasureSpec);
header.layout(getLeft() + getPaddingLeft(), 0, getRight()
- getPaddingRight(), frame.getHeight());
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.bottom = frame.getBottom();
mClippingRect.top = frame.getTop();
canvas.save();
canvas.clipRect(mClippingRect);
canvas.translate(getPaddingLeft(), frame.getTop());
header.draw(canvas);
canvas.restore();
}
if (drawStickiedHeader && mMaskStickyHeaderRegion) {
canvas.restore();
} else if (!drawStickiedHeader) {
// Done.
return;
}
// Draw stickied header.
if (mStickiedHeader.getWidth() != getWidth() - getPaddingLeft()
- getPaddingRight()) {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(),
MeasureSpec.EXACTLY - getPaddingLeft() - getPaddingRight());
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
mStickiedHeader.measure(widthMeasureSpec, heightMeasureSpec);
mStickiedHeader.layout(getLeft() + getPaddingLeft(), 0, getRight()
- getPaddingRight(), mStickiedHeader.getHeight());
}
mClippingRect.left = getPaddingLeft();
mClippingRect.right = getWidth() - getPaddingRight();
mClippingRect.bottom = top + headerHeight;
if (mClippingToPadding) {
mClippingRect.top = getPaddingTop();
} else {
mClippingRect.top = 0;
}
canvas.save();
canvas.clipRect(mClippingRect);
canvas.translate(getPaddingLeft(), top);
canvas.saveLayerAlpha(0, 0, canvas.getWidth(), canvas.getHeight(),
(int)(0xff * (float)mHeaderBottomPosition / headerHeight),
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG);
mStickiedHeader.draw(canvas);
canvas.restore();
canvas.restore();
}
|
diff --git a/sandbox/rest/src/main/java/brooklyn/cli/commands/BrooklynCommand.java b/sandbox/rest/src/main/java/brooklyn/cli/commands/BrooklynCommand.java
index 6bd2e9888..cdc711159 100644
--- a/sandbox/rest/src/main/java/brooklyn/cli/commands/BrooklynCommand.java
+++ b/sandbox/rest/src/main/java/brooklyn/cli/commands/BrooklynCommand.java
@@ -1,208 +1,207 @@
package brooklyn.cli.commands;
import brooklyn.rest.api.ApiError;
import com.google.common.base.Objects;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter;
import org.codehaus.jackson.map.ObjectMapper;
import org.iq80.cli.Option;
import org.iq80.cli.OptionType;
import org.iq80.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.org.mozilla.javascript.internal.LazilyLoadedCtor;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ConnectException;
import java.util.concurrent.Callable;
import java.lang.UnsupportedOperationException;
import static com.sun.jersey.api.client.ClientResponse.*;
public abstract class BrooklynCommand implements Callable<Void> {
public static final Logger LOG = LoggerFactory.getLogger(BrooklynCommand.class);
private PrintStream out = System.out;
private PrintStream err = System.err;
private Client httpClient = null; // Jersey REST client
private ObjectMapper jsonParser = null; // Jackson json parser
public static final int DEFAULT_RETRY_PERIOD = 30;
public static final String DEFAULT_ENDPOINT = "http://localhost:8080";
@Option(type = OptionType.GLOBAL,
name = { "--embedded" },
description = "Start a simple embedded local web server")
public boolean embedded = false;
@Option(type = OptionType.GLOBAL,
name = { "--endpoint" },
description = "REST endpoint, default \""+DEFAULT_ENDPOINT+"\"")
public String endpoint = DEFAULT_ENDPOINT;
@Option(type = OptionType.GLOBAL,
name = { "--retry" },
description = "Will retry connection to the endpoint for this time period, default \""+DEFAULT_RETRY_PERIOD+"s\"")
public int retry = DEFAULT_RETRY_PERIOD;
@Option(type = OptionType.GLOBAL,
name = { "--no-retry" },
description = "Won't retry connection")
public boolean noRetry = false;
@Override
public String toString() {
return Objects.toStringHelper(getClass())
.add("embedded", embedded)
.add("endpoint", endpoint)
.add("retry", retry)
.add("no-retry",noRetry)
.toString();
}
/**
* This method should contain the particular behavior for each command
* that extends {@link BrooklynCommand}.
*/
public abstract void run() throws Exception;
/**
* This method contains the common behavior for any {@link BrooklynCommand} and
* also makes a call to run() that contains the command-specific behavior.
*
* @return null
* @throws Exception
*/
@Override
public Void call() throws Exception {
// Additional higher level syntax validation
additionalValidation();
// Embedded web server feature
if(embedded)
throw new UnsupportedOperationException(
"The \"--embedded\" option is not supported yet");
// If --no-retry then set number of retries to 1
if(noRetry)
retry = 1;
// Execute the command-specific code
run();
return null;
}
/**
* Adds some additional validation for the cli arguments.
*
* Git-like-cli doesn't attempt to do this so this is the place
* where some of the additional things that we need can go.
*
* Calling this will throw a {@link ParseException} that will be caught.
*
* @throws ParseException
*/
private void additionalValidation() throws ParseException {
// Make sure that "--retry" and "--no-retry" are mutually exclusive
if(noRetry && retry!=DEFAULT_RETRY_PERIOD)
throw new ParseException("The \"--retry\" and \"--no-retry\" options are mutually exclusive!");
}
/**
* Get an instance of the http client
*
* @return a fully configured retry-aware Jersey client
*/
Client getClient() {
if(httpClient==null) { //client has not been initialized
// Lazily create a Jersey client instance
httpClient = Client.create();
// Add a retry filter that retries the request every second for a given number of attempts
httpClient.addFilter(new ClientFilter() {
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
ClientHandlerException lasterror = null;
int i = 0;
int maxAttempts = retry+1; // "--retry" option affects this
do {
i++;
try {
return getNext().handle(cr);
} catch (ClientHandlerException e) {
lasterror = e;
- if (i < retry) {
-// if(e.getCause() instanceof IOException) {
- LOG.debug("Request failed, attempt "+i+" of "+maxAttempts, e);
- getErr().println("Request failed ("+e.getCause()+"); attempt "+i+" of "+maxAttempts+"...");
+ if (i < maxAttempts) {
+ LOG.debug("Request failed, retry attempt "+i+" of "+retry, e);
+ getErr().println("Request failed ("+e.getCause()+"); retry attempt "+i+" of "+retry+" ...");
try {
Thread.sleep(1000);
} catch(InterruptedException ie) {
Thread.currentThread().interrupt();
throw new ClientHandlerException("Interrupted; aborting request retries", ie);
}
}
}
} while (i < maxAttempts);
throw lasterror;
}
});
// Add a Jersey GZIP filter
httpClient.addFilter(new GZIPContentEncodingFilter(true));
}
return httpClient;
}
ObjectMapper getJsonParser() {
if(jsonParser==null) { //parser has not been initialized
// Lazily create a Jackson JSON parser
jsonParser = new ObjectMapper();
}
return jsonParser;
}
public PrintStream getErr() {
return err;
}
public void setErr(PrintStream err) {
this.err = err;
}
public PrintStream getOut() {
return out;
}
public void setOut(PrintStream out) {
this.out = out;
}
String getErrorMessage(ClientResponse clientResponse) {
String response = clientResponse.getEntity(String.class);
try {
// Try to see if the server responded with an error message from the API
ApiError error = getJsonParser().readValue(response, ApiError.class);
return error.getMessage();
} catch (IOException e) {
// If not, inform the user of the underlying response (e.g. if server threw NPE or whatever)
int statusCode = clientResponse.getStatus();
ClientResponse.Status status = clientResponse.getClientResponseStatus();
String responseText = clientResponse.getEntity(String.class);
return "Server returned "+status+"("+statusCode+"); "+responseText;
}
}
}
| true | true | Client getClient() {
if(httpClient==null) { //client has not been initialized
// Lazily create a Jersey client instance
httpClient = Client.create();
// Add a retry filter that retries the request every second for a given number of attempts
httpClient.addFilter(new ClientFilter() {
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
ClientHandlerException lasterror = null;
int i = 0;
int maxAttempts = retry+1; // "--retry" option affects this
do {
i++;
try {
return getNext().handle(cr);
} catch (ClientHandlerException e) {
lasterror = e;
if (i < retry) {
// if(e.getCause() instanceof IOException) {
LOG.debug("Request failed, attempt "+i+" of "+maxAttempts, e);
getErr().println("Request failed ("+e.getCause()+"); attempt "+i+" of "+maxAttempts+"...");
try {
Thread.sleep(1000);
} catch(InterruptedException ie) {
Thread.currentThread().interrupt();
throw new ClientHandlerException("Interrupted; aborting request retries", ie);
}
}
}
} while (i < maxAttempts);
throw lasterror;
}
});
// Add a Jersey GZIP filter
httpClient.addFilter(new GZIPContentEncodingFilter(true));
}
return httpClient;
}
| Client getClient() {
if(httpClient==null) { //client has not been initialized
// Lazily create a Jersey client instance
httpClient = Client.create();
// Add a retry filter that retries the request every second for a given number of attempts
httpClient.addFilter(new ClientFilter() {
@Override
public ClientResponse handle(ClientRequest cr) throws ClientHandlerException {
ClientHandlerException lasterror = null;
int i = 0;
int maxAttempts = retry+1; // "--retry" option affects this
do {
i++;
try {
return getNext().handle(cr);
} catch (ClientHandlerException e) {
lasterror = e;
if (i < maxAttempts) {
LOG.debug("Request failed, retry attempt "+i+" of "+retry, e);
getErr().println("Request failed ("+e.getCause()+"); retry attempt "+i+" of "+retry+" ...");
try {
Thread.sleep(1000);
} catch(InterruptedException ie) {
Thread.currentThread().interrupt();
throw new ClientHandlerException("Interrupted; aborting request retries", ie);
}
}
}
} while (i < maxAttempts);
throw lasterror;
}
});
// Add a Jersey GZIP filter
httpClient.addFilter(new GZIPContentEncodingFilter(true));
}
return httpClient;
}
|
diff --git a/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java b/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java
index 78916f2b..f45bc96d 100755
--- a/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java
+++ b/src/org/geworkbench/bison/datastructure/bioobjects/markers/annotationparser/AnnotationParser.java
@@ -1,718 +1,717 @@
package org.geworkbench.bison.datastructure.bioobjects.markers.annotationparser;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.DSDataSet;
import org.geworkbench.bison.datastructure.biocollections.microarrays.CSMicroarraySet;
import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet;
import org.geworkbench.bison.datastructure.bioobjects.DSBioObject;
import org.geworkbench.bison.datastructure.bioobjects.markers.DSGeneMarker;
import org.geworkbench.bison.datastructure.bioobjects.microarray.DSMicroarray;
import org.geworkbench.bison.datastructure.complex.panels.DSItemList;
import org.geworkbench.engine.preferences.PreferencesManager;
import org.geworkbench.engine.properties.PropertiesManager;
import com.Ostermiller.util.CSVParser;
import com.Ostermiller.util.LabeledCSVParser;
import com.jgoodies.forms.builder.ButtonBarBuilder;
/**
*
* Description:This Class is for retrieving probe annotation information from
* default annotation files provided by Affymetrix.
*
* @author Xuegong Wang
* @author manjunath at genomecenter dot columbia dot edu
* @version $Id$
*/
public class AnnotationParser implements Serializable {
private static final long serialVersionUID = -117234619759135916L;
static Log log = LogFactory.getLog(AnnotationParser.class);
public static final String GENE_ONTOLOGY_BIOLOGICAL_PROCESS = "Gene Ontology Biological Process";
public static final String GENE_ONTOLOGY_CELLULAR_COMPONENT = "Gene Ontology Cellular Component";
public static final String GENE_ONTOLOGY_MOLECULAR_FUNCTION = "Gene Ontology Molecular Function";
public static final String GENE_SYMBOL = "Gene Symbol";
public static final String PROBE_SET_ID = "Probe Set ID";
public static final String MAIN_DELIMITER = "///";
// field names
public static final String DESCRIPTION = "Gene Title"; // (full name)
public static final String ABREV = GENE_SYMBOL; // title(short name)
public static final String PATHWAY = "Pathway"; // pathway
public static final String GOTERM = GENE_ONTOLOGY_BIOLOGICAL_PROCESS; // Goterms
public static final String UNIGENE = "UniGene ID"; // Unigene
public static final String UNIGENE_CLUSTER = "Archival UniGene Cluster";
public static final String LOCUSLINK = "Entrez Gene"; // LocusLink
public static final String SWISSPROT = "SwissProt"; // swissprot
public static final String REFSEQ = "RefSeq Transcript ID"; // RefSeq
public static final String TRANSCRIPT = "Transcript Assignments";
public static final String SCIENTIFIC_NAME = "Species Scientific Name";
public static final String GENOME_VERSION = "Genome Version";
public static final String ALIGNMENT = "Alignments";
// columns read into geWorkbench
// probe id must be first column read in, and the rest of the columns must
// follow the same order
// as the columns in the annotation file.
private static final String[] labels = {
PROBE_SET_ID // probe id must be the first item in this list
, SCIENTIFIC_NAME, UNIGENE_CLUSTER, UNIGENE, GENOME_VERSION,
ALIGNMENT, DESCRIPTION, GENE_SYMBOL, LOCUSLINK, SWISSPROT, REFSEQ,
GENE_ONTOLOGY_BIOLOGICAL_PROCESS, GENE_ONTOLOGY_CELLULAR_COMPONENT,
GENE_ONTOLOGY_MOLECULAR_FUNCTION, PATHWAY, TRANSCRIPT };
// TODO all the DSDataSets handled in this class should be DSMicroarraySet
// FIELDS
private static DSDataSet<? extends DSBioObject> currentDataSet = null;
private static Map<DSDataSet<? extends DSBioObject>, String> datasetToChipTypes = new HashMap<DSDataSet<? extends DSBioObject>, String>();
private static Map<String, MarkerAnnotation> chipTypeToAnnotation = new TreeMap<String, MarkerAnnotation>();
// END FIELDS
/* The reason that we need APSerializable is that the status fields are designed as static. */
public static APSerializable getSerializable() {
return new APSerializable(currentDataSet, datasetToChipTypes,
chipTypeToAnnotation);
}
public static void setFromSerializable(APSerializable aps) {
currentDataSet = aps.currentDataSet;
datasetToChipTypes = aps.datasetToChipTypes;
chipTypeToAnnotation = aps.chipTypeToAnnotation;
}
private static final String ANNOT_DIR = "annotDir";
public static DSDataSet<? extends DSBioObject> getCurrentDataSet() {
return currentDataSet;
}
public static void setCurrentDataSet(DSDataSet<DSBioObject> currentDataSet) {
if(!(currentDataSet instanceof CSMicroarraySet)) {
AnnotationParser.currentDataSet = null;
}
AnnotationParser.currentDataSet = currentDataSet;
}
public static String getCurrentChipType() {
if (currentDataSet != null) {
return datasetToChipTypes.get(currentDataSet);
} else {
return null;
}
}
public static String getChipType(DSDataSet<? extends DSBioObject> dataset) {
return datasetToChipTypes.get(dataset);
}
public static void setChipType(DSDataSet<? extends DSBioObject> dataset, String chiptype) {
datasetToChipTypes.put(dataset, chiptype);
currentDataSet = dataset;
}
/* this is used to handle annotation file when the real dataset is chosen after annotation. */
private static CSMicroarraySet<? extends DSBioObject> dummyMicroarraySet = new CSMicroarraySet<DSMicroarray>();
public static String getLastAnnotationFileName () {
return dummyMicroarraySet.getAnnotationFileName();
}
private static boolean setChipType(DSDataSet<? extends DSBioObject> dataset, String chiptype,
File annotationData) {
datasetToChipTypes.put(dataset, chiptype);
currentDataSet = dataset;
if(dataset==null) {
dummyMicroarraySet.setAnnotationFileName(annotationData.getAbsolutePath());
} if(dataset instanceof CSMicroarraySet) {
CSMicroarraySet<?> d = (CSMicroarraySet<?>)dataset;
d.setAnnotationFileName(annotationData.getAbsolutePath());
}
return loadAnnotationData(chiptype, annotationData);
}
private static boolean loadAnnotationData(String chipType, File datafile) {
if (datafile.exists()) { // data file is found
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(datafile);
bis = new BufferedInputStream(fis);
CSVParser cvsParser = new CSVParser(bis);
cvsParser.setCommentStart("#;!");// Skip all comments line.
// XQ. The bug is reported
// by Bernd.
LabeledCSVParser parser = new LabeledCSVParser(cvsParser);
MarkerAnnotation markerAnnotation = new MarkerAnnotation();
boolean ignoreAll = false;
boolean cancelAnnotationFileProcessing = false;
while ((parser.getLine() != null) && !cancelAnnotationFileProcessing) {
String affyId = parser.getValueByLabel(labels[0]);
affyId = affyId.trim();
AnnotationFields fields = new AnnotationFields();
for (int i = 1; i < labels.length; i++) {
String label = labels[i];
String val = parser.getValueByLabel(label);
if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS)
|| label
.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT)
|| label
.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION)) {
// get rid of leading 0's
while (val.startsWith("0") && (val.length() > 0)) {
val = val.substring(1);
}
}
if (label.equals(GENE_SYMBOL))
fields.setGeneSymbol(val);
else if (label.equals(LOCUSLINK))
fields.setLocusLink(val);
else if (label.equals(SWISSPROT))
fields.setSwissProt(val);
else if (label.equals(DESCRIPTION))
fields.setDescription(val);
else if (label.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION))
fields.setMolecularFunction(val);
else if (label.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT))
fields.setCellularComponent(val);
else if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS))
fields.setBiologicalProcess(val);
else if(label.equals(UNIGENE))
fields.setUniGene(val);
else if(label.equals(REFSEQ))
fields.setRefSeq(val);
}
if (markerAnnotation.containsMarker(affyId)) {
if (!ignoreAll){
- String[] options = {"Proceed", "Ignore All", "Cancel",};
+ String[] options = {"Skip duplicate", "Skip all duplicates", "Cancel",};
int code = JOptionPane.showOptionDialog(null,
"Duplicate entry. Probe Set ID=" + affyId + "." + "\n" +
- "How do you want to proceed?" + "\n" +
- "Proceed - will ignore this entry" + "\n" +
- "Ignore All - will ignore all duplicate entries." + "\n" +
+ "Skip duplicate - will ignore this entry" + "\n" +
+ "Skip all duplicates - will ignore all duplicate entries." + "\n" +
"Cancel - will cancel the annotation file processing.",
"Duplicate entry in annotation file", 0, JOptionPane.QUESTION_MESSAGE,
null, options, "Proceed");
if (code == 1) {
ignoreAll = true;
}
if (code == 2) {
cancelAnnotationFileProcessing = true;
}
}
} else {
markerAnnotation.addMarker(affyId, fields);
}
}
if (!cancelAnnotationFileProcessing) {
chipTypeToAnnotation.put(chipType, markerAnnotation);
}
return true;
} catch (Exception e) {
log.error("", e);
return false;
}finally{
try {
fis.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return false;
}
}
public static String getGeneName(String id) {
try {
String chipType = datasetToChipTypes.get(currentDataSet);
return chipTypeToAnnotation.get(chipType).getFields(id).getGeneSymbol();
} catch (Exception e) {
// watkin - removed because it crippled components with repeated
// logging
// log.warn("Problem getting gene name, returning id. (AffyID: " +
// id+")");
return id;
}
}
/**
* This method returns required annotation field for a given affymatrix marker ID .
*
* @param affyid
* affyID as string
* @param fieldID
*
*/
// this method used to depend on chipTypeToAnnotations, which take unnecessary large memory
// the first step is to re-implement this method so it does not use chipTypeToAnnotations
static public String[] getInfo(String affyID, String fieldID) {
try {
String chipType = datasetToChipTypes.get(currentDataSet);
String field = "";
AnnotationFields fields = chipTypeToAnnotation.get(chipType).getFields(affyID);
// individual field to be process separately to eventually get rid of the large map
if(fieldID.equals(ABREV)) { // same as GENE_SYMBOL
field = fields.getGeneSymbol();
} else if(fieldID.equals(LOCUSLINK)) {
field = fields.getLocusLink();
} else if(fieldID.equals(DESCRIPTION)) {
field = fields.getDescription();
} else if(fieldID.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION)) {
field = fields.getMolecularFunction();
} else if(fieldID.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT)) {
field = fields.getCellularComponent();
} else if(fieldID.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS)) {
field = fields.getBiologicalProcess();
} else if(fieldID.equals(UNIGENE)) {
field = fields.getUniGene();
} else if(fieldID.equals(REFSEQ)) {
field = fields.getRefSeq();
} else if(fieldID.equals(SWISSPROT)) {
field = fields.getSwissProt();
} else {
log.error("trying to retreive unsupported field "+fieldID+" from marker annotation. null is returned.");
return null;
}
return field.split(MAIN_DELIMITER);
} catch (Exception e) {
if (affyID != null) {
log
.debug("Error getting info for affyId (" + affyID
+ "):" + e);
}
return null;
}
}
static public String getInfoAsString(String affyID, String fieldID) {
String[] result = getInfo(affyID, fieldID);
String info = " ";
if (result == null) {
return affyID;
}
if (result.length > 0) {
info = result[0];
for (int i = 1; i < result.length; i++) {
info += "/" + result[i];
}
}
return info;
}
public static Set<String> getSwissProtIDs(String markerID) {
String chipType = datasetToChipTypes.get(currentDataSet);
HashSet<String> set = new HashSet<String>();
String[] ids = chipTypeToAnnotation.get(chipType).getFields(markerID).getSwissProt().split("///");
for (String s : ids) {
set.add(s.trim());
}
return set;
}
public static Set<String> getGeneIDs(String markerID) {
String chipType = datasetToChipTypes.get(currentDataSet);
HashSet<String> set = new HashSet<String>();
String[] ids = chipTypeToAnnotation.get(chipType).getFields(markerID).getLocusLink().split("///");
for (String s : ids) {
set.add(s.trim());
}
return set;
}
public static Map<String, List<Integer>> getGeneIdToMarkerIDMapping(
DSMicroarraySet<? extends DSMicroarray> microarraySet) {
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
DSItemList<DSGeneMarker> markers = microarraySet.getMarkers();
int index = 0;
for (DSGeneMarker marker : markers) {
if (marker != null && marker.getLabel() != null) {
try {
Set<String> geneIDs = getGeneIDs(marker.getLabel());
for (String s : geneIDs) {
List<Integer> list = map.get(s);
if(list==null) {
list = new ArrayList<Integer>();
list.add(index);
map.put(s, list);
} else {
list.add(index);
}
}
index++;
} catch (Exception e) {
continue;
}
}
}
return map;
}
public static Set<String> getGeneNames(String markerID) {
String chipType = datasetToChipTypes.get(currentDataSet);
HashSet<String> set = new HashSet<String>();
String[] ids = chipTypeToAnnotation.get(chipType).getFields(markerID).getGeneSymbol().split("///");
for (String s : ids) {
set.add(s.trim());
}
return set;
}
public static String matchChipType(final DSDataSet<? extends DSBioObject> dataset, String id,
boolean askIfNotFound) {
PreferencesManager preferencesManager = PreferencesManager
.getPreferencesManager();
File prefDir = preferencesManager.getPrefDir();
final File annotFile = new File(prefDir, "annotations.prefs");
if (!annotFile.exists()) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
boolean dontShowAgain = showAnnotationsMessage();
if (dontShowAgain) {
try {
annotFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
String chip = "Other";
currentDataSet = dataset;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
userFile = selectUserDefinedAnnotation(dataset);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (userFile != null) {
chip = userFile.getName();
setChipType(dataset, chip, userFile);
}
return chip;
}
private volatile static File userFile = null;
public static boolean showAnnotationsMessage() {
String message = "To process Affymetrix files many geWorkbench components require information from the associated chip annotation files. Annotation files can be downloaded from the Affymetrix web site, <a href='http://www.affymetrix.com/support/technical/byproduct.affx?cat=arrays' target='_blank'>http://www.affymetrix.com/support/technical/byproduct.affx?cat=arrays</a> (due to the Affymetrix license we are precluded from shipping these files with geWorkbench). Place downloaded files to a directory of your choice; when prompted by geWorkbench point to the appropriate annotation file to be associated with the microarray data you are about to load into the application. Your data will load even if you do not associate them with an annotation file; in that case, some geWorkbench components will not be fully functional.<br>\n"
+ "<br>\n"
+ "NOTE: Affymetrix requires users to register in order to download annotation files from its web site. Registration is a one time procedure. The credentials (user id and password) acquired via the registration process can then be used in subsequent interactions with the site.<br>\n"
+ "<br>\n"
+ "Each chip type in the Affymetrix site can have several associated annotation files (with names like \"...Annotations, BLAST\", \"...Annotations, MAGE-ML XML\", etc). Only annotation files named \"...Annotations, CSV\" need to be downloaded (these are the only files that geWorkbench can process).<br>";
final JDialog window = new JDialog((Frame) null,
"Annotations Information");
Container panel = window.getContentPane();
JEditorPane textarea = new JEditorPane("text/html", message);
textarea.setEditable(false);
textarea.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
openURL("http://www.affymetrix.com/support/technical/byproduct.affx?cat=arrays");
}
}
});
// textarea.setLineWrap(true);
// textarea.setWrapStyleWord(true);
panel.add(textarea, BorderLayout.CENTER);
ButtonBarBuilder builder = ButtonBarBuilder.createLeftToRightBuilder();
JCheckBox dontShow = new JCheckBox("Don't show this again");
builder.addFixed(dontShow);
builder.addGlue();
JButton jButton = new JButton("Continue");
builder.addFixed(jButton);
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.dispose();
}
});
panel.add(builder.getPanel(), BorderLayout.SOUTH);
int width = 500;
int height = 450;
window.pack();
window.setSize(width, height);
window
.setLocation(
(Toolkit.getDefaultToolkit().getScreenSize().width - width) / 2,
(Toolkit.getDefaultToolkit().getScreenSize().height - height) / 2);
window.setModal(true);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
return dontShow.isSelected();
}
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class<?>[] { String.class });
openURL.invoke(null, new Object[] { url });
} else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec(
"rundll32 url.dll,FileProtocolHandler " + url);
} else { // assume Unix or Linux
String[] browsers = { "firefox", "opera", "konqueror",
"epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(
new String[] { "which", browsers[count] })
.waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception("Could not find web browser");
else
Runtime.getRuntime().exec(new String[] { browser, url });
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to open browser"
+ ":\n" + e.getLocalizedMessage());
}
}
private static File selectUserDefinedAnnotation(DSDataSet<? extends DSBioObject> dataset) {
PropertiesManager properties = PropertiesManager.getInstance();
String annotationDir = System.getProperty("user.dir"); ;
try {
annotationDir = properties.getProperty(AnnotationParser.class,
ANNOT_DIR, annotationDir);
} catch (IOException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
}
JFileChooser chooser = new JFileChooser(annotationDir);
ExampleFilter filter = new ExampleFilter();
filter.addExtension("csv");
filter.setDescription("CSV files");
chooser.setFileFilter(filter);
chooser.setDialogTitle("Please select the annotation file");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File userAnnotations = chooser.getSelectedFile();
try {
properties.setProperty(AnnotationParser.class, ANNOT_DIR,
userAnnotations.getParent());
} catch (IOException e) {
e.printStackTrace();
}
return userAnnotations;
} else {
return null;
}
}
static private class AnnotationFields implements Serializable {
private static final long serialVersionUID = -3571880185587329070L;
String getMolecularFunction() {
return molecularFunction;
}
void setMolecularFunction(String molecularFunction) {
this.molecularFunction = molecularFunction;
}
String getCellularComponent() {
return cellularComponent;
}
void setCellularComponent(String cellularComponent) {
this.cellularComponent = cellularComponent;
}
String getBiologicalProcess() {
return biologicalProcess;
}
void setBiologicalProcess(String biologicalProcess) {
this.biologicalProcess = biologicalProcess;
}
String getUniGene() {
return uniGene;
}
void setUniGene(String uniGene) {
this.uniGene = uniGene;
}
String getDescription() {
return description;
}
void setDescription(String description) {
this.description = description;
}
String getGeneSymbol() {
return geneSymbol;
}
void setGeneSymbol(String geneSymbol) {
this.geneSymbol = geneSymbol;
}
String getLocusLink() {
return locusLink;
}
void setLocusLink(String locusLink) {
this.locusLink = locusLink;
}
String getSwissProt() {
return swissProt;
}
void setSwissProt(String swissProt) {
this.swissProt = swissProt;
}
public void setRefSeq(String refSeq) {
this.refSeq = refSeq;
}
public String getRefSeq() {
return refSeq;
}
private String molecularFunction, cellularComponent, biologicalProcess;
private String uniGene, description, geneSymbol, locusLink, swissProt;
private String refSeq;
}
static class MarkerAnnotation implements Serializable {
private static final long serialVersionUID = 1350873248604803043L;
private Map<String, AnnotationFields> annotationFields;
MarkerAnnotation() {
annotationFields = new TreeMap<String, AnnotationFields>();
}
void addMarker(String marker, AnnotationFields fields) {
annotationFields.put(marker, fields);
}
boolean containsMarker(String marker) {
return annotationFields.containsKey(marker);
}
AnnotationFields getFields(String marker) {
return annotationFields.get(marker);
}
Set<String> getMarkerSet() {
return annotationFields.keySet();
}
}
public static void cleanUpAnnotatioAfterUnload(DSDataSet<DSBioObject> dataset) {
String annotationName = datasetToChipTypes.get(dataset);
datasetToChipTypes.remove(dataset);
for(DSDataSet<? extends DSBioObject> dset: datasetToChipTypes.keySet() ) {
if(datasetToChipTypes.get(dset).equals(annotationName)) return;
}
// if not returned, then it is not used anymore, clean it up
if(annotationName!=null)
chipTypeToAnnotation.put(annotationName, null);
}
}
| false | true | private static boolean loadAnnotationData(String chipType, File datafile) {
if (datafile.exists()) { // data file is found
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(datafile);
bis = new BufferedInputStream(fis);
CSVParser cvsParser = new CSVParser(bis);
cvsParser.setCommentStart("#;!");// Skip all comments line.
// XQ. The bug is reported
// by Bernd.
LabeledCSVParser parser = new LabeledCSVParser(cvsParser);
MarkerAnnotation markerAnnotation = new MarkerAnnotation();
boolean ignoreAll = false;
boolean cancelAnnotationFileProcessing = false;
while ((parser.getLine() != null) && !cancelAnnotationFileProcessing) {
String affyId = parser.getValueByLabel(labels[0]);
affyId = affyId.trim();
AnnotationFields fields = new AnnotationFields();
for (int i = 1; i < labels.length; i++) {
String label = labels[i];
String val = parser.getValueByLabel(label);
if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS)
|| label
.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT)
|| label
.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION)) {
// get rid of leading 0's
while (val.startsWith("0") && (val.length() > 0)) {
val = val.substring(1);
}
}
if (label.equals(GENE_SYMBOL))
fields.setGeneSymbol(val);
else if (label.equals(LOCUSLINK))
fields.setLocusLink(val);
else if (label.equals(SWISSPROT))
fields.setSwissProt(val);
else if (label.equals(DESCRIPTION))
fields.setDescription(val);
else if (label.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION))
fields.setMolecularFunction(val);
else if (label.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT))
fields.setCellularComponent(val);
else if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS))
fields.setBiologicalProcess(val);
else if(label.equals(UNIGENE))
fields.setUniGene(val);
else if(label.equals(REFSEQ))
fields.setRefSeq(val);
}
if (markerAnnotation.containsMarker(affyId)) {
if (!ignoreAll){
String[] options = {"Proceed", "Ignore All", "Cancel",};
int code = JOptionPane.showOptionDialog(null,
"Duplicate entry. Probe Set ID=" + affyId + "." + "\n" +
"How do you want to proceed?" + "\n" +
"Proceed - will ignore this entry" + "\n" +
"Ignore All - will ignore all duplicate entries." + "\n" +
"Cancel - will cancel the annotation file processing.",
"Duplicate entry in annotation file", 0, JOptionPane.QUESTION_MESSAGE,
null, options, "Proceed");
if (code == 1) {
ignoreAll = true;
}
if (code == 2) {
cancelAnnotationFileProcessing = true;
}
}
} else {
markerAnnotation.addMarker(affyId, fields);
}
}
if (!cancelAnnotationFileProcessing) {
chipTypeToAnnotation.put(chipType, markerAnnotation);
}
return true;
} catch (Exception e) {
log.error("", e);
return false;
}finally{
try {
fis.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return false;
}
}
| private static boolean loadAnnotationData(String chipType, File datafile) {
if (datafile.exists()) { // data file is found
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(datafile);
bis = new BufferedInputStream(fis);
CSVParser cvsParser = new CSVParser(bis);
cvsParser.setCommentStart("#;!");// Skip all comments line.
// XQ. The bug is reported
// by Bernd.
LabeledCSVParser parser = new LabeledCSVParser(cvsParser);
MarkerAnnotation markerAnnotation = new MarkerAnnotation();
boolean ignoreAll = false;
boolean cancelAnnotationFileProcessing = false;
while ((parser.getLine() != null) && !cancelAnnotationFileProcessing) {
String affyId = parser.getValueByLabel(labels[0]);
affyId = affyId.trim();
AnnotationFields fields = new AnnotationFields();
for (int i = 1; i < labels.length; i++) {
String label = labels[i];
String val = parser.getValueByLabel(label);
if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS)
|| label
.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT)
|| label
.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION)) {
// get rid of leading 0's
while (val.startsWith("0") && (val.length() > 0)) {
val = val.substring(1);
}
}
if (label.equals(GENE_SYMBOL))
fields.setGeneSymbol(val);
else if (label.equals(LOCUSLINK))
fields.setLocusLink(val);
else if (label.equals(SWISSPROT))
fields.setSwissProt(val);
else if (label.equals(DESCRIPTION))
fields.setDescription(val);
else if (label.equals(GENE_ONTOLOGY_MOLECULAR_FUNCTION))
fields.setMolecularFunction(val);
else if (label.equals(GENE_ONTOLOGY_CELLULAR_COMPONENT))
fields.setCellularComponent(val);
else if (label.equals(GENE_ONTOLOGY_BIOLOGICAL_PROCESS))
fields.setBiologicalProcess(val);
else if(label.equals(UNIGENE))
fields.setUniGene(val);
else if(label.equals(REFSEQ))
fields.setRefSeq(val);
}
if (markerAnnotation.containsMarker(affyId)) {
if (!ignoreAll){
String[] options = {"Skip duplicate", "Skip all duplicates", "Cancel",};
int code = JOptionPane.showOptionDialog(null,
"Duplicate entry. Probe Set ID=" + affyId + "." + "\n" +
"Skip duplicate - will ignore this entry" + "\n" +
"Skip all duplicates - will ignore all duplicate entries." + "\n" +
"Cancel - will cancel the annotation file processing.",
"Duplicate entry in annotation file", 0, JOptionPane.QUESTION_MESSAGE,
null, options, "Proceed");
if (code == 1) {
ignoreAll = true;
}
if (code == 2) {
cancelAnnotationFileProcessing = true;
}
}
} else {
markerAnnotation.addMarker(affyId, fields);
}
}
if (!cancelAnnotationFileProcessing) {
chipTypeToAnnotation.put(chipType, markerAnnotation);
}
return true;
} catch (Exception e) {
log.error("", e);
return false;
}finally{
try {
fis.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return false;
}
}
|
diff --git a/src/com/mrockey28/bukkit/ItemRepair/Repair.java b/src/com/mrockey28/bukkit/ItemRepair/Repair.java
index b2265d2..03ecbac 100644
--- a/src/com/mrockey28/bukkit/ItemRepair/Repair.java
+++ b/src/com/mrockey28/bukkit/ItemRepair/Repair.java
@@ -1,122 +1,122 @@
package com.mrockey28.bukkit.ItemRepair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.mrockey28.bukkit.ItemRepair.AutoRepairPlugin.operationType;
public class Repair extends AutoRepairSupport{
public static final Logger log = Logger.getLogger("Minecraft");
public Repair(AutoRepairPlugin instance) {
super(instance, getPlayer());
}
public boolean manualRepair(ItemStack tool) {
doRepairOperation(tool, operationType.MANUAL_REPAIR);
return false;
}
public boolean autoRepairTool(ItemStack tool) {
doRepairOperation(tool, operationType.AUTO_REPAIR);
return false;
}
public void repairAll(Player player) {
ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0);
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
for (ItemStack item : player.getInventory().getContents())
{
- if (item == null || item.getType() == Material.AIR)
+ if (item == null || item.getType() == Material.AIR || item.getType() == Material.WOOL)
{
continue;
}
if (item.getDurability() != 0)
{
doRepairOperation(item, operationType.FULL_REPAIR);
if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString()))
{
couldNotRepair.add(item);
}
}
}
for (ItemStack item : player.getInventory().getArmorContents())
{
if (item == null || item.getType() == Material.AIR)
{
continue;
}
if (item.getDurability() != 0)
{
doRepairOperation(item, operationType.FULL_REPAIR);
if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString()))
{
couldNotRepair.add(item);
}
}
}
if (!couldNotRepair.isEmpty())
{
String itemsNotRepaired = "";
for (ItemStack item : couldNotRepair)
{
itemsNotRepaired += (item.getType().toString() + ", ");
}
itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2);
player.sendMessage("�cDid not repair the following items: ");
player.sendMessage("�c" + itemsNotRepaired);
}
}
public void repairArmor(Player player) {
ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0);
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
for (ItemStack item : player.getInventory().getArmorContents())
{
if (item == null || item.getType() == Material.AIR)
{
continue;
}
if (item.getDurability() != 0)
{
doRepairOperation(item, operationType.FULL_REPAIR);
if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString()))
{
couldNotRepair.add(item);
}
}
}
if (!couldNotRepair.isEmpty())
{
String itemsNotRepaired = "";
for (ItemStack item : couldNotRepair)
{
itemsNotRepaired += (item.getType().toString() + ", ");
}
itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2);
player.sendMessage("�cDid not repair the following items: ");
player.sendMessage("�c" + itemsNotRepaired);
}
}
}
| true | true | public void repairAll(Player player) {
ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0);
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
for (ItemStack item : player.getInventory().getContents())
{
if (item == null || item.getType() == Material.AIR)
{
continue;
}
if (item.getDurability() != 0)
{
doRepairOperation(item, operationType.FULL_REPAIR);
if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString()))
{
couldNotRepair.add(item);
}
}
}
for (ItemStack item : player.getInventory().getArmorContents())
{
if (item == null || item.getType() == Material.AIR)
{
continue;
}
if (item.getDurability() != 0)
{
doRepairOperation(item, operationType.FULL_REPAIR);
if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString()))
{
couldNotRepair.add(item);
}
}
}
if (!couldNotRepair.isEmpty())
{
String itemsNotRepaired = "";
for (ItemStack item : couldNotRepair)
{
itemsNotRepaired += (item.getType().toString() + ", ");
}
itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2);
player.sendMessage("�cDid not repair the following items: ");
player.sendMessage("�c" + itemsNotRepaired);
}
}
| public void repairAll(Player player) {
ArrayList<ItemStack> couldNotRepair = new ArrayList<ItemStack> (0);
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
for (ItemStack item : player.getInventory().getContents())
{
if (item == null || item.getType() == Material.AIR || item.getType() == Material.WOOL)
{
continue;
}
if (item.getDurability() != 0)
{
doRepairOperation(item, operationType.FULL_REPAIR);
if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString()))
{
couldNotRepair.add(item);
}
}
}
for (ItemStack item : player.getInventory().getArmorContents())
{
if (item == null || item.getType() == Material.AIR)
{
continue;
}
if (item.getDurability() != 0)
{
doRepairOperation(item, operationType.FULL_REPAIR);
if (item.getDurability() != 0 && durabilities.containsKey(item.getType().toString()))
{
couldNotRepair.add(item);
}
}
}
if (!couldNotRepair.isEmpty())
{
String itemsNotRepaired = "";
for (ItemStack item : couldNotRepair)
{
itemsNotRepaired += (item.getType().toString() + ", ");
}
itemsNotRepaired = itemsNotRepaired.substring(0, itemsNotRepaired.length() - 2);
player.sendMessage("�cDid not repair the following items: ");
player.sendMessage("�c" + itemsNotRepaired);
}
}
|
diff --git a/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/interceptor/ContentTypeInterceptor.java b/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/interceptor/ContentTypeInterceptor.java
index 7df8aad..79fd3ec 100644
--- a/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/interceptor/ContentTypeInterceptor.java
+++ b/spring-batch-admin-resources/src/main/java/org/springframework/batch/admin/web/interceptor/ContentTypeInterceptor.java
@@ -1,122 +1,122 @@
/*
* Copyright 2009-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.admin.web.interceptor;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;
/**
* Interceptor that looks for an extension on the request path and adds it to
* the view name if it matches a list provided. This can be used to do simple
* content negotiation based on request path extensions, as is usual with
* browsers (the view that is finally resolved could have a different content
* type than the original request).
*
* @author Dave Syer
*
*/
public class ContentTypeInterceptor extends HandlerInterceptorAdapter implements BeanFactoryAware {
private Collection<String> extensions = new HashSet<String>();
private BeanFactory beanFactory;
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
/**
* A collection of extensions to append to view names.
*
* @param extensions
* the extensions (e.g. [rss, xml, atom])
*/
public void setExtensions(Collection<String> extensions) {
this.extensions = new LinkedHashSet<String>(extensions);
}
/**
* Compare the extension of the request path (if there is one) with the set
* provided, and if it matches then add the same extension to the view name,
* if it is not already present.
*
* @see HandlerInterceptorAdapter#postHandle(HttpServletRequest,
* HttpServletResponse, Object, ModelAndView)
*/
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView==null) {
return;
}
if (modelAndView == null) {
return;
}
String path = WebUtils.extractFullFilenameFromUrlPath(request
.getPathInfo());
if (!path.contains(".")) {
return;
}
String extension = path.substring(path.indexOf(".") + 1);
if (extensions.contains(extension)) {
if (modelAndView.isReference()) {
String viewName = modelAndView.getViewName();
if (viewName.contains(".")) {
viewName = viewName.substring(0, path.indexOf("."));
}
String newViewName = viewName + "." + extension;
- if (beanFactory.containsBean(newViewName)) {
+ if (beanFactory==null || beanFactory.containsBean(newViewName)) {
// Adding a suffix only makes sense for bean name resolution
modelAndView.setViewName(newViewName);
}
}
}
String scheme = request.getScheme();
StringBuffer url = new StringBuffer(scheme + "://");
url.append(request.getServerName());
int port = request.getServerPort();
if ((scheme.equals("http") && port != 80)
|| (scheme.equals("https") && port != 443)) {
url.append(":" + port);
}
modelAndView.addObject("baseUrl", url.toString());
modelAndView.addObject("currentTime", new Date());
}
}
| true | true | public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView==null) {
return;
}
if (modelAndView == null) {
return;
}
String path = WebUtils.extractFullFilenameFromUrlPath(request
.getPathInfo());
if (!path.contains(".")) {
return;
}
String extension = path.substring(path.indexOf(".") + 1);
if (extensions.contains(extension)) {
if (modelAndView.isReference()) {
String viewName = modelAndView.getViewName();
if (viewName.contains(".")) {
viewName = viewName.substring(0, path.indexOf("."));
}
String newViewName = viewName + "." + extension;
if (beanFactory.containsBean(newViewName)) {
// Adding a suffix only makes sense for bean name resolution
modelAndView.setViewName(newViewName);
}
}
}
String scheme = request.getScheme();
StringBuffer url = new StringBuffer(scheme + "://");
url.append(request.getServerName());
int port = request.getServerPort();
if ((scheme.equals("http") && port != 80)
|| (scheme.equals("https") && port != 443)) {
url.append(":" + port);
}
modelAndView.addObject("baseUrl", url.toString());
modelAndView.addObject("currentTime", new Date());
}
| public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView==null) {
return;
}
if (modelAndView == null) {
return;
}
String path = WebUtils.extractFullFilenameFromUrlPath(request
.getPathInfo());
if (!path.contains(".")) {
return;
}
String extension = path.substring(path.indexOf(".") + 1);
if (extensions.contains(extension)) {
if (modelAndView.isReference()) {
String viewName = modelAndView.getViewName();
if (viewName.contains(".")) {
viewName = viewName.substring(0, path.indexOf("."));
}
String newViewName = viewName + "." + extension;
if (beanFactory==null || beanFactory.containsBean(newViewName)) {
// Adding a suffix only makes sense for bean name resolution
modelAndView.setViewName(newViewName);
}
}
}
String scheme = request.getScheme();
StringBuffer url = new StringBuffer(scheme + "://");
url.append(request.getServerName());
int port = request.getServerPort();
if ((scheme.equals("http") && port != 80)
|| (scheme.equals("https") && port != 443)) {
url.append(":" + port);
}
modelAndView.addObject("baseUrl", url.toString());
modelAndView.addObject("currentTime", new Date());
}
|
diff --git a/net/jnickg/acamedia/strg/Storage.java b/net/jnickg/acamedia/strg/Storage.java
index b3f2c57..6f239e7 100644
--- a/net/jnickg/acamedia/strg/Storage.java
+++ b/net/jnickg/acamedia/strg/Storage.java
@@ -1,282 +1,287 @@
package net.jnickg.acamedia.strg;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.*;
import net.jnickg.acamedia.fil.*;
public abstract class Storage
extends File
{
// For implementation of Serializable interface
private static final long serialVersionUID = 1L;
/* Variable Members */
private Set<Item> contents; // Items held directly inside the storage
private Set<Folder> folders; // All labels must be unique
private Map<String, Set<Item>> uuidMap; // Allows key collisions by storing Items in a Set
private Map<String, Set<Item>> titleMap;
private Map<String, Set<Item>> tagMap;
/* Constructors */
public Storage(File parent, String fldr)
{
// Make the file and
super(parent, fldr);
if(!this.exists()) this.mkdir();
// Initialize guts
contents = new TreeSet<>();
folders = new TreeSet<>();
// Initialize maps
uuidMap = new HashMap<>();
titleMap = new HashMap<>();
tagMap = new HashMap<>();
}
/* General methods */
protected void saveAll(PrintStream out)
{
// Save own-level contents
for(Item i: contents)
{
i.saveFile(out);
}
}
protected void saveAllSubs(PrintStream out)
{
this.saveAll(out);
// invoke save method for each folder
for(Folder f: folders)
{
f.saveAllSubs(out);
}
}
public void autoDetect(PrintStream out)
{
File[] guts = this.listFiles();
for(File f: guts)
{
if(f.isDirectory()) addSubfolder(f.getName());
else if(f.isFile()) addItem(f, out);
}
}
public void autoDetectSubs(PrintStream out)
{
this.autoDetect(out);
for(Folder f: folders)
{
f.autoDetectSubs(out);
}
}
public int compareTo(Storage other)
{
return this.getName().compareTo(other.getName());
}
private void addToSetMap(Map<String, Set<Item>> disMap, Item disValue, String... disKey)
{
for(String k: disKey)
{
if(!(disMap.containsKey(k)))
{
Set<Item> temp = new TreeSet<>();
temp.add(disValue);
disMap.put(k, temp);
}
else
{
Set<Item> temp = disMap.get(k);
temp.add(disValue);
disMap.put(k, temp);
}
}
}
public void printAll(PrintStream out)
{
printAll(out, "");
}
protected void printAll(PrintStream out, String indent)
{
out.println(indent + this.getName() + "\\");
if (this.hasContents())
{
out.println(indent + " [Contents:]");
for(Item i: this.getContents())
out.println(indent + " " + i.getName());
}
if (this.hasSubfolders())
{
out.println(indent + " [Directories:]");
for(Folder f: this.getSubfolders())
{
//out.println(indent + " " + f.toString() + "\\");
f.printAll(out, indent + " ");
}
}
}
/* Contents methods */
//TODO Revamp the contents methods
public Collection<Item> contentsForKeyword(String keyword)
{
// TODO return items in this level only, which fit the kw
return null;
}
public Collection<Item> allContentsForKeyword(String keyword)
{
// TODO return all items in Cabinet which fit the kw
return null;
}
public Collection<Item> contentsForTitle(String title)
{
return titleMap.get(title);
// if(titleMap.containsKey(title)) return titleMap.get(title);
// else return null;
}
public Collection<Item> allContentsForTitle(String title)
{
List<Item> rtn = new ArrayList<>();
// Add all for title on this level
Collection<Item> toadd = contentsForTitle(title);
if (!(toadd==null)) rtn.addAll(toadd);
// If there are deeper levels, add all for those levels
if (this.hasSubfolders())
{
for(Folder f: this.getSubfolders())
{
rtn.addAll(f.allContentsForTitle(title));
}
}
return rtn;
}
public Boolean hasContents()
{
if (contents.isEmpty()) return false;
else return true;
}
public Set<Item> getContents()
{
return contents;
}
public Collection<Item> getAllContents()
{
List<Item> allContents = new ArrayList<>(contents);
if (this.hasSubfolders())
for (Folder f: folders)
{
Collection<Item> subcontents = f.getAllContents();
for(Item i: subcontents)
{
allContents.add(i);
}
}
return allContents;
}
/* Folders methods */
public Boolean hasSubfolders()
{
if (folders.isEmpty()) return false;
else return true;
}
public Collection<Folder> getSubfolders()
{
return folders;
}
public Folder addSubfolder(String lbl)
{
// Create new folder with given properties
Folder nf = new Folder(this, lbl);
// Add new folder to appropriate maps
folders.add(nf);
return nf;
}
/* New Item Methods */
public Item addItem(File f, PrintStream out)
{
out.println("\nAttempting to add new item: " + f.getName());
Item new1;
try
{
String ext = Files.probeContentType(f.toPath());
out.println("filetype of " + f.getName() + "\n\t" + ext);
//TODO replace this with an enum that makes THIS more readable, and
// allows for easy adding of new doc types.
if(ext.equalsIgnoreCase("application/pdf"))
{
- out.println("It's a PDF: Attempting to make a new PDF Item...");
+ out.println("It's a PDF: Attempting to load the new PDF Item...");
new1 = addPdfItem(f, out);
}
+ else if (ext.equalsIgnoreCase("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
+ {
+ out.println("It's a DOCX: If I knew how, I'd load it for you.");
+ new1 = null;
+ }
else
{
out.println("It didn't fit any Items I know of...");
new1 = null;
}
}
catch(IOException e)
{
out.println(e.getMessage());
out.println(e.getStackTrace());
new1 = null;
}
return new1;
}
private Item addPdfItem(File f, PrintStream out)
{
out.println(f.toString());
// Create the basic Text
Item new1 = new PdfItem(f);
// Add to master list(s)
contents.add(new1);
// Add to other maps
addToSetMap(uuidMap, new1, new1.getUUID());
addToSetMap(titleMap, new1, f.getName());
// Return reference to new Text
return new1;
}
}
| false | true | public Item addItem(File f, PrintStream out)
{
out.println("\nAttempting to add new item: " + f.getName());
Item new1;
try
{
String ext = Files.probeContentType(f.toPath());
out.println("filetype of " + f.getName() + "\n\t" + ext);
//TODO replace this with an enum that makes THIS more readable, and
// allows for easy adding of new doc types.
if(ext.equalsIgnoreCase("application/pdf"))
{
out.println("It's a PDF: Attempting to make a new PDF Item...");
new1 = addPdfItem(f, out);
}
else
{
out.println("It didn't fit any Items I know of...");
new1 = null;
}
}
catch(IOException e)
{
out.println(e.getMessage());
out.println(e.getStackTrace());
new1 = null;
}
return new1;
}
| public Item addItem(File f, PrintStream out)
{
out.println("\nAttempting to add new item: " + f.getName());
Item new1;
try
{
String ext = Files.probeContentType(f.toPath());
out.println("filetype of " + f.getName() + "\n\t" + ext);
//TODO replace this with an enum that makes THIS more readable, and
// allows for easy adding of new doc types.
if(ext.equalsIgnoreCase("application/pdf"))
{
out.println("It's a PDF: Attempting to load the new PDF Item...");
new1 = addPdfItem(f, out);
}
else if (ext.equalsIgnoreCase("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
{
out.println("It's a DOCX: If I knew how, I'd load it for you.");
new1 = null;
}
else
{
out.println("It didn't fit any Items I know of...");
new1 = null;
}
}
catch(IOException e)
{
out.println(e.getMessage());
out.println(e.getStackTrace());
new1 = null;
}
return new1;
}
|
diff --git a/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java b/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java
index f7790bfab..138d4c2f4 100644
--- a/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java
+++ b/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java
@@ -1,393 +1,393 @@
/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rahas.impl;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.description.Parameter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.TrustException;
import org.apache.rahas.impl.util.SAMLCallbackHandler;
/**
* Configuration manager for the <code>SAMLTokenIssuer</code>
*
* @see SAMLTokenIssuer
*/
public class SAMLTokenIssuerConfig extends AbstractIssuerConfig {
Log log = LogFactory.getLog(SAMLTokenIssuerConfig.class);
/**
* The QName of the configuration element of the SAMLTokenIssuer
*/
public final static QName SAML_ISSUER_CONFIG = new QName("saml-issuer-config");
/**
* Element name to include the alias of the private key to sign the response or
* the issued token
*/
private final static QName ISSUER_KEY_ALIAS = new QName("issuerKeyAlias");
/**
* Element name to include the password of the private key to sign the
* response or the issued token
*/
private final static QName ISSUER_KEY_PASSWD = new QName("issuerKeyPassword");
/**
* Element to specify the lifetime of the SAMLToken
* Dafaults to 300000 milliseconds (5 mins)
*/
private final static QName TTL = new QName("timeToLive");
/**
* Element to list the trusted services
*/
private final static QName TRUSTED_SERVICES = new QName("trusted-services");
private final static QName KEY_SIZE = new QName("keySize");
private final static QName SERVICE = new QName("service");
private final static QName ALIAS = new QName("alias");
public final static QName USE_SAML_ATTRIBUTE_STATEMENT = new QName("useSAMLAttributeStatement");
public final static QName ISSUER_NAME = new QName("issuerName");
public final static QName SAML_CALLBACK_CLASS = new QName("dataCallbackHandlerClass");
protected String issuerKeyAlias;
protected String issuerKeyPassword;
protected String issuerName;
protected Map trustedServices = new HashMap();
protected String trustStorePropFile;
protected SAMLCallbackHandler callbackHander;
/**
* Create a new configuration with issuer name and crypto information
* @param issuerName Name of the issuer
* @param cryptoProviderClassName WSS4J Crypto impl class name
* @param cryptoProps Configuration properties of crypto impl
*/
public SAMLTokenIssuerConfig(String issuerName, String cryptoProviderClassName, Properties cryptoProps) {
this.issuerName = issuerName;
this.setCryptoProperties(cryptoProviderClassName, cryptoProps);
}
/**
* Create a SAMLTokenIssuer configuration with a config file picked from the
* given location.
* @param configFilePath Path to the config file
* @throws TrustException
*/
public SAMLTokenIssuerConfig(String configFilePath) throws TrustException {
FileInputStream fis;
StAXOMBuilder builder;
try {
fis = new FileInputStream(configFilePath);
builder = new StAXOMBuilder(fis);
} catch (Exception e) {
throw new TrustException("errorLoadingConfigFile",
new String[] { configFilePath });
}
this.load(builder.getDocumentElement());
}
/**
* Create a SAMLTokenIssuer configuration using the give config element
* @param elem Configuration element as an <code>OMElement</code>
* @throws TrustException
*/
public SAMLTokenIssuerConfig(OMElement elem) throws TrustException {
this.load(elem);
}
private void load(OMElement elem) throws TrustException {
OMElement proofKeyElem = elem.getFirstChildWithName(PROOF_KEY_TYPE);
if (proofKeyElem != null) {
this.proofKeyType = proofKeyElem.getText().trim();
}
//The alias of the private key
OMElement userElem = elem.getFirstChildWithName(ISSUER_KEY_ALIAS);
if (userElem != null) {
this.issuerKeyAlias = userElem.getText().trim();
}
if (this.issuerKeyAlias == null || "".equals(this.issuerKeyAlias)) {
throw new TrustException("samlIssuerKeyAliasMissing");
}
OMElement issuerKeyPasswdElem = elem.getFirstChildWithName(ISSUER_KEY_PASSWD);
if (issuerKeyPasswdElem != null) {
this.issuerKeyPassword = issuerKeyPasswdElem.getText().trim();
}
if (this.issuerKeyPassword == null || "".equals(this.issuerKeyPassword)) {
throw new TrustException("samlIssuerKeyPasswdMissing");
}
OMElement issuerNameElem = elem.getFirstChildWithName(ISSUER_NAME);
if (issuerNameElem != null) {
this.issuerName = issuerNameElem.getText().trim();
}
if (this.issuerName == null || "".equals(this.issuerName)) {
throw new TrustException("samlIssuerNameMissing");
}
this.cryptoPropertiesElement = elem.getFirstChildWithName(CRYPTO_PROPERTIES);
if (this.cryptoPropertiesElement != null) {
if ((this.cryptoElement =
this.cryptoPropertiesElement .getFirstChildWithName(CRYPTO)) == null){
// no children. Hence, prop file should have been defined
this.cryptoPropertiesFile = this.cryptoPropertiesElement .getText().trim();
}
// else Props should be defined as children of a crypto element
}
OMElement keyCompElem = elem.getFirstChildWithName(KeyComputation.KEY_COMPUTATION);
- if (keyCompElem != null && keyCompElem.getText() != null && !"".equals(keyCompElem)) {
+ if (keyCompElem != null && keyCompElem.getText() != null && !"".equals(keyCompElem.getText())) {
this.keyComputation = Integer.parseInt(keyCompElem.getText());
}
//time to live
OMElement ttlElem = elem.getFirstChildWithName(TTL);
if (ttlElem != null) {
try {
this.ttl = Long.parseLong(ttlElem.getText().trim());
} catch (NumberFormatException e) {
throw new TrustException("invlidTTL");
}
}
OMElement keySizeElem = elem.getFirstChildWithName(KEY_SIZE);
if (keySizeElem != null) {
try {
this.keySize = Integer.parseInt(keySizeElem.getText().trim());
} catch (NumberFormatException e) {
throw new TrustException("invalidKeysize");
}
}
this.addRequestedAttachedRef = elem
.getFirstChildWithName(ADD_REQUESTED_ATTACHED_REF) != null;
this.addRequestedUnattachedRef = elem
.getFirstChildWithName(ADD_REQUESTED_UNATTACHED_REF) != null;
//Process trusted services
OMElement trustedServices = elem.getFirstChildWithName(TRUSTED_SERVICES);
/*
* If there are trusted services add them to a list
* Only trusts myself to issue tokens to :
* In this case the STS is embedded in the service as well and
* the issued token can only be used with that particular service
* since the response secret is encrypted by the service's public key
*/
if (trustedServices != null) {
//Now process the trusted services
Iterator servicesIter = trustedServices.getChildrenWithName(SERVICE);
while (servicesIter.hasNext()) {
OMElement service = (OMElement) servicesIter.next();
OMAttribute aliasAttr = service.getAttribute(ALIAS);
if (aliasAttr == null) {
//The certificate alias is a must
throw new TrustException("aliasMissingForService",
new String[]{service.getText().trim()});
}
if (this.trustedServices == null) {
this.trustedServices = new HashMap();
}
//Add the trusted service and the alias to the map of services
this.trustedServices.put(service.getText().trim(), aliasAttr.getAttributeValue());
}
//There maybe no trusted services as well, Therefore do not
//throw an exception when there are no trusted in the list at the
//moment
}
OMElement attrElemet = elem.getFirstChildWithName(SAML_CALLBACK_CLASS);
if (attrElemet != null) {
try {
String value = attrElemet.getText();
Class handlerClass = Class.forName(value);
this.callbackHander = (SAMLCallbackHandler)handlerClass.newInstance();
} catch (ClassNotFoundException e) {
log.debug("Error loading class" , e);
throw new TrustException("Error loading class" , e);
} catch (InstantiationException e) {
log.debug("Error instantiating class" , e);
throw new TrustException("Error instantiating class" , e);
} catch (IllegalAccessException e) {
log.debug("Illegal Access" , e);
throw new TrustException("Illegal Access" , e);
}
}
}
/**
* Generate an Axis2 parameter for this configuration
* @return An Axis2 Parameter instance with configuration information
*/
public Parameter getParameter() {
Parameter param = new Parameter();
OMFactory fac = OMAbstractFactory.getOMFactory();
OMElement paramElem = fac.createOMElement("Parameter", null);
paramElem.addAttribute("name", SAML_ISSUER_CONFIG.getLocalPart(), null);
OMElement configElem = fac.createOMElement(SAML_ISSUER_CONFIG, paramElem);
OMElement issuerNameElem = fac.createOMElement(ISSUER_NAME, configElem);
issuerNameElem.setText(this.issuerName);
OMElement issuerKeyAliasElem = fac.createOMElement(ISSUER_KEY_ALIAS, configElem);
issuerKeyAliasElem.setText(this.issuerKeyAlias);
OMElement issuerKeyPasswd = fac.createOMElement(ISSUER_KEY_PASSWD, configElem);
issuerKeyPasswd.setText(this.issuerKeyPassword);
configElem.addChild(this.cryptoPropertiesElement);
OMElement keySizeElem = fac.createOMElement(KEY_SIZE, configElem);
keySizeElem.setText(Integer.toString(this.keySize));
if(this.addRequestedAttachedRef) {
fac.createOMElement(ADD_REQUESTED_ATTACHED_REF, configElem);
}
if(this.addRequestedUnattachedRef) {
fac.createOMElement(ADD_REQUESTED_UNATTACHED_REF, configElem);
}
OMElement keyCompElem = fac.createOMElement(KeyComputation.KEY_COMPUTATION, configElem);
keyCompElem.setText(Integer.toString(this.keyComputation));
OMElement proofKeyTypeElem = fac.createOMElement(PROOF_KEY_TYPE, configElem);
proofKeyTypeElem.setText(this.proofKeyType);
OMElement trustedServicesElem = fac.createOMElement(TRUSTED_SERVICES, configElem);
for (Iterator iterator = this.trustedServices.keySet().iterator(); iterator.hasNext();) {
String service = (String) iterator.next();
OMElement serviceElem = fac.createOMElement(SERVICE, trustedServicesElem);
serviceElem.setText(service);
serviceElem.addAttribute("alias", (String)this.trustedServices.get(service), null);
}
param.setName(SAML_ISSUER_CONFIG.getLocalPart());
param.setParameterElement(paramElem);
param.setValue(paramElem);
param.setParameterType(Parameter.OM_PARAMETER);
return param;
}
public void setIssuerKeyAlias(String issuerKeyAlias) {
this.issuerKeyAlias = issuerKeyAlias;
}
public void setIssuerKeyPassword(String issuerKeyPassword) {
this.issuerKeyPassword = issuerKeyPassword;
}
public void setIssuerName(String issuerName) {
this.issuerName = issuerName;
}
public void setTrustedServices(Map trustedServices) {
this.trustedServices = trustedServices;
}
public void setTrustStorePropFile(String trustStorePropFile) {
this.trustStorePropFile = trustStorePropFile;
}
/**
* Add a new trusted service endpoint address with its certificate
* @param address Service endpoint address
* @param alias certificate alias
*/
public void addTrustedServiceEndpointAddress(String address, String alias) {
this.trustedServices.put(address, alias);
}
/**
* Set crypto information using WSS4J mechanisms
*
* @param providerClassName
* Provider class - an implementation of
* org.apache.ws.security.components.crypto.Crypto
* @param props Configuration properties
*/
public void setCryptoProperties(String providerClassName, Properties props) {
OMFactory fac = OMAbstractFactory.getOMFactory();
this.cryptoPropertiesElement= fac.createOMElement(CRYPTO_PROPERTIES);
OMElement cryptoElem = fac.createOMElement(CRYPTO, this.cryptoPropertiesElement);
cryptoElem.addAttribute(PROVIDER.getLocalPart(), providerClassName, null);
Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String prop = (String) keys.nextElement();
String value = (String)props.get(prop);
OMElement propElem = fac.createOMElement(PROPERTY, cryptoElem);
propElem.setText(value);
propElem.addAttribute("name", prop, null);
}
}
/**
* Return the list of trusted services as a <code>java.util.Map</code>.
* The services addresses are the keys and cert aliases available under
* those keys.
* @return
*/
public Map getTrustedServices() {
return trustedServices;
}
public SAMLCallbackHandler getCallbackHander() {
return callbackHander;
}
public void setCallbackHander(SAMLCallbackHandler callbackHander) {
this.callbackHander = callbackHander;
}
}
| true | true | private void load(OMElement elem) throws TrustException {
OMElement proofKeyElem = elem.getFirstChildWithName(PROOF_KEY_TYPE);
if (proofKeyElem != null) {
this.proofKeyType = proofKeyElem.getText().trim();
}
//The alias of the private key
OMElement userElem = elem.getFirstChildWithName(ISSUER_KEY_ALIAS);
if (userElem != null) {
this.issuerKeyAlias = userElem.getText().trim();
}
if (this.issuerKeyAlias == null || "".equals(this.issuerKeyAlias)) {
throw new TrustException("samlIssuerKeyAliasMissing");
}
OMElement issuerKeyPasswdElem = elem.getFirstChildWithName(ISSUER_KEY_PASSWD);
if (issuerKeyPasswdElem != null) {
this.issuerKeyPassword = issuerKeyPasswdElem.getText().trim();
}
if (this.issuerKeyPassword == null || "".equals(this.issuerKeyPassword)) {
throw new TrustException("samlIssuerKeyPasswdMissing");
}
OMElement issuerNameElem = elem.getFirstChildWithName(ISSUER_NAME);
if (issuerNameElem != null) {
this.issuerName = issuerNameElem.getText().trim();
}
if (this.issuerName == null || "".equals(this.issuerName)) {
throw new TrustException("samlIssuerNameMissing");
}
this.cryptoPropertiesElement = elem.getFirstChildWithName(CRYPTO_PROPERTIES);
if (this.cryptoPropertiesElement != null) {
if ((this.cryptoElement =
this.cryptoPropertiesElement .getFirstChildWithName(CRYPTO)) == null){
// no children. Hence, prop file should have been defined
this.cryptoPropertiesFile = this.cryptoPropertiesElement .getText().trim();
}
// else Props should be defined as children of a crypto element
}
OMElement keyCompElem = elem.getFirstChildWithName(KeyComputation.KEY_COMPUTATION);
if (keyCompElem != null && keyCompElem.getText() != null && !"".equals(keyCompElem)) {
this.keyComputation = Integer.parseInt(keyCompElem.getText());
}
//time to live
OMElement ttlElem = elem.getFirstChildWithName(TTL);
if (ttlElem != null) {
try {
this.ttl = Long.parseLong(ttlElem.getText().trim());
} catch (NumberFormatException e) {
throw new TrustException("invlidTTL");
}
}
OMElement keySizeElem = elem.getFirstChildWithName(KEY_SIZE);
if (keySizeElem != null) {
try {
this.keySize = Integer.parseInt(keySizeElem.getText().trim());
} catch (NumberFormatException e) {
throw new TrustException("invalidKeysize");
}
}
this.addRequestedAttachedRef = elem
.getFirstChildWithName(ADD_REQUESTED_ATTACHED_REF) != null;
this.addRequestedUnattachedRef = elem
.getFirstChildWithName(ADD_REQUESTED_UNATTACHED_REF) != null;
//Process trusted services
OMElement trustedServices = elem.getFirstChildWithName(TRUSTED_SERVICES);
/*
* If there are trusted services add them to a list
* Only trusts myself to issue tokens to :
* In this case the STS is embedded in the service as well and
* the issued token can only be used with that particular service
* since the response secret is encrypted by the service's public key
*/
if (trustedServices != null) {
//Now process the trusted services
Iterator servicesIter = trustedServices.getChildrenWithName(SERVICE);
while (servicesIter.hasNext()) {
OMElement service = (OMElement) servicesIter.next();
OMAttribute aliasAttr = service.getAttribute(ALIAS);
if (aliasAttr == null) {
//The certificate alias is a must
throw new TrustException("aliasMissingForService",
new String[]{service.getText().trim()});
}
if (this.trustedServices == null) {
this.trustedServices = new HashMap();
}
//Add the trusted service and the alias to the map of services
this.trustedServices.put(service.getText().trim(), aliasAttr.getAttributeValue());
}
//There maybe no trusted services as well, Therefore do not
//throw an exception when there are no trusted in the list at the
//moment
}
OMElement attrElemet = elem.getFirstChildWithName(SAML_CALLBACK_CLASS);
if (attrElemet != null) {
try {
String value = attrElemet.getText();
Class handlerClass = Class.forName(value);
this.callbackHander = (SAMLCallbackHandler)handlerClass.newInstance();
} catch (ClassNotFoundException e) {
log.debug("Error loading class" , e);
throw new TrustException("Error loading class" , e);
} catch (InstantiationException e) {
log.debug("Error instantiating class" , e);
throw new TrustException("Error instantiating class" , e);
} catch (IllegalAccessException e) {
log.debug("Illegal Access" , e);
throw new TrustException("Illegal Access" , e);
}
}
}
| private void load(OMElement elem) throws TrustException {
OMElement proofKeyElem = elem.getFirstChildWithName(PROOF_KEY_TYPE);
if (proofKeyElem != null) {
this.proofKeyType = proofKeyElem.getText().trim();
}
//The alias of the private key
OMElement userElem = elem.getFirstChildWithName(ISSUER_KEY_ALIAS);
if (userElem != null) {
this.issuerKeyAlias = userElem.getText().trim();
}
if (this.issuerKeyAlias == null || "".equals(this.issuerKeyAlias)) {
throw new TrustException("samlIssuerKeyAliasMissing");
}
OMElement issuerKeyPasswdElem = elem.getFirstChildWithName(ISSUER_KEY_PASSWD);
if (issuerKeyPasswdElem != null) {
this.issuerKeyPassword = issuerKeyPasswdElem.getText().trim();
}
if (this.issuerKeyPassword == null || "".equals(this.issuerKeyPassword)) {
throw new TrustException("samlIssuerKeyPasswdMissing");
}
OMElement issuerNameElem = elem.getFirstChildWithName(ISSUER_NAME);
if (issuerNameElem != null) {
this.issuerName = issuerNameElem.getText().trim();
}
if (this.issuerName == null || "".equals(this.issuerName)) {
throw new TrustException("samlIssuerNameMissing");
}
this.cryptoPropertiesElement = elem.getFirstChildWithName(CRYPTO_PROPERTIES);
if (this.cryptoPropertiesElement != null) {
if ((this.cryptoElement =
this.cryptoPropertiesElement .getFirstChildWithName(CRYPTO)) == null){
// no children. Hence, prop file should have been defined
this.cryptoPropertiesFile = this.cryptoPropertiesElement .getText().trim();
}
// else Props should be defined as children of a crypto element
}
OMElement keyCompElem = elem.getFirstChildWithName(KeyComputation.KEY_COMPUTATION);
if (keyCompElem != null && keyCompElem.getText() != null && !"".equals(keyCompElem.getText())) {
this.keyComputation = Integer.parseInt(keyCompElem.getText());
}
//time to live
OMElement ttlElem = elem.getFirstChildWithName(TTL);
if (ttlElem != null) {
try {
this.ttl = Long.parseLong(ttlElem.getText().trim());
} catch (NumberFormatException e) {
throw new TrustException("invlidTTL");
}
}
OMElement keySizeElem = elem.getFirstChildWithName(KEY_SIZE);
if (keySizeElem != null) {
try {
this.keySize = Integer.parseInt(keySizeElem.getText().trim());
} catch (NumberFormatException e) {
throw new TrustException("invalidKeysize");
}
}
this.addRequestedAttachedRef = elem
.getFirstChildWithName(ADD_REQUESTED_ATTACHED_REF) != null;
this.addRequestedUnattachedRef = elem
.getFirstChildWithName(ADD_REQUESTED_UNATTACHED_REF) != null;
//Process trusted services
OMElement trustedServices = elem.getFirstChildWithName(TRUSTED_SERVICES);
/*
* If there are trusted services add them to a list
* Only trusts myself to issue tokens to :
* In this case the STS is embedded in the service as well and
* the issued token can only be used with that particular service
* since the response secret is encrypted by the service's public key
*/
if (trustedServices != null) {
//Now process the trusted services
Iterator servicesIter = trustedServices.getChildrenWithName(SERVICE);
while (servicesIter.hasNext()) {
OMElement service = (OMElement) servicesIter.next();
OMAttribute aliasAttr = service.getAttribute(ALIAS);
if (aliasAttr == null) {
//The certificate alias is a must
throw new TrustException("aliasMissingForService",
new String[]{service.getText().trim()});
}
if (this.trustedServices == null) {
this.trustedServices = new HashMap();
}
//Add the trusted service and the alias to the map of services
this.trustedServices.put(service.getText().trim(), aliasAttr.getAttributeValue());
}
//There maybe no trusted services as well, Therefore do not
//throw an exception when there are no trusted in the list at the
//moment
}
OMElement attrElemet = elem.getFirstChildWithName(SAML_CALLBACK_CLASS);
if (attrElemet != null) {
try {
String value = attrElemet.getText();
Class handlerClass = Class.forName(value);
this.callbackHander = (SAMLCallbackHandler)handlerClass.newInstance();
} catch (ClassNotFoundException e) {
log.debug("Error loading class" , e);
throw new TrustException("Error loading class" , e);
} catch (InstantiationException e) {
log.debug("Error instantiating class" , e);
throw new TrustException("Error instantiating class" , e);
} catch (IllegalAccessException e) {
log.debug("Illegal Access" , e);
throw new TrustException("Illegal Access" , e);
}
}
}
|
diff --git a/src/org/joni/Analyser.java b/src/org/joni/Analyser.java
index 2a83d1b..e5c1477 100644
--- a/src/org/joni/Analyser.java
+++ b/src/org/joni/Analyser.java
@@ -1,2093 +1,2093 @@
/*
* 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.joni;
import static org.joni.BitStatus.bsAt;
import static org.joni.BitStatus.bsClear;
import static org.joni.BitStatus.bsOnAt;
import static org.joni.BitStatus.bsOnAtSimple;
import static org.joni.Option.isCaptureGroup;
import static org.joni.Option.isIgnoreCase;
import static org.joni.Option.isMultiline;
import static org.joni.ast.ConsAltNode.newAltNode;
import static org.joni.ast.ConsAltNode.newListNode;
import static org.joni.ast.QuantifierNode.isRepeatInfinite;
import org.joni.ast.AnchorNode;
import org.joni.ast.BackRefNode;
import org.joni.ast.CClassNode;
import org.joni.ast.CTypeNode;
import org.joni.ast.CallNode;
import org.joni.ast.ConsAltNode;
import org.joni.ast.EncloseNode;
import org.joni.ast.Node;
import org.joni.ast.QuantifierNode;
import org.joni.ast.StringNode;
import org.joni.constants.AnchorType;
import org.joni.constants.CharacterType;
import org.joni.constants.EncloseType;
import org.joni.constants.NodeType;
import org.joni.constants.TargetInfo;
import org.joni.exception.SyntaxException;
class Analyser extends Parser {
protected Analyser(ScanEnvironment env, byte[]bytes, int p, int end) {
super(env, bytes, p, end);
}
private Node noNameDisableMap(Node node, int[]map, int[]counter) {
switch (node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
can.setCar(noNameDisableMap(can.car, map, counter));
} while ((can = can.cdr) != null);
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
Node target = qn.target;
Node old = target;
target = noNameDisableMap(target, map, counter);
if (target != old) {
qn.setTarget(target);
if (target.getType() == NodeType.QTFR) qn.reduceNestedQuantifier((QuantifierNode)target);
}
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
if (en.type == EncloseType.MEMORY) {
if (en.isNamedGroup()) {
counter[0]++;
map[en.regNum] = counter[0];
en.regNum = counter[0];
//en.target = noNameDisableMap(en.target, map, counter);
en.setTarget(noNameDisableMap(en.target, map, counter)); // ???
} else {
node = en.target;
en.target = null; // remove first enclose: /(a)(?<b>c)/
node = noNameDisableMap(node, map, counter);
}
} else {
//en.target = noNameDisableMap(en.target, map, counter);
en.setTarget(noNameDisableMap(en.target, map, counter)); // ???
}
break;
default:
break;
} // switch
return node;
}
private void renumberByMap(Node node, int[]map) {
switch (node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
renumberByMap(can.car, map);
} while ((can = can.cdr) != null);
break;
case NodeType.QTFR:
renumberByMap(((QuantifierNode)node).target, map);
break;
case NodeType.ENCLOSE:
renumberByMap(((EncloseNode)node).target, map);
break;
case NodeType.BREF:
((BackRefNode)node).renumber(map);
break;
default:
break;
} // switch
}
protected final void numberedRefCheck(Node node) {
switch (node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
numberedRefCheck(can.car);
} while ((can = can.cdr) != null);
break;
case NodeType.QTFR:
numberedRefCheck(((QuantifierNode)node).target);
break;
case NodeType.ENCLOSE:
numberedRefCheck(((EncloseNode)node).target);
break;
case NodeType.BREF:
BackRefNode br = (BackRefNode)node;
if (!br.isNameRef()) newValueException(ERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED);
break;
default:
break;
} // switch
}
protected final Node disableNoNameGroupCapture(Node root) {
int[]map = new int[env.numMem + 1];
for (int i=1; i<=env.numMem; i++) map[i] = 0;
int[]counter = new int[]{0}; // !!! this should be passed as the recursion goes right ?, move to plain int
root = noNameDisableMap(root, map, counter); // ???
renumberByMap(root, map);
for (int i=1, pos=1; i<=env.numMem; i++) {
if (map[i] > 0) {
env.memNodes[pos] = env.memNodes[i];
pos++;
}
}
int loc = env.captureHistory;
env.captureHistory = bsClear();
for (int i=1; i<=Config.MAX_CAPTURE_HISTORY_GROUP; i++) {
if (bsAt(loc, i)) {
env.captureHistory = bsOnAtSimple(env.captureHistory, map[i]);
}
}
env.numMem = env.numNamed;
regex.numMem = env.numNamed;
regex.renumberNameTable(map);
return root;
}
private void swap(Node a, Node b) {
a.swap(b);
if (root == b) {
root = a;
} else if (root == a) {
root = b;
}
}
// USE_INFINITE_REPEAT_MONOMANIAC_MEM_STATUS_CHECK
private int quantifiersMemoryInfo(Node node) {
int info = 0;
switch(node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
int v = quantifiersMemoryInfo(can.car);
if (v > info) info = v;
} while ((can = can.cdr) != null);
break;
case NodeType.CALL:
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (cn.isRecursion()) {
return TargetInfo.IS_EMPTY_REC; /* tiny version */
} else {
info = quantifiersMemoryInfo(cn.target);
}
break;
} // USE_SUBEXP_CALL
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
if (qn.upper != 0) {
info = quantifiersMemoryInfo(qn.target);
}
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.MEMORY:
return TargetInfo.IS_EMPTY_MEM;
case EncloseType.OPTION:
case EncloseNode.STOP_BACKTRACK:
info = quantifiersMemoryInfo(en.target);
break;
default:
break;
} // inner switch
break;
case NodeType.BREF:
case NodeType.STR:
case NodeType.CTYPE:
case NodeType.CCLASS:
case NodeType.CANY:
case NodeType.ANCHOR:
default:
break;
} // switch
return info;
}
private int getMinMatchLength(Node node) {
int min = 0;
switch (node.getType()) {
case NodeType.BREF:
BackRefNode br = (BackRefNode)node;
if (br.isRecursion()) break;
if (br.back[0] > env.numMem) newValueException(ERR_INVALID_BACKREF);
min = getMinMatchLength(env.memNodes[br.back[0]]);
for (int i=1; i<br.backNum; i++) {
if (br.back[i] > env.numMem) newValueException(ERR_INVALID_BACKREF);
int tmin = getMinMatchLength(env.memNodes[br.back[i]]);
if (min > tmin) min = tmin;
}
break;
case NodeType.CALL:
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (cn.isRecursion()) {
EncloseNode en = (EncloseNode)cn.target;
if (en.isMinFixed()) min = en.minLength;
} else {
min = getMinMatchLength(cn.target);
}
break;
} // USE_SUBEXP_CALL
break;
case NodeType.LIST:
ConsAltNode can = (ConsAltNode)node;
do {
min += getMinMatchLength(can.car);
} while ((can = can.cdr) != null);
break;
case NodeType.ALT:
ConsAltNode y = (ConsAltNode)node;
do {
Node x = y.car;
int tmin = getMinMatchLength(x);
if (y == node) {
min = tmin;
} else if (min > tmin) {
min = tmin;
}
} while ((y = y.cdr) != null);
break;
case NodeType.STR:
min = ((StringNode)node).length();
break;
case NodeType.CTYPE:
min = 1;
break;
case NodeType.CCLASS:
case NodeType.CANY:
min = 1;
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
if (qn.lower > 0) {
min = getMinMatchLength(qn.target);
min = MinMaxLen.distanceMultiply(min, qn.lower);
}
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.MEMORY:
if (Config.USE_SUBEXP_CALL) {
if (en.isMinFixed()) {
min = en.minLength;
} else {
min = getMinMatchLength(en.target);
en.minLength = min;
en.setMinFixed();
}
break;
} // USE_SUBEXP_CALL
break;
case EncloseType.OPTION:
case EncloseType.STOP_BACKTRACK:
min = getMinMatchLength(en.target);
break;
} // inner switch
break;
case NodeType.ANCHOR:
default:
break;
} // switch
return min;
}
private int getMaxMatchLength(Node node) {
int max = 0;
switch (node.getType()) {
case NodeType.LIST:
ConsAltNode ln = (ConsAltNode)node;
do {
int tmax = getMaxMatchLength(ln.car);
max = MinMaxLen.distanceAdd(max, tmax);
} while ((ln = ln.cdr) != null);
break;
case NodeType.ALT:
ConsAltNode an = (ConsAltNode)node;
do {
int tmax = getMaxMatchLength(an.car);
if (max < tmax) max = tmax;
} while ((an = an.cdr) != null);
break;
case NodeType.STR:
max = ((StringNode)node).length();
break;
case NodeType.CTYPE:
max = enc.maxLengthDistance();
break;
case NodeType.CCLASS:
case NodeType.CANY:
max = enc.maxLengthDistance();
break;
case NodeType.BREF:
BackRefNode br = (BackRefNode)node;
if (br.isRecursion()) {
max = MinMaxLen.INFINITE_DISTANCE;
break;
}
for (int i=0; i<br.backNum; i++) {
if (br.back[i] > env.numMem) newValueException(ERR_INVALID_BACKREF);
int tmax = getMaxMatchLength(env.memNodes[br.back[i]]);
if (max < tmax) max = tmax;
}
break;
case NodeType.CALL:
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (!cn.isRecursion()) {
max = getMaxMatchLength(cn.target);
} else {
max = MinMaxLen.INFINITE_DISTANCE;
}
break;
} // USE_SUBEXP_CALL
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
if (qn.upper != 0) {
max = getMaxMatchLength(qn.target);
if (max != 0) {
if (!isRepeatInfinite(qn.upper)) {
max = MinMaxLen.distanceMultiply(max, qn.upper);
} else {
max = MinMaxLen.INFINITE_DISTANCE;
}
}
}
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.MEMORY:
if (Config.USE_SUBEXP_CALL) {
if (en.isMaxFixed()) {
max = en.maxLength;
} else {
max = getMaxMatchLength(en.target);
en.maxLength = max;
en.setMaxFixed();
}
break;
} // USE_SUBEXP_CALL
break;
case EncloseType.OPTION:
case EncloseType.STOP_BACKTRACK:
max = getMaxMatchLength(en.target);
break;
} // inner switch
break;
case NodeType.ANCHOR:
default:
break;
} // switch
return max;
}
private static final int GET_CHAR_LEN_VARLEN = -1;
private static final int GET_CHAR_LEN_TOP_ALT_VARLEN = -2;
protected final int getCharLengthTree(Node node) {
return getCharLengthTree(node, 0);
}
private int getCharLengthTree(Node node, int level) {
level++;
int len = 0;
returnCode = 0;
switch(node.getType()) {
case NodeType.LIST:
ConsAltNode ln = (ConsAltNode)node;
do {
int tlen = getCharLengthTree(ln.car, level);
if (returnCode == 0) len = MinMaxLen.distanceAdd(len, tlen);
} while (returnCode == 0 && (ln = ln.cdr) != null);
break;
case NodeType.ALT:
ConsAltNode an = (ConsAltNode)node;
boolean varLen = false;
int tlen = getCharLengthTree(an.car, level);
while (returnCode == 0 && (an = an.cdr) != null) {
int tlen2 = getCharLengthTree(an.car, level);
if (returnCode == 0) {
if (tlen != tlen2) varLen = true;
}
}
if (returnCode == 0) {
if (varLen) {
if (level == 1) {
returnCode = GET_CHAR_LEN_TOP_ALT_VARLEN;
} else {
returnCode = GET_CHAR_LEN_VARLEN;
}
} else {
len = tlen;
}
}
break;
case NodeType.STR:
StringNode sn = (StringNode)node;
len = sn.length(enc);
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
if (qn.lower == qn.upper) {
tlen = getCharLengthTree(qn.target, level);
if (returnCode == 0) len = MinMaxLen.distanceMultiply(tlen, qn.lower);
} else {
returnCode = GET_CHAR_LEN_VARLEN;
}
break;
case NodeType.CALL:
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (!cn.isRecursion()) {
len = getCharLengthTree(cn.target, level);
} else {
returnCode = GET_CHAR_LEN_VARLEN;
}
break;
} // USE_SUBEXP_CALL
break;
case NodeType.CTYPE:
len = 1;
case NodeType.CCLASS:
case NodeType.CANY:
len = 1;
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
switch(en.type) {
case EncloseType.MEMORY:
if (Config.USE_SUBEXP_CALL) {
if (en.isCLenFixed()) {
len = en.charLength;
} else {
len = getCharLengthTree(en.target, level);
if (returnCode == 0) {
en.charLength = len;
en.setCLenFixed();
}
}
break;
} // USE_SUBEXP_CALL
break;
case EncloseType.OPTION:
case EncloseType.STOP_BACKTRACK:
len = getCharLengthTree(en.target, level);
break;
} // inner switch
break;
case NodeType.ANCHOR:
break;
default:
returnCode = GET_CHAR_LEN_VARLEN;
} // switch
return len;
}
/* x is not included y ==> 1 : 0 */
private boolean isNotIncluded(Node x, Node y) {
Node tmp;
// !retry:!
retry:while(true) {
int yType = y.getType();
switch(x.getType()) {
case NodeType.CTYPE:
switch(yType) {
case NodeType.CTYPE:
CTypeNode cny = (CTypeNode)y;
CTypeNode cnx = (CTypeNode)x;
return cny.ctype == cnx.ctype && cny.not != cnx.not;
case NodeType.CCLASS:
// !swap:!
tmp = x;
x = y;
y = tmp;
// !goto retry;!
continue retry;
case NodeType.STR:
// !goto swap;!
tmp = x;
x = y;
y = tmp;
continue retry;
default:
break;
} // inner switch
break;
case NodeType.CCLASS:
CClassNode xc = (CClassNode)x;
switch(yType) {
case NodeType.CTYPE:
switch(((CTypeNode)y).ctype) {
case CharacterType.WORD:
if (!((CTypeNode)y).not) {
if (xc.mbuf == null && !xc.isNot()) {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (xc.bs.at(i)) {
if (enc.isSbWord(i)) return false;
}
}
return true;
}
return false;
} else {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (!enc.isSbWord(i)) {
if (!xc.isNot()) {
if (xc.bs.at(i)) return false;
} else {
if (!xc.bs.at(i)) return false;
}
}
}
return true;
}
// break; not reached
default:
break;
} // inner switch
break;
case NodeType.CCLASS:
CClassNode yc = (CClassNode)y;
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
boolean v = xc.bs.at(i);
if ((v && !xc.isNot()) || (!v && xc.isNot())) {
v = yc.bs.at(i);
if ((v && !yc.isNot()) || (!v && yc.isNot())) return false;
}
}
if ((xc.mbuf == null && !xc.isNot()) || yc.mbuf == null && !yc.isNot()) return true;
return false;
// break; not reached
case NodeType.STR:
// !goto swap;!
tmp = x;
x = y;
y = tmp;
continue retry;
default:
break;
} // inner switch
break; // case NodeType.CCLASS
case NodeType.STR:
StringNode xs = (StringNode)x;
if (xs.length() == 0) break;
switch (yType) {
case NodeType.CTYPE:
CTypeNode cy = ((CTypeNode)y);
switch (cy.ctype) {
case CharacterType.WORD:
if (enc.isMbcWord(xs.bytes, xs.p, xs.end)) {
return cy.not;
} else {
return !cy.not;
}
default:
break;
} // inner switch
break;
case NodeType.CCLASS:
CClassNode cc = (CClassNode)y;
int code = enc.mbcToCode(xs.bytes, xs.p, xs.p + enc.maxLength());
return !cc.isCodeInCC(enc, code);
case NodeType.STR:
StringNode ys = (StringNode)y;
int len = xs.length();
if (len > ys.length()) len = ys.length();
if (xs.isAmbig() || ys.isAmbig()) {
/* tiny version */
return false;
} else {
for (int i=0, p=ys.p, q=xs.p; i<len; i++, p++, q++) {
if (ys.bytes[p] != xs.bytes[q]) return true;
}
}
break;
default:
break;
} // inner switch
break; // case NodeType.STR
} // switch
break;
} // retry:while
return false;
}
private Node getHeadValueNode(Node node, boolean exact) {
Node n = null;
switch(node.getType()) {
case NodeType.BREF:
case NodeType.ALT:
case NodeType.CANY:
break;
case NodeType.CALL:
break; // if (Config.USE_SUBEXP_CALL)
case NodeType.CTYPE:
case NodeType.CCLASS:
if (!exact) n = node;
break;
case NodeType.LIST:
n = getHeadValueNode(((ConsAltNode)node).car, exact);
break;
case NodeType.STR:
StringNode sn = (StringNode)node;
if (sn.end <= sn.p) break; // ???
if (exact && !sn.isRaw() && isIgnoreCase(regex.options)){
// nothing
} else {
n = node;
}
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
if (qn.lower > 0) {
if (qn.headExact != null) {
n = qn.headExact;
} else {
n = getHeadValueNode(qn.target, exact);
}
}
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.OPTION:
int options = regex.options;
regex.options = en.option;
n = getHeadValueNode(en.target, exact);
regex.options = options;
break;
case EncloseType.MEMORY:
case EncloseType.STOP_BACKTRACK:
n = getHeadValueNode(en.target, exact);
break;
} // inner switch
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
if (an.type == AnchorType.PREC_READ) n = getHeadValueNode(an.target, exact);
break;
default:
break;
} // switch
return n;
}
// true: invalid
private boolean checkTypeTree(Node node, int typeMask, int encloseMask, int anchorMask) {
if ((node.getType2Bit() & typeMask) == 0) return true;
boolean invalid = false;
switch(node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
invalid = checkTypeTree(can.car, typeMask, encloseMask, anchorMask);
} while (!invalid && (can = can.cdr) != null);
break;
case NodeType.QTFR:
invalid = checkTypeTree(((QuantifierNode)node).target, typeMask, encloseMask, anchorMask);
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
if ((en.type & encloseMask) == 0) return true;
invalid = checkTypeTree(en.target, typeMask, encloseMask, anchorMask);
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
if ((an.type & anchorMask) == 0) return true;
if (an.target != null) invalid = checkTypeTree(an.target, typeMask, encloseMask, anchorMask);
break;
default:
break;
} // switch
return invalid;
}
private static final int RECURSION_EXIST = 1;
private static final int RECURSION_INFINITE = 2;
private int subexpInfRecursiveCheck(Node node, boolean head) {
int r = 0;
switch (node.getType()) {
case NodeType.LIST:
int min;
ConsAltNode x = (ConsAltNode)node;
do {
int ret = subexpInfRecursiveCheck(x.car, head);
if (ret == RECURSION_INFINITE) return ret;
r |= ret;
if (head) {
min = getMinMatchLength(x.car);
if (min != 0) head = false;
}
} while ((x = x.cdr) != null);
break;
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
r = RECURSION_EXIST;
do {
int ret = subexpInfRecursiveCheck(can.car, head);
if (ret == RECURSION_INFINITE) return ret;
r &= ret;
} while ((can = can.cdr) != null);
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
r = subexpInfRecursiveCheck(qn.target, head);
if (r == RECURSION_EXIST) {
if (qn.lower == 0) r = 0;
}
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.PREC_READ:
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND:
case AnchorType.LOOK_BEHIND_NOT:
r = subexpInfRecursiveCheck(an.target, head);
break;
} // inner switch
break;
case NodeType.CALL:
r = subexpInfRecursiveCheck(((CallNode)node).target, head);
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
if (en.isMark2()) {
return 0;
} else if (en.isMark1()) {
return !head ? RECURSION_EXIST : RECURSION_INFINITE;
// throw exception here ???
} else {
en.setMark2();
r = subexpInfRecursiveCheck(en.target, head);
en.clearMark2();
}
break;
default:
break;
} // switch
return r;
}
protected final int subexpInfRecursiveCheckTrav(Node node) {
int r = 0;
switch (node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
r = subexpInfRecursiveCheckTrav(can.car);
} while (r == 0 && (can = can.cdr) != null);
break;
case NodeType.QTFR:
r = subexpInfRecursiveCheckTrav(((QuantifierNode)node).target);
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.PREC_READ:
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND:
case AnchorType.LOOK_BEHIND_NOT:
r = subexpInfRecursiveCheckTrav(an.target);
break;
} // inner switch
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
if (en.isRecursion()) {
en.setMark1();
r = subexpInfRecursiveCheck(en.target, true);
if (r > 0) newValueException(ERR_NEVER_ENDING_RECURSION);
en.clearMark1();
}
r = subexpInfRecursiveCheckTrav(en.target);
break;
default:
break;
} // switch
return r;
}
private int subexpRecursiveCheck(Node node) {
int r = 0;
switch (node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
r |= subexpRecursiveCheck(can.car);
} while ((can = can.cdr) != null);
break;
case NodeType.QTFR:
r = subexpRecursiveCheck(((QuantifierNode)node).target);
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.PREC_READ:
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND:
case AnchorType.LOOK_BEHIND_NOT:
r = subexpRecursiveCheck(an.target);
break;
} // inner switch
break;
case NodeType.CALL:
CallNode cn = (CallNode)node;
r = subexpRecursiveCheck(cn.target);
if (r != 0) cn.setRecursion();
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
if (en.isMark2()) {
return 0;
} else if (en.isMark1()) {
return 1; /* recursion */
} else {
en.setMark2();
r = subexpRecursiveCheck(en.target);
en.clearMark2();
}
break;
default:
break;
} // switch
return r;
}
private static final int FOUND_CALLED_NODE = 1;
protected final int subexpRecursiveCheckTrav(Node node) {
int r = 0;
switch (node.getType()) {
case NodeType.LIST:
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
int ret = subexpRecursiveCheckTrav(can.car);
if (ret == FOUND_CALLED_NODE) {
r = FOUND_CALLED_NODE;
}
// else if (ret < 0) return ret; ???
} while ((can = can.cdr) != null);
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
r = subexpRecursiveCheckTrav(qn.target);
if (qn.upper == 0) {
if (r == FOUND_CALLED_NODE) qn.isRefered = true;
}
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.PREC_READ:
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND:
case AnchorType.LOOK_BEHIND_NOT:
r = subexpRecursiveCheckTrav(an.target);
break;
} // inner switch
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
if (!en.isRecursion()) {
if (en.isCalled()) {
en.setMark1();
r = subexpRecursiveCheck(en.target);
if (r != 0) en.setRecursion();
en.clearMark1();
}
}
r = subexpRecursiveCheckTrav(en.target);
if (en.isCalled()) r |= FOUND_CALLED_NODE;
break;
default:
break;
} // switch
return r;
}
protected final void setupSubExpCall(Node node) {
switch(node.getType()) {
case NodeType.LIST:
ConsAltNode ln = (ConsAltNode)node;
do {
setupSubExpCall(ln.car);
} while ((ln = ln.cdr) != null);
break;
case NodeType.ALT:
ConsAltNode can = (ConsAltNode)node;
do {
setupSubExpCall(can.car);
} while ((can = can.cdr) != null);
break;
case NodeType.QTFR:
setupSubExpCall(((QuantifierNode)node).target);
break;
case NodeType.ENCLOSE:
setupSubExpCall(((EncloseNode)node).target);
break;
case NodeType.CALL:
CallNode cn = (CallNode)node;
if (cn.groupNum != 0) {
int gNum = cn.groupNum;
if (Config.USE_NAMED_GROUP) {
if (env.numNamed > 0 && syntax.captureOnlyNamedGroup() && !isCaptureGroup(env.option)) {
newValueException(ERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED);
}
} // USE_NAMED_GROUP
if (gNum > env.numMem) newValueException(ERR_UNDEFINED_GROUP_REFERENCE, cn.nameP, cn.nameEnd);
// !goto set_call_attr!; // remove duplication ?
cn.target = env.memNodes[cn.groupNum]; // no setTarget in call nodes!
if (cn.target == null) newValueException(ERR_UNDEFINED_NAME_REFERENCE, cn.nameP, cn.nameEnd);
((EncloseNode)cn.target).setCalled();
env.btMemStart = BitStatus.bsOnAt(env.btMemStart, cn.groupNum);
cn.unsetAddrList = env.unsetAddrList;
} else {
if (Config.USE_NAMED_GROUP) {
NameEntry ne = regex.nameToGroupNumbers(cn.name, cn.nameP, cn.nameEnd);
if (ne == null) {
newValueException(ERR_UNDEFINED_NAME_REFERENCE, cn.nameP, cn.nameEnd);
} else if (ne.backNum > 1) {
newValueException(ERR_MULTIPLEX_DEFINITION_NAME_CALL, cn.nameP, cn.nameEnd);
} else {
cn.groupNum = ne.backRef1; // ne.backNum == 1 ? ne.backRef1 : ne.backRefs[0]; // ??? need to check ?
// !set_call_attr:!
cn.target = env.memNodes[cn.groupNum]; // no setTarget in call nodes!
if (cn.target == null) newValueException(ERR_UNDEFINED_NAME_REFERENCE, cn.nameP, cn.nameEnd);
((EncloseNode)cn.target).setCalled();
env.btMemStart = BitStatus.bsOnAt(env.btMemStart, cn.groupNum);
cn.unsetAddrList = env.unsetAddrList;
}
}
}
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.PREC_READ:
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND:
case AnchorType.LOOK_BEHIND_NOT:
setupSubExpCall(an.target);
break;
}
break;
} // switch
}
/* divide different length alternatives in look-behind.
(?<=A|B) ==> (?<=A)|(?<=B)
(?<!A|B) ==> (?<!A)(?<!B)
*/
private void divideLookBehindAlternatives(Node node) {
AnchorNode an = (AnchorNode)node;
int anchorType = an.type;
Node head = an.target;
Node np = ((ConsAltNode)head).car;
swap(node, head);
Node tmp = node;
node = head;
head = tmp;
((ConsAltNode)node).setCar(head);
((AnchorNode)head).setTarget(np);
np = node;
while ((np = ((ConsAltNode)np).cdr) != null) {
AnchorNode insert = new AnchorNode(anchorType);
insert.setTarget(((ConsAltNode)np).car);
((ConsAltNode)np).setCar(insert);
}
if (anchorType == AnchorType.LOOK_BEHIND_NOT) {
np = node;
do {
((ConsAltNode)np).toListNode(); /* alt -> list */
} while ((np = ((ConsAltNode)np).cdr) != null);
}
}
private void setupLookBehind(Node node) {
AnchorNode an = (AnchorNode)node;
int len = getCharLengthTree(an.target);
switch(returnCode) {
case 0:
an.charLength = len;
break;
case GET_CHAR_LEN_VARLEN:
newSyntaxException(ERR_INVALID_LOOK_BEHIND_PATTERN);
break;
case GET_CHAR_LEN_TOP_ALT_VARLEN:
if (syntax.differentLengthAltLookBehind()) {
divideLookBehindAlternatives(node);
} else {
newSyntaxException(ERR_INVALID_LOOK_BEHIND_PATTERN);
}
}
}
private void nextSetup(Node node, Node nextNode) {
// retry:
retry: while(true) {
int type = node.getType();
if (type == NodeType.QTFR) {
QuantifierNode qn = (QuantifierNode)node;
if (qn.greedy && isRepeatInfinite(qn.upper)) {
if (Config.USE_QTFR_PEEK_NEXT) {
StringNode n = (StringNode)getHeadValueNode(nextNode, true);
/* '\0': for UTF-16BE etc... */
if (n != null && n.bytes[n.p] != 0) { // ?????????
qn.nextHeadExact = n;
}
} // USE_QTFR_PEEK_NEXT
/* automatic posseivation a*b ==> (?>a*)b */
if (qn.lower <= 1) {
if (qn.target.isSimple()) {
Node x = getHeadValueNode(qn.target, false);
if (x != null) {
Node y = getHeadValueNode(nextNode, false);
if (y != null && isNotIncluded(x, y)) {
EncloseNode en = new EncloseNode(EncloseType.STOP_BACKTRACK); //onig_node_new_enclose
en.setStopBtSimpleRepeat();
//en.setTarget(qn.target); // optimize it ??
swap(node, en);
en.setTarget(node);
}
}
}
}
}
} else if (type == NodeType.ENCLOSE) {
EncloseNode en = (EncloseNode)node;
if (en.isMemory()) {
node = en.target;
// !goto retry;!
continue retry;
}
}
break;
} // while
}
private void updateStringNodeCaseFold(Node node) {
StringNode sn = (StringNode)node;
byte[]sbuf = new byte[sn.length() << 1];
int sp = 0;
value = sn.p;
int end = sn.end;
byte[]buf = new byte[Config.ENC_MBC_CASE_FOLD_MAXLEN];
while (value < end) {
int len = enc.mbcCaseFold(regex.caseFoldFlag, sn.bytes, this, end, buf);
for (int i=0; i<len; i++) {
if (sp >= sbuf.length) {
byte[]tmp = new byte[sbuf.length << 1];
System.arraycopy(sbuf, 0, tmp, 0, sbuf.length);
sbuf = tmp;
}
sbuf[sp++] = buf[i];
}
}
sn.set(sbuf, 0, sp);
}
private Node expandCaseFoldMakeRemString(byte[]bytes, int p, int end) {
StringNode node = new StringNode(bytes, p, end);
updateStringNodeCaseFold(node);
node.setAmbig();
node.setDontGetOptInfo();
return node;
}
private boolean expandCaseFoldStringAlt(int itemNum, CaseFoldCodeItem[]items,
byte[]bytes, int p, int slen, int end, Node[]node) {
boolean varlen = false;
for (int i=0; i<itemNum; i++) {
if (items[i].byteLen != slen) {
varlen = true;
break;
}
}
ConsAltNode varANode = null, anode, xnode;
if (varlen) {
node[0] = varANode = newAltNode(null, null);
xnode = newListNode(null, null);
varANode.setCar(xnode);
anode = newAltNode(null, null);
xnode.setCar(anode);
} else {
node[0] = anode = newAltNode(null, null);
}
StringNode snode = new StringNode(bytes, p, p + slen);
anode.setCar(snode);
for (int i=0; i<itemNum; i++) {
snode = new StringNode();
for (int j=0; j<items[i].codeLen; j++) {
snode.ensure(Config.ENC_CODE_TO_MBC_MAXLEN);
snode.end += enc.codeToMbc(items[i].code[j], snode.bytes, snode.end);
}
ConsAltNode an = newAltNode(null, null);
if (items[i].byteLen != slen) {
int q = p + items[i].byteLen;
if (q < end) {
Node rem = expandCaseFoldMakeRemString(bytes, q, end);
xnode = ConsAltNode.listAdd(null, snode);
ConsAltNode.listAdd(xnode, rem);
an.setCar(xnode);
} else {
an.setCar(snode);
}
varANode.setCdr(an);
varANode = an;
} else {
an.setCar(snode);
anode.setCdr(an);
anode = an;
}
}
return varlen;
}
private static final int THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION = 8;
private void expandCaseFoldString(Node node) {
StringNode sn = (StringNode)node;
if (sn.isAmbig()) return;
if (sn.length() <= 0) return;
byte[]bytes = sn.bytes;
int p = sn.p;
int end = sn.end;
int altNum = 1;
ConsAltNode topRoot = null, root = null;
Node[]prevNode = new Node[]{null};
StringNode snode = null;
while (p < end) {
CaseFoldCodeItem[]items = enc.caseFoldCodesByString(regex.caseFoldFlag, bytes, p, end);
int len = enc.length(bytes[p]);
if (items.length == 0) {
if (snode == null) {
if (root == null && prevNode[0] != null) {
topRoot = root = ConsAltNode.listAdd(null, prevNode[0]);
}
prevNode[0] = snode = new StringNode(); // onig_node_new_str(NULL, NULL);
if (root != null) {
ConsAltNode.listAdd(root, snode);
}
}
snode.cat(bytes, p, p + len);
} else {
altNum *= (items.length + 1);
if (altNum > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break;
if (root == null && prevNode[0] != null) {
topRoot = root = ConsAltNode.listAdd(null, prevNode[0]);
}
boolean r = expandCaseFoldStringAlt(items.length, items, bytes, p, len, end, prevNode);
if (r) { // if (r == 1)
if (root == null) {
topRoot = (ConsAltNode)prevNode[0];
} else {
ConsAltNode.listAdd(root, prevNode[0]);
}
root = (ConsAltNode)((ConsAltNode)prevNode[0]).car;
} else { /* r == 0 */
if (root != null) {
ConsAltNode.listAdd(root, prevNode[0]);
}
}
snode = null;
}
p += len;
}
if (p < end) {
Node srem = expandCaseFoldMakeRemString(bytes, p, end);
if (prevNode[0] != null && root == null) {
topRoot = root = ConsAltNode.listAdd(null, prevNode[0]);
}
if (root == null) {
prevNode[0] = srem;
} else {
ConsAltNode.listAdd(root, srem);
}
}
/* ending */
Node xnode = topRoot != null ? topRoot : prevNode[0];
swap(node, xnode);
}
private static final int CEC_THRES_NUM_BIG_REPEAT = 512;
private static final int CEC_INFINITE_NUM = 0x7fffffff;
private static final int CEC_IN_INFINITE_REPEAT = (1<<0);
private static final int CEC_IN_FINITE_REPEAT = (1<<1);
private static final int CEC_CONT_BIG_REPEAT = (1<<2);
protected final int setupCombExpCheck(Node node, int state) {
int r = state;
int ret;
switch (node.getType()) {
case NodeType.LIST:
ConsAltNode ln = (ConsAltNode)node;
do {
r = setupCombExpCheck(ln.car, r);
//prev = ((ConsAltNode)node).car;
} while (r >= 0 && (ln = ln.cdr) != null);
break;
case NodeType.ALT:
ConsAltNode an = (ConsAltNode)node;
do {
ret = setupCombExpCheck(an.car, state);
r |= ret;
} while (ret >= 0 && (an = an.cdr) != null);
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
int childState = state;
int addState = 0;
int varNum;
if (!isRepeatInfinite(qn.upper)) {
if (qn.upper > 1) {
/* {0,1}, {1,1} are allowed */
childState |= CEC_IN_FINITE_REPEAT;
/* check (a*){n,m}, (a+){n,m} => (a*){n,n}, (a+){n,n} */
if (env.backrefedMem == 0) {
if (qn.target.getType() == NodeType.ENCLOSE) {
EncloseNode en = (EncloseNode)qn.target;
if (en.type == EncloseType.MEMORY) {
if (en.target.getType() == NodeType.QTFR) {
QuantifierNode q = (QuantifierNode)en.target;
if (isRepeatInfinite(q.upper) && q.greedy == qn.greedy) {
qn.upper = qn.lower == 0 ? 1 : qn.lower;
if (qn.upper == 1) childState = state;
}
}
}
}
}
}
}
if ((state & CEC_IN_FINITE_REPEAT) != 0) {
qn.combExpCheckNum = -1;
} else {
if (isRepeatInfinite(qn.upper)) {
varNum = CEC_INFINITE_NUM;
childState |= CEC_IN_INFINITE_REPEAT;
} else {
varNum = qn.upper - qn.lower;
}
if (varNum >= CEC_THRES_NUM_BIG_REPEAT) addState |= CEC_CONT_BIG_REPEAT;
if (((state & CEC_IN_INFINITE_REPEAT) != 0 && varNum != 0) ||
((state & CEC_CONT_BIG_REPEAT) != 0 && varNum >= CEC_THRES_NUM_BIG_REPEAT)) {
if (qn.combExpCheckNum == 0) {
env.numCombExpCheck++;
qn.combExpCheckNum = env.numCombExpCheck;
if (env.currMaxRegNum > env.combExpMaxRegNum) {
env.combExpMaxRegNum = env.currMaxRegNum;
}
}
}
}
r = setupCombExpCheck(qn.target, childState);
r |= addState;
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
switch( en.type) {
case EncloseNode.MEMORY:
if (env.currMaxRegNum < en.regNum) {
env.currMaxRegNum = en.regNum;
}
r = setupCombExpCheck(en.target, state);
break;
default:
r = setupCombExpCheck(en.target, state);
} // inner switch
break;
case NodeType.CALL:
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (cn.isRecursion()) {
env.hasRecursion = true;
} else {
r = setupCombExpCheck(cn.target, state);
}
break;
} // USE_SUBEXP_CALL
break;
default:
break;
} // switch
return r;
}
private static final int IN_ALT = (1<<0);
private static final int IN_NOT = (1<<1);
private static final int IN_REPEAT = (1<<2);
private static final int IN_VAR_REPEAT = (1<<3);
private static final int EXPAND_STRING_MAX_LENGTH = 100;
/* setup_tree does the following work.
1. check empty loop. (set qn->target_empty_info)
2. expand ignore-case in char class.
3. set memory status bit flags. (reg->mem_stats)
4. set qn->head_exact for [push, exact] -> [push_or_jump_exact1, exact].
5. find invalid patterns in look-behind.
6. expand repeated string.
*/
protected final void setupTree(Node node, int state) {
switch (node.getType()) {
case NodeType.LIST:
ConsAltNode lin = (ConsAltNode)node;
Node prev = null;
do {
setupTree(lin.car, state);
if (prev != null) {
nextSetup(prev, lin.car);
}
prev = lin.car;
} while ((lin = lin.cdr) != null);
break;
case NodeType.ALT:
ConsAltNode aln = (ConsAltNode)node;
do {
setupTree(aln.car, (state | IN_ALT));
} while ((aln = aln.cdr) != null);
break;
case NodeType.CCLASS:
break;
case NodeType.STR:
if (isIgnoreCase(regex.options) && !((StringNode)node).isRaw()) {
expandCaseFoldString(node);
}
break;
case NodeType.CTYPE:
case NodeType.CANY:
break;
case NodeType.CALL: // if (Config.USE_SUBEXP_CALL) ?
break;
case NodeType.BREF:
BackRefNode br = (BackRefNode)node;
for (int i=0; i<br.backNum; i++) {
if (br.back[i] > env.numMem) newValueException(ERR_INVALID_BACKREF);
env.backrefedMem = bsOnAt(env.backrefedMem, br.back[i]);
env.btMemStart = bsOnAt(env.btMemStart, br.back[i]);
if (Config.USE_BACKREF_WITH_LEVEL) {
if (br.isNestLevel()) {
env.btMemEnd = bsOnAt(env.btMemEnd, br.back[i]);
}
} // USE_BACKREF_AT_LEVEL
((EncloseNode)env.memNodes[br.back[i]]).setMemBackrefed();
}
break;
case NodeType.QTFR:
QuantifierNode qn = (QuantifierNode)node;
Node target = qn.target;
if ((state & IN_REPEAT) != 0) qn.setInRepeat();
if (isRepeatInfinite(qn.upper) || qn.lower >= 1) {
int d = getMinMatchLength(target);
if (d == 0) {
qn.targetEmptyInfo = TargetInfo.IS_EMPTY;
if (Config.USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT) {
int info = quantifiersMemoryInfo(target);
if (info > 0) qn.targetEmptyInfo = info;
} // USE_INFINITE_REPEAT_MONOMANIAC_MEM_STATUS_CHECK
// strange stuff here (turned off)
}
}
state |= IN_REPEAT;
if (qn.lower != qn.upper) state |= IN_VAR_REPEAT;
setupTree(target, state);
/* expand string */
if (target.getType() == NodeType.STR) {
if (!isRepeatInfinite(qn.lower) && qn.lower == qn.upper &&
qn.lower > 1 && qn.lower <= EXPAND_STRING_MAX_LENGTH) {
StringNode sn = (StringNode)target;
int len = sn.length();
if (len * qn.lower <= EXPAND_STRING_MAX_LENGTH) {
StringNode str = qn.convertToString();
// if (str.parent == null) root = str;
int n = qn.lower;
for (int i=0; i<n; i++) {
str.cat(sn.bytes, sn.p, sn.end);
}
}
break; /* break case NT_QTFR: */
}
}
if (Config.USE_OP_PUSH_OR_JUMP_EXACT) {
if (qn.greedy && qn.targetEmptyInfo != 0) {
if (target.getType() == NodeType.QTFR) {
QuantifierNode tqn = (QuantifierNode)target;
if (tqn.headExact != null) {
qn.headExact = tqn.headExact;
tqn.headExact = null;
}
} else {
qn.headExact = getHeadValueNode(qn.target, true);
}
}
} // USE_OP_PUSH_OR_JUMP_EXACT
break;
case NodeType.ENCLOSE:
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.OPTION:
int options = regex.options;
regex.options = en.option;
setupTree(en.target, state);
regex.options = options;
break;
case EncloseType.MEMORY:
if ((state & (IN_ALT | IN_NOT | IN_VAR_REPEAT)) != 0) {
env.btMemStart = bsOnAt(env.btMemStart, en.regNum);
/* SET_ENCLOSE_STATUS(node, NST_MEM_IN_ALT_NOT); */
}
setupTree(en.target, state);
break;
case EncloseType.STOP_BACKTRACK:
setupTree(en.target, state);
if (en.target.getType() == NodeType.QTFR) {
QuantifierNode tqn = (QuantifierNode)en.target;
if (isRepeatInfinite(tqn.upper) && tqn.lower <= 1 && tqn.greedy) {
/* (?>a*), a*+ etc... */
if (tqn.target.isSimple()) en.setStopBtSimpleRepeat();
}
}
break;
} // inner switch
break;
case NodeType.ANCHOR:
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.PREC_READ:
setupTree(an.target, state);
break;
case AnchorType.PREC_READ_NOT:
setupTree(an.target, (state | IN_NOT));
break;
case AnchorType.LOOK_BEHIND:
boolean lbInvalid = checkTypeTree(an.target, NodeType.ALLOWED_IN_LB,
EncloseType.ALLOWED_IN_LB,
AnchorType.ALLOWED_IN_LB);
if (lbInvalid) newSyntaxException(ERR_INVALID_LOOK_BEHIND_PATTERN);
setupLookBehind(node);
setupTree(an.target, state);
break;
case AnchorType.LOOK_BEHIND_NOT:
boolean lbnInvalid = checkTypeTree(an.target, NodeType.ALLOWED_IN_LB,
EncloseType.ALLOWED_IN_LB,
AnchorType.ALLOWED_IN_LB);
if (lbnInvalid) newSyntaxException(ERR_INVALID_LOOK_BEHIND_PATTERN);
setupLookBehind(node);
setupTree(an.target, (state | IN_NOT));
break;
} // inner switch
break;
default:
break;
} // switch
}
private static final int MAX_NODE_OPT_INFO_REF_COUNT = 5;
private void optimizeNodeLeft(Node node, NodeOptInfo opt, OptEnvironment oenv) { // oenv remove, pass mmd
opt.clear();
opt.setBoundNode(oenv.mmd);
switch (node.getType()) {
case NodeType.LIST: {
OptEnvironment nenv = new OptEnvironment();
NodeOptInfo nopt = new NodeOptInfo();
nenv.copy(oenv);
ConsAltNode lin = (ConsAltNode)node;
do {
optimizeNodeLeft(lin.car, nopt, nenv);
nenv.mmd.add(nopt.length);
opt.concatLeftNode(nopt, enc);
} while ((lin = lin.cdr) != null);
break;
}
case NodeType.ALT: {
NodeOptInfo nopt = new NodeOptInfo();
ConsAltNode aln = (ConsAltNode)node;
do {
optimizeNodeLeft(aln.car, nopt, oenv);
if (aln == node) {
opt.copy(nopt);
} else {
opt.altMerge(nopt, oenv);
}
} while ((aln = aln.cdr) != null);
break;
}
case NodeType.STR: {
StringNode sn = (StringNode)node;
int slen = sn.length();
if (!sn.isAmbig()) {
opt.exb.concatStr(sn.bytes, sn.p, sn.end, sn.isRaw(), enc);
if (slen > 0) {
opt.map.addChar(sn.bytes[sn.p], enc);
}
opt.length.set(slen, slen);
} else {
int max;
if (sn.isDontGetOptInfo()) {
int n = sn.length(enc);
max = enc.maxLengthDistance() * n;
} else {
opt.exb.concatStr(sn.bytes, sn.p, sn.end, sn.isRaw(), enc);
opt.exb.ignoreCase = true;
if (slen > 0) {
opt.map.addCharAmb(sn.bytes, sn.p, sn.end, enc, oenv.caseFoldFlag);
}
max = slen;
}
opt.length.set(slen, max);
}
if (opt.exb.length == slen) {
opt.exb.reachEnd = true;
}
break;
}
case NodeType.CCLASS: {
CClassNode cc = (CClassNode)node;
/* no need to check ignore case. (setted in setup_tree()) */
if (cc.mbuf != null || cc.isNot()) {
int min = enc.minLength();
int max = enc.maxLengthDistance();
opt.length.set(min, max);
} else {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
boolean z = cc.bs.at(i);
if ((z && !cc.isNot()) || (!z && cc.isNot())) {
opt.map.addChar((byte)i, enc);
}
}
opt.length.set(1, 1);
}
break;
}
case NodeType.CTYPE: {
int min;
int max = enc.maxLengthDistance();
if (max == 1) {
min = 1;
CTypeNode cn = (CTypeNode)node;
switch (cn.ctype) {
case CharacterType.WORD:
if (cn.not) {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (!enc.isWord(i)) {
opt.map.addChar((byte)i, enc);
}
}
} else {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (enc.isWord(i)) {
opt.map.addChar((byte)i, enc);
}
}
}
break;
} // inner switch
} else {
min = enc.minLength();
}
opt.length.set(min, max);
break;
}
case NodeType.CANY: {
opt.length.set(enc.minLength(), enc.maxLengthDistance());
break;
}
case NodeType.ANCHOR: {
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.BEGIN_BUF:
case AnchorType.BEGIN_POSITION:
case AnchorType.BEGIN_LINE:
case AnchorType.END_BUF:
case AnchorType.SEMI_END_BUF:
case AnchorType.END_LINE:
opt.anchor.add(an.type);
break;
case AnchorType.PREC_READ:
NodeOptInfo nopt = new NodeOptInfo();
optimizeNodeLeft(an.target, nopt, oenv);
if (nopt.exb.length > 0) {
opt.expr.copy(nopt.exb);
} else if (nopt.exm.length > 0) {
opt.expr.copy(nopt.exm);
opt.expr.reachEnd = true;
if (nopt.map.value > 0) opt.map.copy(nopt.map);
}
break;
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND: /* Sorry, I can't make use of it. */
case AnchorType.LOOK_BEHIND_NOT:
break;
} // inner switch
break;
}
case NodeType.BREF: {
BackRefNode br = (BackRefNode)node;
if (br.isRecursion()) {
opt.length.set(0, MinMaxLen.INFINITE_DISTANCE);
break;
}
Node[]nodes = oenv.scanEnv.memNodes;
int min = getMinMatchLength(nodes[br.back[0]]);
int max = getMaxMatchLength(nodes[br.back[0]]);
for (int i=1; i<br.backNum; i++) {
int tmin = getMinMatchLength(nodes[br.back[i]]);
int tmax = getMaxMatchLength(nodes[br.back[i]]);
if (min > tmin) min = tmin;
if (max < tmax) max = tmax;
}
opt.length.set(min, max);
break;
}
case NodeType.CALL: {
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (cn.isRecursion()) {
opt.length.set(0, MinMaxLen.INFINITE_DISTANCE);
} else {
int safe = oenv.options;
oenv.options = ((EncloseNode)cn.target).option;
optimizeNodeLeft(cn.target, opt, oenv);
oenv.options = safe;
}
break;
} // USE_SUBEXP_CALL
break;
}
case NodeType.QTFR: {
NodeOptInfo nopt = new NodeOptInfo();
QuantifierNode qn = (QuantifierNode)node;
optimizeNodeLeft(qn.target, nopt, oenv);
if (qn.lower == 0 && isRepeatInfinite(qn.upper)) {
if (oenv.mmd.max == 0 && qn.target.getType() == NodeType.CANY && qn.greedy) {
if (isMultiline(oenv.options)) {
opt.anchor.add(AnchorType.ANYCHAR_STAR_ML);
} else {
opt.anchor.add(AnchorType.ANYCHAR_STAR);
}
}
} else {
if (qn.lower > 0) {
opt.copy(nopt);
if (nopt.exb.length > 0) {
if (nopt.exb.reachEnd) {
int i;
- for (i=2; i<qn.lower && !opt.exb.isFull(); i++) {
+ for (i=1; i<qn.lower && !opt.exb.isFull(); i++) {
opt.exb.concat(nopt.exb, enc);
}
if (i < qn.lower) {
opt.exb.reachEnd = false;
}
}
}
if (qn.lower != qn.upper) {
opt.exb.reachEnd = false;
opt.exm.reachEnd = false;
}
if (qn.lower > 1) {
opt.exm.reachEnd = false;
}
}
}
int min = MinMaxLen.distanceMultiply(nopt.length.min, qn.lower);
int max;
if (isRepeatInfinite(qn.upper)) {
max = nopt.length.max > 0 ? MinMaxLen.INFINITE_DISTANCE : 0;
} else {
max = MinMaxLen.distanceMultiply(nopt.length.max, qn.upper);
}
opt.length.set(min, max);
break;
}
case NodeType.ENCLOSE: {
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.OPTION:
int save = oenv.options;
oenv.options = en.option;
optimizeNodeLeft(en.target, opt, oenv);
oenv.options = save;
break;
case EncloseType.MEMORY:
if (Config.USE_SUBEXP_CALL && ++en.optCount > MAX_NODE_OPT_INFO_REF_COUNT) {
int min = 0;
int max = MinMaxLen.INFINITE_DISTANCE;
if (en.isMinFixed()) min = en.minLength;
if (en.isMaxFixed()) max = en.maxLength;
opt.length.set(min, max);
} else { // USE_SUBEXP_CALL
optimizeNodeLeft(en.target, opt, oenv);
if (opt.anchor.isSet(AnchorType.ANYCHAR_STAR_MASK)) {
if (bsAt(oenv.scanEnv.backrefedMem, en.regNum)) {
opt.anchor.remove(AnchorType.ANYCHAR_STAR_MASK);
}
}
}
break;
case EncloseType.STOP_BACKTRACK:
optimizeNodeLeft(en.target, opt, oenv);
break;
} // inner switch
break;
}
default:
newInternalException(ERR_PARSER_BUG);
} // switch
}
protected final void setOptimizedInfoFromTree(Node node) {
NodeOptInfo opt = new NodeOptInfo();
OptEnvironment oenv = new OptEnvironment();
oenv.enc = regex.enc;
oenv.options = regex.options;
oenv.caseFoldFlag = regex.caseFoldFlag;
oenv.scanEnv = env;
oenv.mmd.clear(); // ??
optimizeNodeLeft(node, opt, oenv);
regex.anchor = opt.anchor.leftAnchor & (AnchorType.BEGIN_BUF |
AnchorType.BEGIN_POSITION |
AnchorType.ANYCHAR_STAR |
AnchorType.ANYCHAR_STAR_ML);
regex.anchor |= opt.anchor.rightAnchor & (AnchorType.END_BUF |
AnchorType.SEMI_END_BUF);
if ((regex.anchor & (AnchorType.END_BUF | AnchorType.SEMI_END_BUF)) != 0) {
regex.anchorDmin = opt.length.min;
regex.anchorDmax = opt.length.max;
}
if (opt.exb.length > 0 || opt.exm.length > 0) {
opt.exb.select(opt.exm, enc);
if (opt.map.value > 0 && opt.exb.compare(opt.map) > 0) {
// !goto set_map;!
regex.setOptimizeMapInfo(opt.map);
regex.setSubAnchor(opt.map.anchor);
} else {
regex.setExactInfo(opt.exb);
regex.setSubAnchor(opt.exb.anchor);
}
} else if (opt.map.value > 0) {
// !set_map:!
regex.setOptimizeMapInfo(opt.map);
regex.setSubAnchor(opt.map.anchor);
} else {
regex.subAnchor |= opt.anchor.leftAnchor & AnchorType.BEGIN_LINE;
if (opt.length.max == 0) regex.subAnchor |= opt.anchor.rightAnchor & AnchorType.END_LINE;
}
if (Config.DEBUG_COMPILE || Config.DEBUG_MATCH) {
Config.log.println(regex.optimizeInfoToString());
}
}
}
| true | true | private void optimizeNodeLeft(Node node, NodeOptInfo opt, OptEnvironment oenv) { // oenv remove, pass mmd
opt.clear();
opt.setBoundNode(oenv.mmd);
switch (node.getType()) {
case NodeType.LIST: {
OptEnvironment nenv = new OptEnvironment();
NodeOptInfo nopt = new NodeOptInfo();
nenv.copy(oenv);
ConsAltNode lin = (ConsAltNode)node;
do {
optimizeNodeLeft(lin.car, nopt, nenv);
nenv.mmd.add(nopt.length);
opt.concatLeftNode(nopt, enc);
} while ((lin = lin.cdr) != null);
break;
}
case NodeType.ALT: {
NodeOptInfo nopt = new NodeOptInfo();
ConsAltNode aln = (ConsAltNode)node;
do {
optimizeNodeLeft(aln.car, nopt, oenv);
if (aln == node) {
opt.copy(nopt);
} else {
opt.altMerge(nopt, oenv);
}
} while ((aln = aln.cdr) != null);
break;
}
case NodeType.STR: {
StringNode sn = (StringNode)node;
int slen = sn.length();
if (!sn.isAmbig()) {
opt.exb.concatStr(sn.bytes, sn.p, sn.end, sn.isRaw(), enc);
if (slen > 0) {
opt.map.addChar(sn.bytes[sn.p], enc);
}
opt.length.set(slen, slen);
} else {
int max;
if (sn.isDontGetOptInfo()) {
int n = sn.length(enc);
max = enc.maxLengthDistance() * n;
} else {
opt.exb.concatStr(sn.bytes, sn.p, sn.end, sn.isRaw(), enc);
opt.exb.ignoreCase = true;
if (slen > 0) {
opt.map.addCharAmb(sn.bytes, sn.p, sn.end, enc, oenv.caseFoldFlag);
}
max = slen;
}
opt.length.set(slen, max);
}
if (opt.exb.length == slen) {
opt.exb.reachEnd = true;
}
break;
}
case NodeType.CCLASS: {
CClassNode cc = (CClassNode)node;
/* no need to check ignore case. (setted in setup_tree()) */
if (cc.mbuf != null || cc.isNot()) {
int min = enc.minLength();
int max = enc.maxLengthDistance();
opt.length.set(min, max);
} else {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
boolean z = cc.bs.at(i);
if ((z && !cc.isNot()) || (!z && cc.isNot())) {
opt.map.addChar((byte)i, enc);
}
}
opt.length.set(1, 1);
}
break;
}
case NodeType.CTYPE: {
int min;
int max = enc.maxLengthDistance();
if (max == 1) {
min = 1;
CTypeNode cn = (CTypeNode)node;
switch (cn.ctype) {
case CharacterType.WORD:
if (cn.not) {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (!enc.isWord(i)) {
opt.map.addChar((byte)i, enc);
}
}
} else {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (enc.isWord(i)) {
opt.map.addChar((byte)i, enc);
}
}
}
break;
} // inner switch
} else {
min = enc.minLength();
}
opt.length.set(min, max);
break;
}
case NodeType.CANY: {
opt.length.set(enc.minLength(), enc.maxLengthDistance());
break;
}
case NodeType.ANCHOR: {
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.BEGIN_BUF:
case AnchorType.BEGIN_POSITION:
case AnchorType.BEGIN_LINE:
case AnchorType.END_BUF:
case AnchorType.SEMI_END_BUF:
case AnchorType.END_LINE:
opt.anchor.add(an.type);
break;
case AnchorType.PREC_READ:
NodeOptInfo nopt = new NodeOptInfo();
optimizeNodeLeft(an.target, nopt, oenv);
if (nopt.exb.length > 0) {
opt.expr.copy(nopt.exb);
} else if (nopt.exm.length > 0) {
opt.expr.copy(nopt.exm);
opt.expr.reachEnd = true;
if (nopt.map.value > 0) opt.map.copy(nopt.map);
}
break;
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND: /* Sorry, I can't make use of it. */
case AnchorType.LOOK_BEHIND_NOT:
break;
} // inner switch
break;
}
case NodeType.BREF: {
BackRefNode br = (BackRefNode)node;
if (br.isRecursion()) {
opt.length.set(0, MinMaxLen.INFINITE_DISTANCE);
break;
}
Node[]nodes = oenv.scanEnv.memNodes;
int min = getMinMatchLength(nodes[br.back[0]]);
int max = getMaxMatchLength(nodes[br.back[0]]);
for (int i=1; i<br.backNum; i++) {
int tmin = getMinMatchLength(nodes[br.back[i]]);
int tmax = getMaxMatchLength(nodes[br.back[i]]);
if (min > tmin) min = tmin;
if (max < tmax) max = tmax;
}
opt.length.set(min, max);
break;
}
case NodeType.CALL: {
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (cn.isRecursion()) {
opt.length.set(0, MinMaxLen.INFINITE_DISTANCE);
} else {
int safe = oenv.options;
oenv.options = ((EncloseNode)cn.target).option;
optimizeNodeLeft(cn.target, opt, oenv);
oenv.options = safe;
}
break;
} // USE_SUBEXP_CALL
break;
}
case NodeType.QTFR: {
NodeOptInfo nopt = new NodeOptInfo();
QuantifierNode qn = (QuantifierNode)node;
optimizeNodeLeft(qn.target, nopt, oenv);
if (qn.lower == 0 && isRepeatInfinite(qn.upper)) {
if (oenv.mmd.max == 0 && qn.target.getType() == NodeType.CANY && qn.greedy) {
if (isMultiline(oenv.options)) {
opt.anchor.add(AnchorType.ANYCHAR_STAR_ML);
} else {
opt.anchor.add(AnchorType.ANYCHAR_STAR);
}
}
} else {
if (qn.lower > 0) {
opt.copy(nopt);
if (nopt.exb.length > 0) {
if (nopt.exb.reachEnd) {
int i;
for (i=2; i<qn.lower && !opt.exb.isFull(); i++) {
opt.exb.concat(nopt.exb, enc);
}
if (i < qn.lower) {
opt.exb.reachEnd = false;
}
}
}
if (qn.lower != qn.upper) {
opt.exb.reachEnd = false;
opt.exm.reachEnd = false;
}
if (qn.lower > 1) {
opt.exm.reachEnd = false;
}
}
}
int min = MinMaxLen.distanceMultiply(nopt.length.min, qn.lower);
int max;
if (isRepeatInfinite(qn.upper)) {
max = nopt.length.max > 0 ? MinMaxLen.INFINITE_DISTANCE : 0;
} else {
max = MinMaxLen.distanceMultiply(nopt.length.max, qn.upper);
}
opt.length.set(min, max);
break;
}
case NodeType.ENCLOSE: {
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.OPTION:
int save = oenv.options;
oenv.options = en.option;
optimizeNodeLeft(en.target, opt, oenv);
oenv.options = save;
break;
case EncloseType.MEMORY:
if (Config.USE_SUBEXP_CALL && ++en.optCount > MAX_NODE_OPT_INFO_REF_COUNT) {
int min = 0;
int max = MinMaxLen.INFINITE_DISTANCE;
if (en.isMinFixed()) min = en.minLength;
if (en.isMaxFixed()) max = en.maxLength;
opt.length.set(min, max);
} else { // USE_SUBEXP_CALL
optimizeNodeLeft(en.target, opt, oenv);
if (opt.anchor.isSet(AnchorType.ANYCHAR_STAR_MASK)) {
if (bsAt(oenv.scanEnv.backrefedMem, en.regNum)) {
opt.anchor.remove(AnchorType.ANYCHAR_STAR_MASK);
}
}
}
break;
case EncloseType.STOP_BACKTRACK:
optimizeNodeLeft(en.target, opt, oenv);
break;
} // inner switch
break;
}
default:
newInternalException(ERR_PARSER_BUG);
} // switch
}
| private void optimizeNodeLeft(Node node, NodeOptInfo opt, OptEnvironment oenv) { // oenv remove, pass mmd
opt.clear();
opt.setBoundNode(oenv.mmd);
switch (node.getType()) {
case NodeType.LIST: {
OptEnvironment nenv = new OptEnvironment();
NodeOptInfo nopt = new NodeOptInfo();
nenv.copy(oenv);
ConsAltNode lin = (ConsAltNode)node;
do {
optimizeNodeLeft(lin.car, nopt, nenv);
nenv.mmd.add(nopt.length);
opt.concatLeftNode(nopt, enc);
} while ((lin = lin.cdr) != null);
break;
}
case NodeType.ALT: {
NodeOptInfo nopt = new NodeOptInfo();
ConsAltNode aln = (ConsAltNode)node;
do {
optimizeNodeLeft(aln.car, nopt, oenv);
if (aln == node) {
opt.copy(nopt);
} else {
opt.altMerge(nopt, oenv);
}
} while ((aln = aln.cdr) != null);
break;
}
case NodeType.STR: {
StringNode sn = (StringNode)node;
int slen = sn.length();
if (!sn.isAmbig()) {
opt.exb.concatStr(sn.bytes, sn.p, sn.end, sn.isRaw(), enc);
if (slen > 0) {
opt.map.addChar(sn.bytes[sn.p], enc);
}
opt.length.set(slen, slen);
} else {
int max;
if (sn.isDontGetOptInfo()) {
int n = sn.length(enc);
max = enc.maxLengthDistance() * n;
} else {
opt.exb.concatStr(sn.bytes, sn.p, sn.end, sn.isRaw(), enc);
opt.exb.ignoreCase = true;
if (slen > 0) {
opt.map.addCharAmb(sn.bytes, sn.p, sn.end, enc, oenv.caseFoldFlag);
}
max = slen;
}
opt.length.set(slen, max);
}
if (opt.exb.length == slen) {
opt.exb.reachEnd = true;
}
break;
}
case NodeType.CCLASS: {
CClassNode cc = (CClassNode)node;
/* no need to check ignore case. (setted in setup_tree()) */
if (cc.mbuf != null || cc.isNot()) {
int min = enc.minLength();
int max = enc.maxLengthDistance();
opt.length.set(min, max);
} else {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
boolean z = cc.bs.at(i);
if ((z && !cc.isNot()) || (!z && cc.isNot())) {
opt.map.addChar((byte)i, enc);
}
}
opt.length.set(1, 1);
}
break;
}
case NodeType.CTYPE: {
int min;
int max = enc.maxLengthDistance();
if (max == 1) {
min = 1;
CTypeNode cn = (CTypeNode)node;
switch (cn.ctype) {
case CharacterType.WORD:
if (cn.not) {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (!enc.isWord(i)) {
opt.map.addChar((byte)i, enc);
}
}
} else {
for (int i=0; i<BitSet.SINGLE_BYTE_SIZE; i++) {
if (enc.isWord(i)) {
opt.map.addChar((byte)i, enc);
}
}
}
break;
} // inner switch
} else {
min = enc.minLength();
}
opt.length.set(min, max);
break;
}
case NodeType.CANY: {
opt.length.set(enc.minLength(), enc.maxLengthDistance());
break;
}
case NodeType.ANCHOR: {
AnchorNode an = (AnchorNode)node;
switch (an.type) {
case AnchorType.BEGIN_BUF:
case AnchorType.BEGIN_POSITION:
case AnchorType.BEGIN_LINE:
case AnchorType.END_BUF:
case AnchorType.SEMI_END_BUF:
case AnchorType.END_LINE:
opt.anchor.add(an.type);
break;
case AnchorType.PREC_READ:
NodeOptInfo nopt = new NodeOptInfo();
optimizeNodeLeft(an.target, nopt, oenv);
if (nopt.exb.length > 0) {
opt.expr.copy(nopt.exb);
} else if (nopt.exm.length > 0) {
opt.expr.copy(nopt.exm);
opt.expr.reachEnd = true;
if (nopt.map.value > 0) opt.map.copy(nopt.map);
}
break;
case AnchorType.PREC_READ_NOT:
case AnchorType.LOOK_BEHIND: /* Sorry, I can't make use of it. */
case AnchorType.LOOK_BEHIND_NOT:
break;
} // inner switch
break;
}
case NodeType.BREF: {
BackRefNode br = (BackRefNode)node;
if (br.isRecursion()) {
opt.length.set(0, MinMaxLen.INFINITE_DISTANCE);
break;
}
Node[]nodes = oenv.scanEnv.memNodes;
int min = getMinMatchLength(nodes[br.back[0]]);
int max = getMaxMatchLength(nodes[br.back[0]]);
for (int i=1; i<br.backNum; i++) {
int tmin = getMinMatchLength(nodes[br.back[i]]);
int tmax = getMaxMatchLength(nodes[br.back[i]]);
if (min > tmin) min = tmin;
if (max < tmax) max = tmax;
}
opt.length.set(min, max);
break;
}
case NodeType.CALL: {
if (Config.USE_SUBEXP_CALL) {
CallNode cn = (CallNode)node;
if (cn.isRecursion()) {
opt.length.set(0, MinMaxLen.INFINITE_DISTANCE);
} else {
int safe = oenv.options;
oenv.options = ((EncloseNode)cn.target).option;
optimizeNodeLeft(cn.target, opt, oenv);
oenv.options = safe;
}
break;
} // USE_SUBEXP_CALL
break;
}
case NodeType.QTFR: {
NodeOptInfo nopt = new NodeOptInfo();
QuantifierNode qn = (QuantifierNode)node;
optimizeNodeLeft(qn.target, nopt, oenv);
if (qn.lower == 0 && isRepeatInfinite(qn.upper)) {
if (oenv.mmd.max == 0 && qn.target.getType() == NodeType.CANY && qn.greedy) {
if (isMultiline(oenv.options)) {
opt.anchor.add(AnchorType.ANYCHAR_STAR_ML);
} else {
opt.anchor.add(AnchorType.ANYCHAR_STAR);
}
}
} else {
if (qn.lower > 0) {
opt.copy(nopt);
if (nopt.exb.length > 0) {
if (nopt.exb.reachEnd) {
int i;
for (i=1; i<qn.lower && !opt.exb.isFull(); i++) {
opt.exb.concat(nopt.exb, enc);
}
if (i < qn.lower) {
opt.exb.reachEnd = false;
}
}
}
if (qn.lower != qn.upper) {
opt.exb.reachEnd = false;
opt.exm.reachEnd = false;
}
if (qn.lower > 1) {
opt.exm.reachEnd = false;
}
}
}
int min = MinMaxLen.distanceMultiply(nopt.length.min, qn.lower);
int max;
if (isRepeatInfinite(qn.upper)) {
max = nopt.length.max > 0 ? MinMaxLen.INFINITE_DISTANCE : 0;
} else {
max = MinMaxLen.distanceMultiply(nopt.length.max, qn.upper);
}
opt.length.set(min, max);
break;
}
case NodeType.ENCLOSE: {
EncloseNode en = (EncloseNode)node;
switch (en.type) {
case EncloseType.OPTION:
int save = oenv.options;
oenv.options = en.option;
optimizeNodeLeft(en.target, opt, oenv);
oenv.options = save;
break;
case EncloseType.MEMORY:
if (Config.USE_SUBEXP_CALL && ++en.optCount > MAX_NODE_OPT_INFO_REF_COUNT) {
int min = 0;
int max = MinMaxLen.INFINITE_DISTANCE;
if (en.isMinFixed()) min = en.minLength;
if (en.isMaxFixed()) max = en.maxLength;
opt.length.set(min, max);
} else { // USE_SUBEXP_CALL
optimizeNodeLeft(en.target, opt, oenv);
if (opt.anchor.isSet(AnchorType.ANYCHAR_STAR_MASK)) {
if (bsAt(oenv.scanEnv.backrefedMem, en.regNum)) {
opt.anchor.remove(AnchorType.ANYCHAR_STAR_MASK);
}
}
}
break;
case EncloseType.STOP_BACKTRACK:
optimizeNodeLeft(en.target, opt, oenv);
break;
} // inner switch
break;
}
default:
newInternalException(ERR_PARSER_BUG);
} // switch
}
|
diff --git a/src/com/tinfoil/sms/crypto/ExchangeKey.java b/src/com/tinfoil/sms/crypto/ExchangeKey.java
index fbbdf364..a92246bf 100644
--- a/src/com/tinfoil/sms/crypto/ExchangeKey.java
+++ b/src/com/tinfoil/sms/crypto/ExchangeKey.java
@@ -1,287 +1,287 @@
/**
* Copyright (C) 2013 Jonathan Gillett, Joseph Heron
*
* 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.tinfoil.sms.crypto;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.tinfoil.sms.R;
import com.tinfoil.sms.dataStructures.ContactParent;
import com.tinfoil.sms.dataStructures.Number;
import com.tinfoil.sms.dataStructures.TrustedContact;
import com.tinfoil.sms.settings.EditNumber;
import com.tinfoil.sms.utility.MessageService;
import com.tinfoil.sms.utility.SMSUtility;
/**
* A class that creates a thread to manage a user's exchange of keys with
* contacts. It will go through each contact that the user wishes to exchange
* keys with and queue a key exchange message. This thread only handles the
* first phase of the key exchange. The second phase is handled in the
* MessagerReceiver.
*/
public class ExchangeKey implements Runnable {
//public static ProgressDialog keyDialog;
private ArrayList<String> untrusted;
private ArrayList<String> trusted;
private ArrayList<ContactParent> contacts;
private Number number;
private Activity activity;
private TrustedContact trustedContact;
private boolean multiNumber = false;
/**
* Used by the ManageContactsActivity to set up the key exchange thread
*
* @param contacts The list of contacts
*/
public void startThread(Activity activity, final ArrayList<ContactParent> contacts)
{
this.activity = activity;
this.contacts = contacts;
this.trusted = null;
this.untrusted = null;
multiNumber = true;
/*
* Start the thread from the constructor
*/
Thread thread = new Thread(this);
thread.start();
}
/**
* Used to setup the a key exchange for a single contact or to untrust a
* single contact.
* @param trusted The number of the contact to send a key exchange to,
* do not sent a key exchange if null
* @param untrusted The number of the contact to un-trust, no contact is
* untrusted.
*/
public void startThread(Activity activity, final String trusted, final String untrusted)
{
this.activity = activity;
this.trusted = new ArrayList<String>();
this.untrusted = new ArrayList<String>();
if(trusted != null)
{
this.trusted.add(trusted);
}
if(untrusted != null)
{
this.untrusted.add(untrusted);
}
multiNumber = false;
Thread thread = new Thread(this);
thread.start();
}
public void run() {
/*
* Used by ManageContacts Activity to determine from the
* contacts that have been selected need to exchange keys or
* stop sending secure messages
*/
if (this.trusted == null && this.untrusted == null)
{
this.trusted = new ArrayList<String>();
this.untrusted = new ArrayList<String>();
for (int i = 0; i < this.contacts.size(); i++)
{
for (int j = 0; j < this.contacts.get(i).getNumbers().size(); j++)
{
if (this.contacts.get(i).getNumber(j).isSelected())
{
if (!this.contacts.get(i).getNumber(j).isTrusted())
{
this.trusted.add(this.contacts.get(i).getNumber(j).getNumber());
}
else
{
this.untrusted.add(this.contacts.get(i).getNumber(j).getNumber());
}
}
}
}
}
/*
* This is actually how removing contacts from trusted should look since it is just a
* deletion of keys. We don't care if the contact will now fail to decrypt messages that
* is the user's problem
*/
if (this.untrusted != null)
{
for (int i = 0; i < this.untrusted.size(); i++)
{
//untrusted.get(i).clearPublicKey();
this.number = MessageService.dba.getNumber(this.untrusted.get(i));
this.number.clearPublicKey();
//set the initiator flag to false
this.number.setInitiator(false);
MessageService.dba.updateKey(this.number);
}
}
/*
* Start Key exchanges 1 by 1, messages are prepared and then placed in
* the messaging queue.
*/
boolean invalid = false;
if (this.trusted != null)
{
for (int i = 0; i < this.trusted.size(); i++)
{
number = MessageService.dba.getNumber(trusted.get(i));
if (SMSUtility.checksharedSecret(number.getSharedInfo1()) &&
SMSUtility.checksharedSecret(number.getSharedInfo2()))
{
Log.v("S1", number.getSharedInfo1());
Log.v("S2", number.getSharedInfo2());
/*
* Set the initiator flag since this user is starting the key exchange.
*/
number.setInitiator(true);
MessageService.dba.updateInitiator(number);
String keyExchangeMessage = KeyExchange.sign(number);
MessageService.dba.addMessageToQueue(number.getNumber(), keyExchangeMessage, true);
}
else
{
invalid = true;
//Toast.makeText(c, "Invalid shared secrets", Toast.LENGTH_LONG).show();
Log.v("Shared Secret", "Invalid shared secrets");
}
}
}
if (invalid)
{
trustedContact = MessageService.dba.getRow(number.getNumber());
/*
* Get the shared secrets from the user.
*/
activity.runOnUiThread(new Runnable() {
public void run() {
if(!multiNumber)
{
//Toast.makeText(activity, "Shared secrets must be set prior to key exchange", Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LinearLayout linearLayout = new LinearLayout(activity);
linearLayout.setOrientation(LinearLayout.VERTICAL);
final EditText sharedSecret1 = new EditText(activity);
sharedSecret1.setHint(R.string.shared_secret_hint_1);
sharedSecret1.setMaxLines(EditNumber.SHARED_INFO_MAX);
sharedSecret1.setInputType(InputType.TYPE_CLASS_TEXT);
linearLayout.addView(sharedSecret1);
final EditText sharedSecret2 = new EditText(activity);
- sharedSecret2.setHint(R.string.shared_secret_hint_1);
+ sharedSecret2.setHint(R.string.shared_secret_hint_2);
sharedSecret2.setMaxLines(EditNumber.SHARED_INFO_MAX);
sharedSecret2.setInputType(InputType.TYPE_CLASS_TEXT);
linearLayout.addView(sharedSecret2);
builder.setMessage(activity.getString(R.string.set_shared_secrets)
+ " " + trustedContact.getName() + ", " + number.getNumber())
.setCancelable(true)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Save the shared secrets
String s1 = sharedSecret1.getText().toString();
String s2 = sharedSecret2.getText().toString();
if(s1 != null && s2 != null &&
s1.length() >= EditNumber.SHARED_INFO_MIN &&
s2.length() >= EditNumber.SHARED_INFO_MIN)
{
//Toast.makeText(activity, "Valid secrets", Toast.LENGTH_LONG).show();
number.setSharedInfo1(s1);
number.setSharedInfo2(s2);
MessageService.dba.updateNumberRow(number, number.getNumber(), number.getId());
number.setInitiator(true);
MessageService.dba.updateInitiator(number);
String keyExchangeMessage = KeyExchange.sign(number);
MessageService.dba.addMessageToQueue(number.getNumber(), keyExchangeMessage, true);
}
else
{
Toast.makeText(activity, R.string.invalid_secrets, Toast.LENGTH_LONG).show();
}
}})
.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
//Cancel the key exchange
Toast.makeText(activity, R.string.key_exchange_cancelled, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//Cancel the key exchange
Toast.makeText(activity, R.string.key_exchange_cancelled, Toast.LENGTH_LONG).show();
}});
AlertDialog alert = builder.create();
alert.setView(linearLayout);
alert.show();
}
else
{
Toast.makeText(activity, R.string.unsuccessful_key_exchanges, Toast.LENGTH_LONG).show();
}
}
});
}
//Dismisses the load dialog since the load is finished
//keyDialog.dismiss();
}
}
| true | true | public void run() {
/*
* Used by ManageContacts Activity to determine from the
* contacts that have been selected need to exchange keys or
* stop sending secure messages
*/
if (this.trusted == null && this.untrusted == null)
{
this.trusted = new ArrayList<String>();
this.untrusted = new ArrayList<String>();
for (int i = 0; i < this.contacts.size(); i++)
{
for (int j = 0; j < this.contacts.get(i).getNumbers().size(); j++)
{
if (this.contacts.get(i).getNumber(j).isSelected())
{
if (!this.contacts.get(i).getNumber(j).isTrusted())
{
this.trusted.add(this.contacts.get(i).getNumber(j).getNumber());
}
else
{
this.untrusted.add(this.contacts.get(i).getNumber(j).getNumber());
}
}
}
}
}
/*
* This is actually how removing contacts from trusted should look since it is just a
* deletion of keys. We don't care if the contact will now fail to decrypt messages that
* is the user's problem
*/
if (this.untrusted != null)
{
for (int i = 0; i < this.untrusted.size(); i++)
{
//untrusted.get(i).clearPublicKey();
this.number = MessageService.dba.getNumber(this.untrusted.get(i));
this.number.clearPublicKey();
//set the initiator flag to false
this.number.setInitiator(false);
MessageService.dba.updateKey(this.number);
}
}
/*
* Start Key exchanges 1 by 1, messages are prepared and then placed in
* the messaging queue.
*/
boolean invalid = false;
if (this.trusted != null)
{
for (int i = 0; i < this.trusted.size(); i++)
{
number = MessageService.dba.getNumber(trusted.get(i));
if (SMSUtility.checksharedSecret(number.getSharedInfo1()) &&
SMSUtility.checksharedSecret(number.getSharedInfo2()))
{
Log.v("S1", number.getSharedInfo1());
Log.v("S2", number.getSharedInfo2());
/*
* Set the initiator flag since this user is starting the key exchange.
*/
number.setInitiator(true);
MessageService.dba.updateInitiator(number);
String keyExchangeMessage = KeyExchange.sign(number);
MessageService.dba.addMessageToQueue(number.getNumber(), keyExchangeMessage, true);
}
else
{
invalid = true;
//Toast.makeText(c, "Invalid shared secrets", Toast.LENGTH_LONG).show();
Log.v("Shared Secret", "Invalid shared secrets");
}
}
}
if (invalid)
{
trustedContact = MessageService.dba.getRow(number.getNumber());
/*
* Get the shared secrets from the user.
*/
activity.runOnUiThread(new Runnable() {
public void run() {
if(!multiNumber)
{
//Toast.makeText(activity, "Shared secrets must be set prior to key exchange", Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LinearLayout linearLayout = new LinearLayout(activity);
linearLayout.setOrientation(LinearLayout.VERTICAL);
final EditText sharedSecret1 = new EditText(activity);
sharedSecret1.setHint(R.string.shared_secret_hint_1);
sharedSecret1.setMaxLines(EditNumber.SHARED_INFO_MAX);
sharedSecret1.setInputType(InputType.TYPE_CLASS_TEXT);
linearLayout.addView(sharedSecret1);
final EditText sharedSecret2 = new EditText(activity);
sharedSecret2.setHint(R.string.shared_secret_hint_1);
sharedSecret2.setMaxLines(EditNumber.SHARED_INFO_MAX);
sharedSecret2.setInputType(InputType.TYPE_CLASS_TEXT);
linearLayout.addView(sharedSecret2);
builder.setMessage(activity.getString(R.string.set_shared_secrets)
+ " " + trustedContact.getName() + ", " + number.getNumber())
.setCancelable(true)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Save the shared secrets
String s1 = sharedSecret1.getText().toString();
String s2 = sharedSecret2.getText().toString();
if(s1 != null && s2 != null &&
s1.length() >= EditNumber.SHARED_INFO_MIN &&
s2.length() >= EditNumber.SHARED_INFO_MIN)
{
//Toast.makeText(activity, "Valid secrets", Toast.LENGTH_LONG).show();
number.setSharedInfo1(s1);
number.setSharedInfo2(s2);
MessageService.dba.updateNumberRow(number, number.getNumber(), number.getId());
number.setInitiator(true);
MessageService.dba.updateInitiator(number);
String keyExchangeMessage = KeyExchange.sign(number);
MessageService.dba.addMessageToQueue(number.getNumber(), keyExchangeMessage, true);
}
else
{
Toast.makeText(activity, R.string.invalid_secrets, Toast.LENGTH_LONG).show();
}
}})
.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
//Cancel the key exchange
Toast.makeText(activity, R.string.key_exchange_cancelled, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//Cancel the key exchange
Toast.makeText(activity, R.string.key_exchange_cancelled, Toast.LENGTH_LONG).show();
}});
AlertDialog alert = builder.create();
alert.setView(linearLayout);
alert.show();
}
else
{
Toast.makeText(activity, R.string.unsuccessful_key_exchanges, Toast.LENGTH_LONG).show();
}
}
});
}
//Dismisses the load dialog since the load is finished
//keyDialog.dismiss();
}
| public void run() {
/*
* Used by ManageContacts Activity to determine from the
* contacts that have been selected need to exchange keys or
* stop sending secure messages
*/
if (this.trusted == null && this.untrusted == null)
{
this.trusted = new ArrayList<String>();
this.untrusted = new ArrayList<String>();
for (int i = 0; i < this.contacts.size(); i++)
{
for (int j = 0; j < this.contacts.get(i).getNumbers().size(); j++)
{
if (this.contacts.get(i).getNumber(j).isSelected())
{
if (!this.contacts.get(i).getNumber(j).isTrusted())
{
this.trusted.add(this.contacts.get(i).getNumber(j).getNumber());
}
else
{
this.untrusted.add(this.contacts.get(i).getNumber(j).getNumber());
}
}
}
}
}
/*
* This is actually how removing contacts from trusted should look since it is just a
* deletion of keys. We don't care if the contact will now fail to decrypt messages that
* is the user's problem
*/
if (this.untrusted != null)
{
for (int i = 0; i < this.untrusted.size(); i++)
{
//untrusted.get(i).clearPublicKey();
this.number = MessageService.dba.getNumber(this.untrusted.get(i));
this.number.clearPublicKey();
//set the initiator flag to false
this.number.setInitiator(false);
MessageService.dba.updateKey(this.number);
}
}
/*
* Start Key exchanges 1 by 1, messages are prepared and then placed in
* the messaging queue.
*/
boolean invalid = false;
if (this.trusted != null)
{
for (int i = 0; i < this.trusted.size(); i++)
{
number = MessageService.dba.getNumber(trusted.get(i));
if (SMSUtility.checksharedSecret(number.getSharedInfo1()) &&
SMSUtility.checksharedSecret(number.getSharedInfo2()))
{
Log.v("S1", number.getSharedInfo1());
Log.v("S2", number.getSharedInfo2());
/*
* Set the initiator flag since this user is starting the key exchange.
*/
number.setInitiator(true);
MessageService.dba.updateInitiator(number);
String keyExchangeMessage = KeyExchange.sign(number);
MessageService.dba.addMessageToQueue(number.getNumber(), keyExchangeMessage, true);
}
else
{
invalid = true;
//Toast.makeText(c, "Invalid shared secrets", Toast.LENGTH_LONG).show();
Log.v("Shared Secret", "Invalid shared secrets");
}
}
}
if (invalid)
{
trustedContact = MessageService.dba.getRow(number.getNumber());
/*
* Get the shared secrets from the user.
*/
activity.runOnUiThread(new Runnable() {
public void run() {
if(!multiNumber)
{
//Toast.makeText(activity, "Shared secrets must be set prior to key exchange", Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LinearLayout linearLayout = new LinearLayout(activity);
linearLayout.setOrientation(LinearLayout.VERTICAL);
final EditText sharedSecret1 = new EditText(activity);
sharedSecret1.setHint(R.string.shared_secret_hint_1);
sharedSecret1.setMaxLines(EditNumber.SHARED_INFO_MAX);
sharedSecret1.setInputType(InputType.TYPE_CLASS_TEXT);
linearLayout.addView(sharedSecret1);
final EditText sharedSecret2 = new EditText(activity);
sharedSecret2.setHint(R.string.shared_secret_hint_2);
sharedSecret2.setMaxLines(EditNumber.SHARED_INFO_MAX);
sharedSecret2.setInputType(InputType.TYPE_CLASS_TEXT);
linearLayout.addView(sharedSecret2);
builder.setMessage(activity.getString(R.string.set_shared_secrets)
+ " " + trustedContact.getName() + ", " + number.getNumber())
.setCancelable(true)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Save the shared secrets
String s1 = sharedSecret1.getText().toString();
String s2 = sharedSecret2.getText().toString();
if(s1 != null && s2 != null &&
s1.length() >= EditNumber.SHARED_INFO_MIN &&
s2.length() >= EditNumber.SHARED_INFO_MIN)
{
//Toast.makeText(activity, "Valid secrets", Toast.LENGTH_LONG).show();
number.setSharedInfo1(s1);
number.setSharedInfo2(s2);
MessageService.dba.updateNumberRow(number, number.getNumber(), number.getId());
number.setInitiator(true);
MessageService.dba.updateInitiator(number);
String keyExchangeMessage = KeyExchange.sign(number);
MessageService.dba.addMessageToQueue(number.getNumber(), keyExchangeMessage, true);
}
else
{
Toast.makeText(activity, R.string.invalid_secrets, Toast.LENGTH_LONG).show();
}
}})
.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
//Cancel the key exchange
Toast.makeText(activity, R.string.key_exchange_cancelled, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//Cancel the key exchange
Toast.makeText(activity, R.string.key_exchange_cancelled, Toast.LENGTH_LONG).show();
}});
AlertDialog alert = builder.create();
alert.setView(linearLayout);
alert.show();
}
else
{
Toast.makeText(activity, R.string.unsuccessful_key_exchanges, Toast.LENGTH_LONG).show();
}
}
});
}
//Dismisses the load dialog since the load is finished
//keyDialog.dismiss();
}
|
diff --git a/assets/src/org/ruboto/Script.java b/assets/src/org/ruboto/Script.java
index c2c7343..3c19a6d 100644
--- a/assets/src/org/ruboto/Script.java
+++ b/assets/src/org/ruboto/Script.java
@@ -1,498 +1,497 @@
package org.ruboto;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import dalvik.system.PathClassLoader;
public class Script {
private static String scriptsDir = "scripts";
private static File scriptsDirFile = null;
private String name = null;
private static Object ruby;
private static boolean initialized = false;
private String contents = null;
public static final String TAG = "RUBOTO"; // for logging
private static String JRUBY_VERSION;
/*************************************************************************************************
*
* Static Methods: JRuby Execution
*/
public static final FilenameFilter RUBY_FILES = new FilenameFilter() {
public boolean accept(File dir, String fname) {
return fname.endsWith(".rb");
}
};
public static boolean isInitialized() {
return initialized;
}
public static synchronized boolean setUpJRuby(Context appContext) {
return setUpJRuby(appContext, System.out);
}
public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) {
if (ruby == null) {
Log.d(TAG, "Setting up JRuby runtime");
System.setProperty("jruby.bytecode.version", "1.5");
System.setProperty("jruby.interfaces.useProxy", "true");
System.setProperty("jruby.management.enabled", "false");
ClassLoader classLoader;
Class<?> scriptingContainerClass;
try {
scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer");
System.out.println("Found JRuby in this APK");
classLoader = Script.class.getClassLoader();
} catch (ClassNotFoundException e1) {
String packagePath = "org.ruboto.core";
String apkName = null;
try {
apkName = appContext.getPackageManager().getApplicationInfo(packagePath, 0).sourceDir;
} catch (PackageManager.NameNotFoundException e) {
System.out.println("JRuby not found");
return false;
}
System.out.println("Found JRuby in platform APK");
classLoader = new PathClassLoader(apkName, Script.class.getClassLoader());
try {
scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader);
} catch (ClassNotFoundException e) {
// FIXME(uwe): ScriptingContainer not found in the platform APK...
e.printStackTrace();
return false;
}
}
try {
try {
JRUBY_VERSION = (String) Class.forName("org.jruby.runtime.Constants", true, classLoader).getDeclaredField("VERSION").get(String.class);
} catch (java.lang.NoSuchFieldException nsfex) {
nsfex.printStackTrace();
JRUBY_VERSION = "ERROR";
}
ruby = scriptingContainerClass.getConstructor().newInstance();
- Class<?> compileModeClass = Class
- .forName("org.jruby.RubyInstanceConfig$CompileMode", true, classLoader);
- callScriptingContainerMethod(Void.class, "setCompileMode", compileModeClass.getEnumConstants()[2]);
+ Class compileModeClass = Class.forName("org.jruby.RubyInstanceConfig$CompileMode", true, classLoader);
+ callScriptingContainerMethod(Void.class, "setCompileMode", Enum.valueOf(compileModeClass, "OFF"));
// callScriptingContainerMethod(Void.class, "setClassLoader", classLoader);
Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class);
setClassLoaderMethod.invoke(ruby, classLoader);
Thread.currentThread().setContextClassLoader(classLoader);
if (scriptsDir != null) {
Log.d(TAG, "Setting JRuby current directory to " + scriptsDir);
callScriptingContainerMethod(Void.class, "setCurrentDirectory", scriptsDir);
}
if (out != null) {
// callScriptingContainerMethod(Void.class, "setOutput", out);
Method setOutputMethod = ruby.getClass().getMethod("setOutput", PrintStream.class);
setOutputMethod.invoke(ruby, out);
// callScriptingContainerMethod(Void.class, "setError", out);
Method setErrorMethod = ruby.getClass().getMethod("setError", PrintStream.class);
setErrorMethod.invoke(ruby, out);
}
String extraScriptsDir = scriptsDirName(appContext);
Log.i(TAG, "Checking scripts in " + extraScriptsDir);
if (configDir(extraScriptsDir)) {
Log.i(TAG, "Added extra scripts path: " + extraScriptsDir);
}
initialized = true;
return true;
} catch (ClassNotFoundException e) {
// FIXME(uwe): ScriptingContainer not found in the platform APK...
e.printStackTrace();
} catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
+ Log.e(TAG, "IllegalArgumentException starting JRuby: " + e.getMessage());
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
} else {
while (!initialized) {
Log.i(TAG, "Waiting for JRuby runtime to initialize.");
try {
Thread.sleep(1000);
} catch (InterruptedException iex) {
}
}
}
return true;
}
@SuppressWarnings("unchecked")
public static <T> T callScriptingContainerMethod(Class<T> returnType, String methodName, Object... args) {
Class<?>[] argClasses = new Class[args.length];
for (int i = 0; i < argClasses.length; i++) {
argClasses[i] = args[i].getClass();
}
try {
Method method = ruby.getClass().getMethod(methodName, argClasses);
System.out.println("callScriptingContainerMethod: method: " + method);
T result = (T) method.invoke(ruby, args);
System.out.println("callScriptingContainerMethod: result: " + result);
return result;
} catch (RuntimeException re) {
re.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
try {
e.printStackTrace();
} catch (NullPointerException npe) {
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String execute(String code) {
try {
Object result = exec(code);
return result != null ? callMethod(result, "inspect", String.class) : "null";
} catch (RuntimeException re) {
// System.err.println(re.getMessage());
re.printStackTrace();
return null;
}
}
public static Object exec(String code) {
return callScriptingContainerMethod(Object.class, "runScriptlet", code);
}
public static void defineGlobalConstant(String name, Object object) {
put(name, object);
}
public static void put(String name, Object object) {
// callScriptingContainerMethod(Void.class, "put", name, object);
try {
Method putMethod = ruby.getClass().getMethod("put", String.class, Object.class);
putMethod.invoke(ruby, name, object);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae);
} catch (java.lang.reflect.InvocationTargetException ite) {
throw new RuntimeException(ite);
}
}
public static void defineGlobalVariable(String name, Object object) {
defineGlobalConstant(name, object);
}
/*************************************************************************************************
*
* Static Methods: Scripts Directory
*/
public static void setDir(String dir) {
scriptsDir = dir;
scriptsDirFile = new File(dir);
if (ruby != null) {
Log.d(TAG, "Changing JRuby current directory to " + scriptsDir);
callScriptingContainerMethod(Void.class, "setCurrentDirectory", scriptsDir);
}
}
public static String getDir() {
return scriptsDir;
}
public static File getDirFile() {
return scriptsDirFile;
}
public static Boolean configDir(String noSdcard) {
setDir(noSdcard);
Method getLoadPathsMethod;
List<String> loadPath = callScriptingContainerMethod(List.class, "getLoadPaths");
if (!loadPath.contains(noSdcard)) {
Log.i(TAG, "Adding scripts dir to load path: " + noSdcard);
List<String> paths = loadPath;
paths.add(noSdcard);
// callScriptingContainerMethod(Void.class, "setLoadPaths", paths);
try {
Method setLoadPathsMethod = ruby.getClass().getMethod("setLoadPaths", List.class);
setLoadPathsMethod.invoke(ruby, paths);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae);
} catch (java.lang.reflect.InvocationTargetException ite) {
throw new RuntimeException(ite);
}
}
/* Create directory if it doesn't exist */
if (!scriptsDirFile.exists()) {
boolean dirCreatedOk = scriptsDirFile.mkdirs();
if (!dirCreatedOk) {
throw new RuntimeException("Unable to create script directory");
}
return true;
}
return false;
}
private static void copyScripts(String from, File to, AssetManager assets) {
try {
byte[] buffer = new byte[8192];
for (String f : assets.list(from)) {
File dest = new File(to, f);
if (dest.exists()) {
continue;
}
Log.d(TAG, "copying file from " + from + "/" + f + " to " + dest);
if (assets.list(from + "/" + f).length == 0) {
InputStream is = assets.open(from + "/" + f);
OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest), 8192);
int n;
while ((n = is.read(buffer, 0, buffer.length)) != -1) {
fos.write(buffer, 0, n);
}
is.close();
fos.close();
} else {
dest.mkdir();
copyScripts(from + "/" + f, dest, assets);
}
}
} catch (IOException iox) {
Log.e(TAG, "error copying scripts", iox);
}
}
public static void copyAssets(Context context, String directory) {
File dest = new File(scriptsDirFile.getParentFile(), directory);
if (dest.exists() || dest.mkdir()) {
copyScripts(directory, dest, context.getAssets());
} else {
throw new RuntimeException("Unable to create scripts directory: " + dest);
}
}
private static boolean isDebugBuild(Context context) {
PackageManager pm = context.getPackageManager();
PackageInfo pi;
try {
pi = pm.getPackageInfo(context.getPackageName(), 0);
return ((pi.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
} catch (NameNotFoundException e) {
return false;
}
}
private static String scriptsDirName(Context context) {
File storageDir = null;
if (isDebugBuild(context)) {
// FIXME(uwe): Simplify this as soon as we drop support for android-7 or JRuby 1.5.6 or JRuby 1.6.2
Log.i(TAG, "JRuby VERSION: " + JRUBY_VERSION);
if (!JRUBY_VERSION.equals("1.5.6") && !JRUBY_VERSION.equals("1.6.2") && android.os.Build.VERSION.SDK_INT >= 8) {
put("script_context", context);
storageDir = (File) exec("script_context.getExternalFilesDir(nil)");
} else {
storageDir = new File(Environment.getExternalStorageDirectory(), "Android/data/" + context.getPackageName() + "/files");
Log.e(TAG, "Calculated path to sdcard the old way: " + storageDir);
}
// FIXME end
if (storageDir == null || (!storageDir.exists() && !storageDir.mkdirs())) {
Log.e(TAG,
"Development mode active, but sdcard is not available. Make sure you have added\n<uses-permission android:name='android.permission.WRITE_EXTERNAL_STORAGE' />\nto your AndroidManifest.xml file.");
storageDir = context.getFilesDir();
}
} else {
storageDir = context.getFilesDir();
}
return storageDir.getAbsolutePath() + "/scripts";
}
private static void copyScriptsIfNeeded(Context context) {
String to = scriptsDirName(context);
Log.i(TAG, "Checking scripts in "
+ to);
/* the if makes sure we only do this the first time */
if (configDir(to)) {
Log.i(TAG, "Copying scripts to " + to);
copyAssets(context, "scripts");
}
}
/*************************************************************************************************
*
* Constructors
*/
public Script(String name) {
this(name, null);
}
public Script(String name, String contents) {
this.name = name;
this.contents = contents;
}
/*************************************************************************************************
*
* Attribute Access
*/
public String getName() {
return name;
}
public File getFile() {
return new File(getDir(), name);
}
public Script setName(String name) {
this.name = name;
// TODO: Other states possible
return this;
}
public String getContents() throws IOException {
BufferedReader buffer = new BufferedReader(new FileReader(getFile()), 8192);
StringBuilder source = new StringBuilder();
while (true) {
String line = buffer.readLine();
if (line == null) {
break;
}
source.append(line).append("\n");
}
buffer.close();
contents = source.toString();
return contents;
}
/*************************************************************************************************
*
* Script Actions
*/
public static String getScriptFilename() {
return callScriptingContainerMethod(String.class, "getScriptFilename");
}
public static void setScriptFilename(String name) {
callScriptingContainerMethod(Void.class, "setScriptFilename", name);
}
public String execute() throws IOException {
setScriptFilename(name);
return Script.execute("load '" + name + "'");
}
public static void callMethod(Object receiver, String methodName, Object[] args) {
// callScriptingContainerMethod(Void.class, "callMethod", receiver, methodName, args);
try {
Method callMethodMethod = ruby.getClass().getMethod("callMethod", Object.class, String.class, Object[].class);
callMethodMethod.invoke(ruby, receiver, methodName, args);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae);
} catch (java.lang.reflect.InvocationTargetException ite) {
throw new RuntimeException(ite);
}
}
public static void callMethod(Object object, String methodName, Object arg) {
callMethod(object, methodName, new Object[] { arg });
}
public static void callMethod(Object object, String methodName) {
callMethod(object, methodName, new Object[] {});
}
@SuppressWarnings("unchecked")
public static <T> T callMethod(Object receiver, String methodName, Object[] args, Class<T> returnType) {
// return callScriptingContainerMethod(returnType, "callMethod", receiver, methodName, args, returnType);
try {
Method callMethodMethod = ruby.getClass().getMethod("callMethod", Object.class, String.class, Object[].class, Class.class);
return (T) callMethodMethod.invoke(ruby, receiver, methodName, args, returnType);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae);
} catch (java.lang.reflect.InvocationTargetException ite) {
throw new RuntimeException(ite);
}
}
public static <T> T callMethod(Object receiver, String methodName,
Object arg, Class<T> returnType) {
return callMethod(receiver, methodName, new Object[]{arg}, returnType);
}
public static <T> T callMethod(Object receiver, String methodName,
Class<T> returnType) {
return callMethod(receiver, methodName, new Object[]{}, returnType);
}
}
| false | true | public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) {
if (ruby == null) {
Log.d(TAG, "Setting up JRuby runtime");
System.setProperty("jruby.bytecode.version", "1.5");
System.setProperty("jruby.interfaces.useProxy", "true");
System.setProperty("jruby.management.enabled", "false");
ClassLoader classLoader;
Class<?> scriptingContainerClass;
try {
scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer");
System.out.println("Found JRuby in this APK");
classLoader = Script.class.getClassLoader();
} catch (ClassNotFoundException e1) {
String packagePath = "org.ruboto.core";
String apkName = null;
try {
apkName = appContext.getPackageManager().getApplicationInfo(packagePath, 0).sourceDir;
} catch (PackageManager.NameNotFoundException e) {
System.out.println("JRuby not found");
return false;
}
System.out.println("Found JRuby in platform APK");
classLoader = new PathClassLoader(apkName, Script.class.getClassLoader());
try {
scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader);
} catch (ClassNotFoundException e) {
// FIXME(uwe): ScriptingContainer not found in the platform APK...
e.printStackTrace();
return false;
}
}
try {
try {
JRUBY_VERSION = (String) Class.forName("org.jruby.runtime.Constants", true, classLoader).getDeclaredField("VERSION").get(String.class);
} catch (java.lang.NoSuchFieldException nsfex) {
nsfex.printStackTrace();
JRUBY_VERSION = "ERROR";
}
ruby = scriptingContainerClass.getConstructor().newInstance();
Class<?> compileModeClass = Class
.forName("org.jruby.RubyInstanceConfig$CompileMode", true, classLoader);
callScriptingContainerMethod(Void.class, "setCompileMode", compileModeClass.getEnumConstants()[2]);
// callScriptingContainerMethod(Void.class, "setClassLoader", classLoader);
Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class);
setClassLoaderMethod.invoke(ruby, classLoader);
Thread.currentThread().setContextClassLoader(classLoader);
if (scriptsDir != null) {
Log.d(TAG, "Setting JRuby current directory to " + scriptsDir);
callScriptingContainerMethod(Void.class, "setCurrentDirectory", scriptsDir);
}
if (out != null) {
// callScriptingContainerMethod(Void.class, "setOutput", out);
Method setOutputMethod = ruby.getClass().getMethod("setOutput", PrintStream.class);
setOutputMethod.invoke(ruby, out);
// callScriptingContainerMethod(Void.class, "setError", out);
Method setErrorMethod = ruby.getClass().getMethod("setError", PrintStream.class);
setErrorMethod.invoke(ruby, out);
}
String extraScriptsDir = scriptsDirName(appContext);
Log.i(TAG, "Checking scripts in " + extraScriptsDir);
if (configDir(extraScriptsDir)) {
Log.i(TAG, "Added extra scripts path: " + extraScriptsDir);
}
initialized = true;
return true;
} catch (ClassNotFoundException e) {
// FIXME(uwe): ScriptingContainer not found in the platform APK...
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
} else {
while (!initialized) {
Log.i(TAG, "Waiting for JRuby runtime to initialize.");
try {
Thread.sleep(1000);
} catch (InterruptedException iex) {
}
}
}
return true;
}
| public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) {
if (ruby == null) {
Log.d(TAG, "Setting up JRuby runtime");
System.setProperty("jruby.bytecode.version", "1.5");
System.setProperty("jruby.interfaces.useProxy", "true");
System.setProperty("jruby.management.enabled", "false");
ClassLoader classLoader;
Class<?> scriptingContainerClass;
try {
scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer");
System.out.println("Found JRuby in this APK");
classLoader = Script.class.getClassLoader();
} catch (ClassNotFoundException e1) {
String packagePath = "org.ruboto.core";
String apkName = null;
try {
apkName = appContext.getPackageManager().getApplicationInfo(packagePath, 0).sourceDir;
} catch (PackageManager.NameNotFoundException e) {
System.out.println("JRuby not found");
return false;
}
System.out.println("Found JRuby in platform APK");
classLoader = new PathClassLoader(apkName, Script.class.getClassLoader());
try {
scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader);
} catch (ClassNotFoundException e) {
// FIXME(uwe): ScriptingContainer not found in the platform APK...
e.printStackTrace();
return false;
}
}
try {
try {
JRUBY_VERSION = (String) Class.forName("org.jruby.runtime.Constants", true, classLoader).getDeclaredField("VERSION").get(String.class);
} catch (java.lang.NoSuchFieldException nsfex) {
nsfex.printStackTrace();
JRUBY_VERSION = "ERROR";
}
ruby = scriptingContainerClass.getConstructor().newInstance();
Class compileModeClass = Class.forName("org.jruby.RubyInstanceConfig$CompileMode", true, classLoader);
callScriptingContainerMethod(Void.class, "setCompileMode", Enum.valueOf(compileModeClass, "OFF"));
// callScriptingContainerMethod(Void.class, "setClassLoader", classLoader);
Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class);
setClassLoaderMethod.invoke(ruby, classLoader);
Thread.currentThread().setContextClassLoader(classLoader);
if (scriptsDir != null) {
Log.d(TAG, "Setting JRuby current directory to " + scriptsDir);
callScriptingContainerMethod(Void.class, "setCurrentDirectory", scriptsDir);
}
if (out != null) {
// callScriptingContainerMethod(Void.class, "setOutput", out);
Method setOutputMethod = ruby.getClass().getMethod("setOutput", PrintStream.class);
setOutputMethod.invoke(ruby, out);
// callScriptingContainerMethod(Void.class, "setError", out);
Method setErrorMethod = ruby.getClass().getMethod("setError", PrintStream.class);
setErrorMethod.invoke(ruby, out);
}
String extraScriptsDir = scriptsDirName(appContext);
Log.i(TAG, "Checking scripts in " + extraScriptsDir);
if (configDir(extraScriptsDir)) {
Log.i(TAG, "Added extra scripts path: " + extraScriptsDir);
}
initialized = true;
return true;
} catch (ClassNotFoundException e) {
// FIXME(uwe): ScriptingContainer not found in the platform APK...
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.e(TAG, "IllegalArgumentException starting JRuby: " + e.getMessage());
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
} else {
while (!initialized) {
Log.i(TAG, "Waiting for JRuby runtime to initialize.");
try {
Thread.sleep(1000);
} catch (InterruptedException iex) {
}
}
}
return true;
}
|
diff --git a/src/com/dunksoftware/seminoletix/ListActivity.java b/src/com/dunksoftware/seminoletix/ListActivity.java
index cd6f4f1..890d1c8 100644
--- a/src/com/dunksoftware/seminoletix/ListActivity.java
+++ b/src/com/dunksoftware/seminoletix/ListActivity.java
@@ -1,517 +1,516 @@
package com.dunksoftware.seminoletix;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("DefaultLocale")
public class ListActivity extends Activity {
public static String userName = "";
private JSONObject[] GameObjects = null;
private JSONArray gamesArray = null;
private AdditionDetailsListener mDetailsListener = null;
private GetGames games;
private GetCurrentUser getCurrentUser;
private String response = "ERROR!";
/*
* A variable that lets functions know which game has been inquired
* about. When a "More details" button is clicked, that JSONArray element
* location will be recorded into this variable. ( -1 is default value )
*/
private int inquiredGame = -1;
private String homeTeam,
awayTeam,
sportType,
date,
selectedGameID;
CharSequence finalDetailString;
private int remainingSeats = 0;
private TableLayout mainTable;
private final int MESSAGE = 200,
DETAILS_POPUP = 250,
NO_MORE_SEATS_POPUP = 300;
@SuppressLint("DefaultLocale")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
TextView welcomeMsg = (TextView)findViewById(R.id.UI_GreetingText);
// set up logout button
((Button)findViewById(R.id.UI_LogoutBtn)).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
UserControl UC = new UserControl();
UserControl.Logout logout = UC.new Logout();
// begin the logout process
logout.execute();
// wait for the server's results
try {
JSONObject json = new JSONObject(logout.get());
String message = json.getString("success");
// check to see if user has successfully logged out
if(message.equals("true")) {
Toast.makeText(getApplicationContext(),
"You have been logged out.", Toast.LENGTH_LONG)
.show();
}
else {
Toast.makeText(getApplicationContext(),
"You are not logged in.", Toast.LENGTH_LONG)
.show();
- finish();
}
finish();
startActivity(new Intent(getApplicationContext(),
LoginActivity.class));
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
homeTeam = awayTeam = sportType = date = "";
// general initialization
mainTable = (TableLayout)findViewById(R.id.UI_MainTableLayout);
mDetailsListener = new AdditionDetailsListener();
// get the name of the user that is currently logged in
getCurrentUser = new GetCurrentUser();
getCurrentUser.execute();
try {
JSONObject userInfoObject = new JSONObject(getCurrentUser.get());
userName = userInfoObject.getJSONObject("name").getString("first")
+ " " +
userInfoObject.getJSONObject("name").getString("last");
String constructHeader = "Welcome, " + userName;
welcomeMsg.setText(constructHeader);
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
games = new GetGames();
try {
games.execute();
response = games.get();
// Show the pop-up box (for display testing)
//showDialog(MESSAGE);
gamesArray = new JSONArray(response);
// Allocate space for all JSON objects embedded in the JSON array
GameObjects = new JSONObject[gamesArray.length()];
// Transfer each object in this JSONArray into its own object
for(int i=0;i<gamesArray.length();i++)
GameObjects[i] = gamesArray.getJSONObject(i);
/*
* give every game a button for displaying additional
* details about that game. (This button will also be
* used to register for games
*/
Button[] detailsButtons =
new Button[ gamesArray.length()];
for(int i = 0; i < gamesArray.length(); i++) {
TableRow gameTableRow = new TableRow(this);
LinearLayout list = new LinearLayout(this);
// Initialize each button and give it a reference id (i)
detailsButtons[i] = new Button(this);
detailsButtons[i].setText("More Details");
detailsButtons[i].setId(i);
detailsButtons[i].setOnClickListener(mDetailsListener);
TextView[] info = new TextView[4];
// set the list to a top down look
list.setOrientation(LinearLayout.VERTICAL);
info[0] = new TextView(this);
info[0].setText("\tSport:\t\t" + GameObjects[i].getString("sport"));
list.addView(info[0]);
info[1] = new TextView(this);
//Format the date so that it is appropriate
String dateTime = GameObjects[i].getString("date");
String date = FormatDate(dateTime);
info[1].setText("\tGame Date:\t\t" + date);
list.addView(info[1]);
info[2] = new TextView(this);
info[2].setText("\tHome Team:\t\t" + GameObjects[i].getJSONObject("teams")
.getString("home").toUpperCase());
list.addView(info[2]);
info[3] = new TextView(this);
info[3].setText("\tAgainst:\t\t" + GameObjects[i].getJSONObject("teams")
.getString("away").toUpperCase());
list.addView(info[3]);
// add the button to the display details for each game
// might have to add tag to button
list.addView(detailsButtons[i]);
list.setPadding(0, 5, 0, 20);
gameTableRow.addView(list);
gameTableRow.setBackgroundResource(R.drawable.img_gloss_background);
mainTable.addView(gameTableRow);
}
} catch(InterruptedException ex) {
Log.w("List Activity - mGetTable.execute()", ex.getMessage());
} catch(ExecutionException ex) {
Log.w("List Activity - mGetTable.execute()", ex.getMessage());
} catch (JSONException e) {
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
String FormatDate(String Date) {
String[] splits = Date.split("T");
splits = splits[0].split("-");
Date d = new Date(Integer.parseInt(splits[0]) - 1900,
Integer.parseInt(splits[1]), Integer.parseInt(splits[2]));
DateFormat newDate = DateFormat.getDateInstance(DateFormat.LONG);
newDate.format(d);
return DateFormat.getDateInstance(DateFormat.LONG).format(d);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_list, menu);
return true;
}
@SuppressWarnings("deprecation")
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = null;
switch( id ) {
case MESSAGE: {
builder = new AlertDialog.
Builder(this);
builder.setCancelable(false).setTitle("Page Result").
setMessage(response).setNeutralButton("Close",
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/* onclick closes the dialog by default, unless code is
* added here
*/
}
});
break;
}
case DETAILS_POPUP:
builder = new AlertDialog.Builder(this);
// set up the URL for the map (map uses browser)
TextView mapURL = new TextView(this);
mapURL.setText(Html.fromHtml("<a href=http://tinyurl.com/bwvhpsv>" +
"<i>View a Map of the Stadium</i></a><br /><br />"));
mapURL.setTextSize(20);
// make URL active
mapURL.setMovementMethod(LinkMovementMethod.getInstance());
builder.setCancelable(false).setTitle(
Html.fromHtml("<b>Intramural Review Page</b>")).
setMessage(finalDetailString).setNeutralButton("Close",
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/* onclick closes the dialog by default, unless code is
* added here
*/
}
}).setPositiveButton("Reserve It!",
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*
* if all seats are gone, show error. Else, reserve
* the selected ticket
*
* (remaining seats was set in the "ShowDetails"
* function)
*/
if( remainingSeats == 0)
showDialog(NO_MORE_SEATS_POPUP);
else {
ReserveTicket reserve = new ReserveTicket();
reserve.execute(selectedGameID);
// navigate to the list of currently reserved tickets
startActivity(new Intent(getApplication(),
ShowGamesList.class));
}
}
}).setView(mapURL); // add link at the bottom
break;
case NO_MORE_SEATS_POPUP:
builder = new AlertDialog.Builder(this);
builder.setCancelable(false)
.setTitle("An Error Occurred During Reservation")
.setNeutralButton("Return to List", null)
.setMessage("It appears that no more seats are" +
" available at the moment.\n\nPlease choose" +
" another game.");
break;
}
if( builder != null) {
// now show the dialog box once it's completed
builder.create().show();
}
return super.onCreateDialog(id);
}
/**
* This function will set the data for the necessary variables
* needed to correctly display a details dialog box for the chosen
* game.
* @param gameIndex - Signifies which game (index) was chosen
*/
@SuppressWarnings("deprecation")
public void showDetails() {
// get the corresponding object for the desired game
JSONObject selectedGame = GameObjects[inquiredGame];
//set up the information variables
try {
selectedGameID = selectedGame.getString("_id");
homeTeam = selectedGame.getJSONObject("teams")
.getString("home");
awayTeam = selectedGame.getJSONObject("teams")
.getString("away");
sportType = selectedGame.getString("sport");
date = selectedGame.getString("date");
// format the date
date = FormatDate(date);
remainingSeats = selectedGame.getInt("seatsLeft");
} catch (JSONException e) {
e.printStackTrace();
}
// format the resulting info string using HTML :) (New skill acquired)
finalDetailString = Html.fromHtml(
"<img src=img_" + homeTeam + ">\t\t" +
"<b>V.S</b>\t\t" +
"<img src=img_" + awayTeam + "> " +
"<br />" + "<br />" +
"<b>Sport: </b>" + sportType +
"<br />" + "<br />" +
"<b>Seats Remaining: </b>" + remainingSeats +
"<br />" + "<br />" +
"<b>Event Date: </b>" + date
,new ImageGetter() {
@Override public Drawable getDrawable(String source) {
Drawable drawFromPath;
int path =
ListActivity.this.getResources().getIdentifier(source, "drawable",
"com.dunksoftware.seminoletix");
drawFromPath = (Drawable) ListActivity.this.getResources()
.getDrawable(path);
drawFromPath.setBounds(0, 0,
drawFromPath.getIntrinsicWidth(),
drawFromPath.getIntrinsicHeight());
return drawFromPath;
}
}, null);// link to map of game arena
showDialog(DETAILS_POPUP);
}
/**
* After determining what game was inquired about, this class
* will draw up a Dialog box that will give a full list of info
* concerning that game. After reviewing the terms of the game, users
* can either return to the list of games or reserve a ticket to the
* current game being viewed
*/
class AdditionDetailsListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Button btn_viewGame = (Button)v;
// find out which list array element was inquired about and set it
inquiredGame = btn_viewGame.getId();
showDetails();
}
}
class GetCurrentUser extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// Create a new HttpClient and Post Header
MyHttpClient client = new MyHttpClient(null);
//sets cookie
client.setCookieStore(UserControl.mCookie);
// Prepare a request object
HttpGet httpget = new HttpGet(Constants.CurrentUserAddress);
// Execute the request
HttpResponse response=null;
// return string
String returnString = null;
try {
// Open the web page.
response = client.execute(httpget);
returnString = EntityUtils.toString(response.getEntity());
}
catch (IOException ex) {
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
return returnString;
}
}
class GetGames extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// Create a new HttpClient and Post Header
MyHttpClient client=new MyHttpClient(null);
//sets cookie
client.setCookieStore(UserControl.mCookie);
// Prepare a request object
HttpGet httpget = new HttpGet(Constants.GamesAddress);
// Execute the request
HttpResponse response=null;
// return string
String returnString = null;
try {
// Open the web page.
response = client.execute(httpget);
returnString = EntityUtils.toString(response.getEntity());
}
catch (IOException ex) {
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
return returnString;
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
TextView welcomeMsg = (TextView)findViewById(R.id.UI_GreetingText);
// set up logout button
((Button)findViewById(R.id.UI_LogoutBtn)).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
UserControl UC = new UserControl();
UserControl.Logout logout = UC.new Logout();
// begin the logout process
logout.execute();
// wait for the server's results
try {
JSONObject json = new JSONObject(logout.get());
String message = json.getString("success");
// check to see if user has successfully logged out
if(message.equals("true")) {
Toast.makeText(getApplicationContext(),
"You have been logged out.", Toast.LENGTH_LONG)
.show();
}
else {
Toast.makeText(getApplicationContext(),
"You are not logged in.", Toast.LENGTH_LONG)
.show();
finish();
}
finish();
startActivity(new Intent(getApplicationContext(),
LoginActivity.class));
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
homeTeam = awayTeam = sportType = date = "";
// general initialization
mainTable = (TableLayout)findViewById(R.id.UI_MainTableLayout);
mDetailsListener = new AdditionDetailsListener();
// get the name of the user that is currently logged in
getCurrentUser = new GetCurrentUser();
getCurrentUser.execute();
try {
JSONObject userInfoObject = new JSONObject(getCurrentUser.get());
userName = userInfoObject.getJSONObject("name").getString("first")
+ " " +
userInfoObject.getJSONObject("name").getString("last");
String constructHeader = "Welcome, " + userName;
welcomeMsg.setText(constructHeader);
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
games = new GetGames();
try {
games.execute();
response = games.get();
// Show the pop-up box (for display testing)
//showDialog(MESSAGE);
gamesArray = new JSONArray(response);
// Allocate space for all JSON objects embedded in the JSON array
GameObjects = new JSONObject[gamesArray.length()];
// Transfer each object in this JSONArray into its own object
for(int i=0;i<gamesArray.length();i++)
GameObjects[i] = gamesArray.getJSONObject(i);
/*
* give every game a button for displaying additional
* details about that game. (This button will also be
* used to register for games
*/
Button[] detailsButtons =
new Button[ gamesArray.length()];
for(int i = 0; i < gamesArray.length(); i++) {
TableRow gameTableRow = new TableRow(this);
LinearLayout list = new LinearLayout(this);
// Initialize each button and give it a reference id (i)
detailsButtons[i] = new Button(this);
detailsButtons[i].setText("More Details");
detailsButtons[i].setId(i);
detailsButtons[i].setOnClickListener(mDetailsListener);
TextView[] info = new TextView[4];
// set the list to a top down look
list.setOrientation(LinearLayout.VERTICAL);
info[0] = new TextView(this);
info[0].setText("\tSport:\t\t" + GameObjects[i].getString("sport"));
list.addView(info[0]);
info[1] = new TextView(this);
//Format the date so that it is appropriate
String dateTime = GameObjects[i].getString("date");
String date = FormatDate(dateTime);
info[1].setText("\tGame Date:\t\t" + date);
list.addView(info[1]);
info[2] = new TextView(this);
info[2].setText("\tHome Team:\t\t" + GameObjects[i].getJSONObject("teams")
.getString("home").toUpperCase());
list.addView(info[2]);
info[3] = new TextView(this);
info[3].setText("\tAgainst:\t\t" + GameObjects[i].getJSONObject("teams")
.getString("away").toUpperCase());
list.addView(info[3]);
// add the button to the display details for each game
// might have to add tag to button
list.addView(detailsButtons[i]);
list.setPadding(0, 5, 0, 20);
gameTableRow.addView(list);
gameTableRow.setBackgroundResource(R.drawable.img_gloss_background);
mainTable.addView(gameTableRow);
}
} catch(InterruptedException ex) {
Log.w("List Activity - mGetTable.execute()", ex.getMessage());
} catch(ExecutionException ex) {
Log.w("List Activity - mGetTable.execute()", ex.getMessage());
} catch (JSONException e) {
e.printStackTrace();
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
TextView welcomeMsg = (TextView)findViewById(R.id.UI_GreetingText);
// set up logout button
((Button)findViewById(R.id.UI_LogoutBtn)).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
UserControl UC = new UserControl();
UserControl.Logout logout = UC.new Logout();
// begin the logout process
logout.execute();
// wait for the server's results
try {
JSONObject json = new JSONObject(logout.get());
String message = json.getString("success");
// check to see if user has successfully logged out
if(message.equals("true")) {
Toast.makeText(getApplicationContext(),
"You have been logged out.", Toast.LENGTH_LONG)
.show();
}
else {
Toast.makeText(getApplicationContext(),
"You are not logged in.", Toast.LENGTH_LONG)
.show();
}
finish();
startActivity(new Intent(getApplicationContext(),
LoginActivity.class));
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
homeTeam = awayTeam = sportType = date = "";
// general initialization
mainTable = (TableLayout)findViewById(R.id.UI_MainTableLayout);
mDetailsListener = new AdditionDetailsListener();
// get the name of the user that is currently logged in
getCurrentUser = new GetCurrentUser();
getCurrentUser.execute();
try {
JSONObject userInfoObject = new JSONObject(getCurrentUser.get());
userName = userInfoObject.getJSONObject("name").getString("first")
+ " " +
userInfoObject.getJSONObject("name").getString("last");
String constructHeader = "Welcome, " + userName;
welcomeMsg.setText(constructHeader);
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
games = new GetGames();
try {
games.execute();
response = games.get();
// Show the pop-up box (for display testing)
//showDialog(MESSAGE);
gamesArray = new JSONArray(response);
// Allocate space for all JSON objects embedded in the JSON array
GameObjects = new JSONObject[gamesArray.length()];
// Transfer each object in this JSONArray into its own object
for(int i=0;i<gamesArray.length();i++)
GameObjects[i] = gamesArray.getJSONObject(i);
/*
* give every game a button for displaying additional
* details about that game. (This button will also be
* used to register for games
*/
Button[] detailsButtons =
new Button[ gamesArray.length()];
for(int i = 0; i < gamesArray.length(); i++) {
TableRow gameTableRow = new TableRow(this);
LinearLayout list = new LinearLayout(this);
// Initialize each button and give it a reference id (i)
detailsButtons[i] = new Button(this);
detailsButtons[i].setText("More Details");
detailsButtons[i].setId(i);
detailsButtons[i].setOnClickListener(mDetailsListener);
TextView[] info = new TextView[4];
// set the list to a top down look
list.setOrientation(LinearLayout.VERTICAL);
info[0] = new TextView(this);
info[0].setText("\tSport:\t\t" + GameObjects[i].getString("sport"));
list.addView(info[0]);
info[1] = new TextView(this);
//Format the date so that it is appropriate
String dateTime = GameObjects[i].getString("date");
String date = FormatDate(dateTime);
info[1].setText("\tGame Date:\t\t" + date);
list.addView(info[1]);
info[2] = new TextView(this);
info[2].setText("\tHome Team:\t\t" + GameObjects[i].getJSONObject("teams")
.getString("home").toUpperCase());
list.addView(info[2]);
info[3] = new TextView(this);
info[3].setText("\tAgainst:\t\t" + GameObjects[i].getJSONObject("teams")
.getString("away").toUpperCase());
list.addView(info[3]);
// add the button to the display details for each game
// might have to add tag to button
list.addView(detailsButtons[i]);
list.setPadding(0, 5, 0, 20);
gameTableRow.addView(list);
gameTableRow.setBackgroundResource(R.drawable.img_gloss_background);
mainTable.addView(gameTableRow);
}
} catch(InterruptedException ex) {
Log.w("List Activity - mGetTable.execute()", ex.getMessage());
} catch(ExecutionException ex) {
Log.w("List Activity - mGetTable.execute()", ex.getMessage());
} catch (JSONException e) {
e.printStackTrace();
}
}
|
diff --git a/src/tree/ConsNode.java b/src/tree/ConsNode.java
index c5f0d69..15ecea1 100755
--- a/src/tree/ConsNode.java
+++ b/src/tree/ConsNode.java
@@ -1,57 +1,57 @@
package tree;
public class ConsNode extends ParNode {
private ExprNode exprA, exprB;
public ConsNode(ExprNode exprA, ExprNode exprB) {
this.exprA = exprA;
this.exprB = exprB;
}
public ExprNode getExprA() {
return exprA;
}
public void setExprA(ExprNode exprA) {
this.exprA = exprA;
}
public ExprNode getExprB() {
return exprB;
}
public void setExprB(ExprNode exprB) {
this.exprB = exprB;
}
@Override
public void parse() {
this.exprA.parse();
this.exprB.parse();
}
@Override
public String codeC() {
StringBuilder str = new StringBuilder();
str.append("wh::cons(");
str.append(exprA.codeC());
- str.append(" ");
+ str.append(", ");
str.append(exprB.codeC());
str.append(");");
return str.toString();
}
@Override
public String display() {
StringBuilder str = new StringBuilder();
str.append("|-cons\r\n");
str.append(this.format(exprA.display()));
str.append(this.format(exprB.display()));
return str.toString();
}
}
| true | true | public String codeC() {
StringBuilder str = new StringBuilder();
str.append("wh::cons(");
str.append(exprA.codeC());
str.append(" ");
str.append(exprB.codeC());
str.append(");");
return str.toString();
}
| public String codeC() {
StringBuilder str = new StringBuilder();
str.append("wh::cons(");
str.append(exprA.codeC());
str.append(", ");
str.append(exprB.codeC());
str.append(");");
return str.toString();
}
|
diff --git a/query/src/test/java/org/apache/accumulo/examples/wikisearch/logic/TestQueryLogic.java b/query/src/test/java/org/apache/accumulo/examples/wikisearch/logic/TestQueryLogic.java
index 8400fb5..4b7aaee 100644
--- a/query/src/test/java/org/apache/accumulo/examples/wikisearch/logic/TestQueryLogic.java
+++ b/query/src/test/java/org/apache/accumulo/examples/wikisearch/logic/TestQueryLogic.java
@@ -1,187 +1,187 @@
/*
* 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.accumulo.examples.wikisearch.logic;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import junit.framework.Assert;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.mock.MockInstance;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.examples.wikisearch.ingest.WikipediaConfiguration;
import org.apache.accumulo.examples.wikisearch.ingest.WikipediaInputFormat.WikipediaInputSplit;
import org.apache.accumulo.examples.wikisearch.ingest.WikipediaMapper;
import org.apache.accumulo.examples.wikisearch.parser.RangeCalculator;
import org.apache.accumulo.examples.wikisearch.reader.AggregatingRecordReader;
import org.apache.accumulo.examples.wikisearch.sample.Document;
import org.apache.accumulo.examples.wikisearch.sample.Field;
import org.apache.accumulo.examples.wikisearch.sample.Results;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.OutputCommitter;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
public class TestQueryLogic {
private static final String METADATA_TABLE_NAME = "wikiMetadata";
private static final String TABLE_NAME = "wiki";
private static final String INDEX_TABLE_NAME = "wikiIndex";
private static final String RINDEX_TABLE_NAME = "wikiReverseIndex";
private static final String TABLE_NAMES[] = {METADATA_TABLE_NAME, TABLE_NAME, RINDEX_TABLE_NAME, INDEX_TABLE_NAME};
private class MockAccumuloRecordWriter extends RecordWriter<Text,Mutation> {
@Override
public void write(Text key, Mutation value) throws IOException, InterruptedException {
try {
writerMap.get(key).addMutation(value);
} catch (MutationsRejectedException e) {
throw new IOException("Error adding mutation", e);
}
}
@Override
public void close(TaskAttemptContext context) throws IOException, InterruptedException {
try {
for (BatchWriter w : writerMap.values()) {
w.flush();
w.close();
}
} catch (MutationsRejectedException e) {
throw new IOException("Error closing Batch Writer", e);
}
}
}
private Connector c = null;
private Configuration conf = new Configuration();
private HashMap<Text,BatchWriter> writerMap = new HashMap<Text,BatchWriter>();
private QueryLogic table = null;
@Before
public void setup() throws Exception {
Logger.getLogger(AbstractQueryLogic.class).setLevel(Level.DEBUG);
Logger.getLogger(QueryLogic.class).setLevel(Level.DEBUG);
Logger.getLogger(RangeCalculator.class).setLevel(Level.DEBUG);
conf.set(AggregatingRecordReader.START_TOKEN, "<page>");
conf.set(AggregatingRecordReader.END_TOKEN, "</page>");
conf.set(WikipediaConfiguration.TABLE_NAME, TABLE_NAME);
conf.set(WikipediaConfiguration.NUM_PARTITIONS, "1");
conf.set(WikipediaConfiguration.NUM_GROUPS, "1");
MockInstance i = new MockInstance();
- c = i.getConnector("root", "pass");
+ c = i.getConnector("root", "");
for (String table : TABLE_NAMES) {
try {
c.tableOperations().delete(table);
} catch (Exception ex) {}
c.tableOperations().create(table);
writerMap.put(new Text(table), c.createBatchWriter(table, 1000L, 1000L, 1));
}
TaskAttemptID id = new TaskAttemptID();
TaskAttemptContext context = new TaskAttemptContext(conf, id);
RawLocalFileSystem fs = new RawLocalFileSystem();
fs.setConf(conf);
URL url = ClassLoader.getSystemResource("enwiki-20110901-001.xml");
Assert.assertNotNull(url);
File data = new File(url.toURI());
Path tmpFile = new Path(data.getAbsolutePath());
// Setup the Mapper
WikipediaInputSplit split = new WikipediaInputSplit(new FileSplit(tmpFile, 0, fs.pathToFile(tmpFile).length(), null),0);
AggregatingRecordReader rr = new AggregatingRecordReader();
Path ocPath = new Path(tmpFile, "oc");
OutputCommitter oc = new FileOutputCommitter(ocPath, context);
fs.deleteOnExit(ocPath);
StandaloneStatusReporter sr = new StandaloneStatusReporter();
rr.initialize(split, context);
MockAccumuloRecordWriter rw = new MockAccumuloRecordWriter();
WikipediaMapper mapper = new WikipediaMapper();
// Load data into Mock Accumulo
Mapper<LongWritable,Text,Text,Mutation>.Context con = mapper.new Context(conf, id, rr, rw, oc, sr, split);
mapper.run(con);
// Flush and close record writers.
rw.close(context);
table = new QueryLogic();
table.setMetadataTableName(METADATA_TABLE_NAME);
table.setTableName(TABLE_NAME);
table.setIndexTableName(INDEX_TABLE_NAME);
table.setReverseIndexTableName(RINDEX_TABLE_NAME);
table.setUseReadAheadIterator(false);
}
void debugQuery(String tableName) throws Exception {
Scanner s = c.createScanner(tableName, new Authorizations());
Range r = new Range();
s.setRange(r);
for (Entry<Key,Value> entry : s)
System.out.println(entry.getKey().toString() + " " + entry.getValue().toString());
}
@Test
public void testTitle() {
Logger.getLogger(AbstractQueryLogic.class).setLevel(Level.OFF);
Logger.getLogger(RangeCalculator.class).setLevel(Level.OFF);
List<String> auths = new ArrayList<String>();
auths.add("enwiki");
Results results = table.runQuery(c, auths, "TITLE == 'afghanistanhistory'", null, null, null);
for (Document doc : results.getResults()) {
System.out.println("id: " + doc.getId());
for (Field field : doc.getFields())
System.out.println(field.getFieldName() + " -> " + field.getFieldValue());
}
}
}
| true | true | public void setup() throws Exception {
Logger.getLogger(AbstractQueryLogic.class).setLevel(Level.DEBUG);
Logger.getLogger(QueryLogic.class).setLevel(Level.DEBUG);
Logger.getLogger(RangeCalculator.class).setLevel(Level.DEBUG);
conf.set(AggregatingRecordReader.START_TOKEN, "<page>");
conf.set(AggregatingRecordReader.END_TOKEN, "</page>");
conf.set(WikipediaConfiguration.TABLE_NAME, TABLE_NAME);
conf.set(WikipediaConfiguration.NUM_PARTITIONS, "1");
conf.set(WikipediaConfiguration.NUM_GROUPS, "1");
MockInstance i = new MockInstance();
c = i.getConnector("root", "pass");
for (String table : TABLE_NAMES) {
try {
c.tableOperations().delete(table);
} catch (Exception ex) {}
c.tableOperations().create(table);
writerMap.put(new Text(table), c.createBatchWriter(table, 1000L, 1000L, 1));
}
TaskAttemptID id = new TaskAttemptID();
TaskAttemptContext context = new TaskAttemptContext(conf, id);
RawLocalFileSystem fs = new RawLocalFileSystem();
fs.setConf(conf);
URL url = ClassLoader.getSystemResource("enwiki-20110901-001.xml");
Assert.assertNotNull(url);
File data = new File(url.toURI());
Path tmpFile = new Path(data.getAbsolutePath());
// Setup the Mapper
WikipediaInputSplit split = new WikipediaInputSplit(new FileSplit(tmpFile, 0, fs.pathToFile(tmpFile).length(), null),0);
AggregatingRecordReader rr = new AggregatingRecordReader();
Path ocPath = new Path(tmpFile, "oc");
OutputCommitter oc = new FileOutputCommitter(ocPath, context);
fs.deleteOnExit(ocPath);
StandaloneStatusReporter sr = new StandaloneStatusReporter();
rr.initialize(split, context);
MockAccumuloRecordWriter rw = new MockAccumuloRecordWriter();
WikipediaMapper mapper = new WikipediaMapper();
// Load data into Mock Accumulo
Mapper<LongWritable,Text,Text,Mutation>.Context con = mapper.new Context(conf, id, rr, rw, oc, sr, split);
mapper.run(con);
// Flush and close record writers.
rw.close(context);
table = new QueryLogic();
table.setMetadataTableName(METADATA_TABLE_NAME);
table.setTableName(TABLE_NAME);
table.setIndexTableName(INDEX_TABLE_NAME);
table.setReverseIndexTableName(RINDEX_TABLE_NAME);
table.setUseReadAheadIterator(false);
}
| public void setup() throws Exception {
Logger.getLogger(AbstractQueryLogic.class).setLevel(Level.DEBUG);
Logger.getLogger(QueryLogic.class).setLevel(Level.DEBUG);
Logger.getLogger(RangeCalculator.class).setLevel(Level.DEBUG);
conf.set(AggregatingRecordReader.START_TOKEN, "<page>");
conf.set(AggregatingRecordReader.END_TOKEN, "</page>");
conf.set(WikipediaConfiguration.TABLE_NAME, TABLE_NAME);
conf.set(WikipediaConfiguration.NUM_PARTITIONS, "1");
conf.set(WikipediaConfiguration.NUM_GROUPS, "1");
MockInstance i = new MockInstance();
c = i.getConnector("root", "");
for (String table : TABLE_NAMES) {
try {
c.tableOperations().delete(table);
} catch (Exception ex) {}
c.tableOperations().create(table);
writerMap.put(new Text(table), c.createBatchWriter(table, 1000L, 1000L, 1));
}
TaskAttemptID id = new TaskAttemptID();
TaskAttemptContext context = new TaskAttemptContext(conf, id);
RawLocalFileSystem fs = new RawLocalFileSystem();
fs.setConf(conf);
URL url = ClassLoader.getSystemResource("enwiki-20110901-001.xml");
Assert.assertNotNull(url);
File data = new File(url.toURI());
Path tmpFile = new Path(data.getAbsolutePath());
// Setup the Mapper
WikipediaInputSplit split = new WikipediaInputSplit(new FileSplit(tmpFile, 0, fs.pathToFile(tmpFile).length(), null),0);
AggregatingRecordReader rr = new AggregatingRecordReader();
Path ocPath = new Path(tmpFile, "oc");
OutputCommitter oc = new FileOutputCommitter(ocPath, context);
fs.deleteOnExit(ocPath);
StandaloneStatusReporter sr = new StandaloneStatusReporter();
rr.initialize(split, context);
MockAccumuloRecordWriter rw = new MockAccumuloRecordWriter();
WikipediaMapper mapper = new WikipediaMapper();
// Load data into Mock Accumulo
Mapper<LongWritable,Text,Text,Mutation>.Context con = mapper.new Context(conf, id, rr, rw, oc, sr, split);
mapper.run(con);
// Flush and close record writers.
rw.close(context);
table = new QueryLogic();
table.setMetadataTableName(METADATA_TABLE_NAME);
table.setTableName(TABLE_NAME);
table.setIndexTableName(INDEX_TABLE_NAME);
table.setReverseIndexTableName(RINDEX_TABLE_NAME);
table.setUseReadAheadIterator(false);
}
|
diff --git a/src/main/java/stirling/console/commands/Profile.java b/src/main/java/stirling/console/commands/Profile.java
index 802ddee4..2f637047 100644
--- a/src/main/java/stirling/console/commands/Profile.java
+++ b/src/main/java/stirling/console/commands/Profile.java
@@ -1,67 +1,68 @@
/*
* Copyright 2010 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 stirling.console.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import stirling.console.Arguments;
import stirling.console.ConsoleClient;
import stirling.fix.messages.MessageFactory;
public class Profile implements Command {
private static final String ARGUMENT_NAME = "Name";
private Map<String, MessageFactory> factories = new HashMap<String, MessageFactory>();
public Profile() {
factories.put("default", new stirling.fix.messages.fix42.DefaultMessageFactory());
factories.put("bats-europe", new stirling.fix.messages.fix42.bats.europe.MessageFactory());
factories.put("mb-trading", new stirling.fix.messages.fix44.mbtrading.MessageFactory());
factories.put("burgundy", new stirling.fix.messages.fix44.burgundy.MessageFactory());
factories.put("hotspot-fx", new stirling.fix.messages.fix42.hotspotfx.MessageFactory());
factories.put("samrat", new stirling.fix.messages.fix42.samrat.MessageFactory());
+ factories.put("nasdaq-omx", new stirling.fix.messages.fix42.nasdaqomx.MessageFactory());
}
public void execute(ConsoleClient client, Scanner scanner) throws CommandException {
String profile = new Arguments(scanner).requiredValue(ARGUMENT_NAME);
MessageFactory factory = factories.get(profile);
if (factory == null)
throw new CommandArgException("unknown profile: " + profile);
client.setMessageFactory(factory);
}
@Override public String[] getArgumentNames(ConsoleClient client) {
List<String> profiles = new ArrayList<String>(factories.keySet());
List<String> argumentNames = new ArrayList<String>();
Collections.sort(profiles);
for (String profile : profiles)
argumentNames.add(ARGUMENT_NAME + "=" + profile);
return argumentNames.toArray(new String[0]);
}
@Override public String description() {
return "Sets profile which will be used for creating and sending messages.";
}
@Override public String usage() {
return ARGUMENT_NAME + "=<profile> : " + description();
}
}
| true | true | public Profile() {
factories.put("default", new stirling.fix.messages.fix42.DefaultMessageFactory());
factories.put("bats-europe", new stirling.fix.messages.fix42.bats.europe.MessageFactory());
factories.put("mb-trading", new stirling.fix.messages.fix44.mbtrading.MessageFactory());
factories.put("burgundy", new stirling.fix.messages.fix44.burgundy.MessageFactory());
factories.put("hotspot-fx", new stirling.fix.messages.fix42.hotspotfx.MessageFactory());
factories.put("samrat", new stirling.fix.messages.fix42.samrat.MessageFactory());
}
| public Profile() {
factories.put("default", new stirling.fix.messages.fix42.DefaultMessageFactory());
factories.put("bats-europe", new stirling.fix.messages.fix42.bats.europe.MessageFactory());
factories.put("mb-trading", new stirling.fix.messages.fix44.mbtrading.MessageFactory());
factories.put("burgundy", new stirling.fix.messages.fix44.burgundy.MessageFactory());
factories.put("hotspot-fx", new stirling.fix.messages.fix42.hotspotfx.MessageFactory());
factories.put("samrat", new stirling.fix.messages.fix42.samrat.MessageFactory());
factories.put("nasdaq-omx", new stirling.fix.messages.fix42.nasdaqomx.MessageFactory());
}
|
diff --git a/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java b/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java
index e3f2561..fe39c84 100644
--- a/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java
+++ b/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java
@@ -1,105 +1,107 @@
package ar.proyecto.gui;
import java.awt.FlowLayout;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
import ar.proyecto.controller.ActionInsert;
public class MiddlePanelInsert extends MiddlePanel {
//Crear la ventana
private JLabel into;
private JLabel nroPatente;
private JFormattedTextField txtNroPatente;
private JLabel typo;
private JTextField txtTypo;
private JLabel modelo;
private JTextField txtModelo;
private JLabel ano;
private JFormattedTextField txtAno;
@SuppressWarnings("rawtypes")
private JComboBox cboxMarca;
private JButton ok;
//constructor
@SuppressWarnings({ "unchecked", "rawtypes" })
public MiddlePanelInsert(MainWindow gui) {
super(gui);
//Inicializar los Labeles
into = new JLabel("INTO Vehiculo :");
nroPatente = new JLabel("nro_patente =");
typo = new JLabel("typo =");
modelo = new JLabel("modelo =");
ano = new JLabel("anos =");
//Inicializar los textFields
try {
txtNroPatente = new JFormattedTextField(new MaskFormatter("******"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtNroPatente = new JFormattedTextField();
}
txtNroPatente.setColumns(5);
txtTypo = new JTextField();
txtTypo.setColumns(4);
txtModelo = new JTextField();
txtModelo.setColumns(10);
- txtAno = new JFormattedTextField(NumberFormat.getIntegerInstance());
+ NumberFormat AnoFormatter = NumberFormat.getIntegerInstance();
+ AnoFormatter.setGroupingUsed(false);
+ txtAno = new JFormattedTextField(AnoFormatter);
txtAno.setColumns(4);
//Inicializar el comboBox
String[] marcas = {"FIAT","FORD","RENAULT"};
cboxMarca = new JComboBox(marcas);
cboxMarca.setSelectedItem(2);
//Inicializar el Button
ok = new JButton(new ActionInsert(this,"OK"));
//Agregar todo al panel
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(into);
this.add(nroPatente);
this.add(txtNroPatente);
this.add(typo);
this.add(txtTypo);
this.add(cboxMarca);
this.add(modelo);
this.add(txtModelo);
this.add(ano);
this.add(txtAno);
this.add(ok);
}
public JFormattedTextField getTxtNroPatente() {
return txtNroPatente;
}
public JTextField getTxtTypo() {
return txtTypo;
}
public JTextField getTxtModelo() {
return txtModelo;
}
public JFormattedTextField getTxtAno() {
return txtAno;
}
public JComboBox getCboxMarca() {
return cboxMarca;
}
}
| true | true | public MiddlePanelInsert(MainWindow gui) {
super(gui);
//Inicializar los Labeles
into = new JLabel("INTO Vehiculo :");
nroPatente = new JLabel("nro_patente =");
typo = new JLabel("typo =");
modelo = new JLabel("modelo =");
ano = new JLabel("anos =");
//Inicializar los textFields
try {
txtNroPatente = new JFormattedTextField(new MaskFormatter("******"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtNroPatente = new JFormattedTextField();
}
txtNroPatente.setColumns(5);
txtTypo = new JTextField();
txtTypo.setColumns(4);
txtModelo = new JTextField();
txtModelo.setColumns(10);
txtAno = new JFormattedTextField(NumberFormat.getIntegerInstance());
txtAno.setColumns(4);
//Inicializar el comboBox
String[] marcas = {"FIAT","FORD","RENAULT"};
cboxMarca = new JComboBox(marcas);
cboxMarca.setSelectedItem(2);
//Inicializar el Button
ok = new JButton(new ActionInsert(this,"OK"));
//Agregar todo al panel
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(into);
this.add(nroPatente);
this.add(txtNroPatente);
this.add(typo);
this.add(txtTypo);
this.add(cboxMarca);
this.add(modelo);
this.add(txtModelo);
this.add(ano);
this.add(txtAno);
this.add(ok);
}
| public MiddlePanelInsert(MainWindow gui) {
super(gui);
//Inicializar los Labeles
into = new JLabel("INTO Vehiculo :");
nroPatente = new JLabel("nro_patente =");
typo = new JLabel("typo =");
modelo = new JLabel("modelo =");
ano = new JLabel("anos =");
//Inicializar los textFields
try {
txtNroPatente = new JFormattedTextField(new MaskFormatter("******"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtNroPatente = new JFormattedTextField();
}
txtNroPatente.setColumns(5);
txtTypo = new JTextField();
txtTypo.setColumns(4);
txtModelo = new JTextField();
txtModelo.setColumns(10);
NumberFormat AnoFormatter = NumberFormat.getIntegerInstance();
AnoFormatter.setGroupingUsed(false);
txtAno = new JFormattedTextField(AnoFormatter);
txtAno.setColumns(4);
//Inicializar el comboBox
String[] marcas = {"FIAT","FORD","RENAULT"};
cboxMarca = new JComboBox(marcas);
cboxMarca.setSelectedItem(2);
//Inicializar el Button
ok = new JButton(new ActionInsert(this,"OK"));
//Agregar todo al panel
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(into);
this.add(nroPatente);
this.add(txtNroPatente);
this.add(typo);
this.add(txtTypo);
this.add(cboxMarca);
this.add(modelo);
this.add(txtModelo);
this.add(ano);
this.add(txtAno);
this.add(ok);
}
|
diff --git a/src/main/java/com/concursive/connect/web/modules/tools/actions/ProjectManagementTools.java b/src/main/java/com/concursive/connect/web/modules/tools/actions/ProjectManagementTools.java
index 20261ab..b082212 100644
--- a/src/main/java/com/concursive/connect/web/modules/tools/actions/ProjectManagementTools.java
+++ b/src/main/java/com/concursive/connect/web/modules/tools/actions/ProjectManagementTools.java
@@ -1,197 +1,197 @@
/*
* ConcourseConnect
* Copyright 2009 Concursive Corporation
* http://www.concursive.com
*
* This file is part of ConcourseConnect, an open source social business
* software and community platform.
*
* Concursive ConcourseConnect 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, version 3 of the License.
*
* Under the terms of the GNU Affero General Public License you must release the
* complete source code for any application that uses any part of ConcourseConnect
* (system header files and libraries used by the operating system are excluded).
* These terms must be included in any work that has ConcourseConnect components.
* If you are developing and distributing open source applications under the
* GNU Affero General Public License, then you are free to use ConcourseConnect
* under the GNU Affero General Public License.
*
* If you are deploying a web site in which users interact with any portion of
* ConcourseConnect over a network, the complete source code changes must be made
* available. For example, include a link to the source archive directly from
* your web site.
*
* For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their
* products, and do not license and distribute their source code under the GNU
* Affero General Public License, Concursive provides a flexible commercial
* license.
*
* To anyone in doubt, we recommend the commercial license. Our commercial license
* is competitively priced and will eliminate any confusion about how
* ConcourseConnect can be used and distributed.
*
* ConcourseConnect 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 ConcourseConnect. If not, see <http://www.gnu.org/licenses/>.
*
* Attribution Notice: ConcourseConnect is an Original Work of software created
* by Concursive Corporation
*/
package com.concursive.connect.web.modules.tools.actions;
import com.concursive.commons.http.RequestUtils;
import com.concursive.commons.text.StringUtils;
import com.concursive.commons.web.mvc.actions.ActionContext;
import com.concursive.connect.cache.utils.CacheUtils;
import com.concursive.connect.web.controller.actions.GenericAction;
import com.concursive.connect.web.modules.login.dao.User;
import com.concursive.connect.web.modules.login.utils.UserUtils;
import com.concursive.connect.web.modules.members.dao.TeamMember;
import com.concursive.connect.web.modules.profile.dao.Project;
import com.concursive.connect.web.utils.LookupList;
import java.net.URLEncoder;
import org.aspcfs.apps.transfer.DataRecord;
import org.aspcfs.utils.CRMConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Random;
/**
* @author jfielek
* @created Jul 19, 2008 11:53:58 PM
*/
public class ProjectManagementTools extends GenericAction {
public String executeCommandDefault(ActionContext context) {
// Base Visible Format is: /show/<project unique id>/tools[/xyz]
String projectId = context.getRequest().getParameter("pid");
String linkTo = context.getRequest().getParameter("linkTo");
// Validate and redirect to the tools url
try {
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
// Make sure the project has a tools link
if (!StringUtils.hasText(thisProject.getConcursiveCRMUrl())) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> concursive crm url is empty for project: " + thisProject.getId() + " - " + thisProject.getUniqueId());
}
return "PermissionError";
}
// Make sure this user is on the team
TeamMember thisMember = thisProject.getTeam().getTeamMember(getUserId(context));
if (thisMember == null || !thisMember.getTools()) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> user doesn't have access to tools");
}
return "PermissionError";
}
// Retrieve owner's email address to create a relationship in tools
String ownerEmail = null;
Connection db = null;
try {
db = getConnection(context);
// Get owner's email address in case the user needs to be added
int ownerId = thisProject.getOwner();
if (ownerId > -1) {
User owner = UserUtils.loadUser(ownerId);
ownerEmail = owner.getEmail();
}
} catch (Exception e) {
e.printStackTrace();
return "SystemError";
} finally {
freeConnection(context, db);
}
// Determine the user's current role
LookupList roleList = CacheUtils.getLookupList("lookup_project_role");
- String role = roleList.getValueFromId(thisMember.getRoleId());
+ String role = roleList.getValueFromId(thisMember.getUserLevel());
// Then generate token and use CRM API to pass token, and then redirect to CRM
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> generating token");
}
String token = generateRandomToken();
if (sendToken(thisProject, getUser(context), token, ownerEmail, role)) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> sending redirect");
}
// if successful, send the redirect...
String redirect = "MyCFS.do?command=Home";
if ("campaign".equals(linkTo)) {
redirect = "CampaignManager.do?command=Default";
}
// Link back to this page
String returnURL = (String) context.getRequest().getParameter("returnURL");
if (returnURL != null) {
try {
returnURL = RequestUtils.getAbsoluteServerUrl(context.getRequest()) + URLEncoder.encode(returnURL, "UTF-8");
} catch (Exception e) {
}
}
LOG.debug("Return URL: " + returnURL);
context.getRequest().setAttribute("redirectTo", thisProject.getConcursiveCRMUrl() + "/" + redirect + "&token=" + token + (returnURL != null ? "&returnURL=" + returnURL : ""));
return ("Redirect301");
} else {
return "ToolsError";
}
} catch (SQLException e) {
e.printStackTrace();
}
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> End reached");
}
return "SystemError";
}
private boolean sendToken(Project project, User user, String token, String ownerEmail, String role) {
// Connection details
CRMConnection conn = new CRMConnection();
conn.setUrl(project.getConcursiveCRMUrl());
conn.setId(project.getConcursiveCRMDomain());
conn.setCode(project.getConcursiveCRMCode());
conn.setClientId(project.getConcursiveCRMClient());
// Request info
DataRecord record = new DataRecord();
record.setName("map");
record.setAction("importSessionAuthenticationId");
record.addField("userEmail", user.getEmail());
record.addField("sessionToken", token);
record.addField("userFirstName", user.getFirstName());
record.addField("userLastName", user.getLastName());
record.addField("userCompany", user.getCompany());
record.addField("userPassword", user.getPassword());
if (StringUtils.hasText(ownerEmail)) {
record.addField("userReportsTo", ownerEmail);
}
record.addField("userTimeZone", user.getTimeZone());
record.addField("role", role);
boolean success = conn.save(record);
if (!success) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> sendToken error: " + conn.getLastResponse());
}
}
return success;
}
static Random random = new Random();
static String validCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy0123456789";
private String generateRandomToken() {
String token = new String("");
for (int i = 0; i < 128; i++) {
// Generate a random character..
int charNum = random.nextInt(validCharacters.length());
token += validCharacters.charAt(charNum);
//token += validCharacters.substring(charNum, charNum + 1);
}
return token;
}
}
| true | true | public String executeCommandDefault(ActionContext context) {
// Base Visible Format is: /show/<project unique id>/tools[/xyz]
String projectId = context.getRequest().getParameter("pid");
String linkTo = context.getRequest().getParameter("linkTo");
// Validate and redirect to the tools url
try {
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
// Make sure the project has a tools link
if (!StringUtils.hasText(thisProject.getConcursiveCRMUrl())) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> concursive crm url is empty for project: " + thisProject.getId() + " - " + thisProject.getUniqueId());
}
return "PermissionError";
}
// Make sure this user is on the team
TeamMember thisMember = thisProject.getTeam().getTeamMember(getUserId(context));
if (thisMember == null || !thisMember.getTools()) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> user doesn't have access to tools");
}
return "PermissionError";
}
// Retrieve owner's email address to create a relationship in tools
String ownerEmail = null;
Connection db = null;
try {
db = getConnection(context);
// Get owner's email address in case the user needs to be added
int ownerId = thisProject.getOwner();
if (ownerId > -1) {
User owner = UserUtils.loadUser(ownerId);
ownerEmail = owner.getEmail();
}
} catch (Exception e) {
e.printStackTrace();
return "SystemError";
} finally {
freeConnection(context, db);
}
// Determine the user's current role
LookupList roleList = CacheUtils.getLookupList("lookup_project_role");
String role = roleList.getValueFromId(thisMember.getRoleId());
// Then generate token and use CRM API to pass token, and then redirect to CRM
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> generating token");
}
String token = generateRandomToken();
if (sendToken(thisProject, getUser(context), token, ownerEmail, role)) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> sending redirect");
}
// if successful, send the redirect...
String redirect = "MyCFS.do?command=Home";
if ("campaign".equals(linkTo)) {
redirect = "CampaignManager.do?command=Default";
}
// Link back to this page
String returnURL = (String) context.getRequest().getParameter("returnURL");
if (returnURL != null) {
try {
returnURL = RequestUtils.getAbsoluteServerUrl(context.getRequest()) + URLEncoder.encode(returnURL, "UTF-8");
} catch (Exception e) {
}
}
LOG.debug("Return URL: " + returnURL);
context.getRequest().setAttribute("redirectTo", thisProject.getConcursiveCRMUrl() + "/" + redirect + "&token=" + token + (returnURL != null ? "&returnURL=" + returnURL : ""));
return ("Redirect301");
} else {
return "ToolsError";
}
} catch (SQLException e) {
e.printStackTrace();
}
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> End reached");
}
return "SystemError";
}
| public String executeCommandDefault(ActionContext context) {
// Base Visible Format is: /show/<project unique id>/tools[/xyz]
String projectId = context.getRequest().getParameter("pid");
String linkTo = context.getRequest().getParameter("linkTo");
// Validate and redirect to the tools url
try {
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
// Make sure the project has a tools link
if (!StringUtils.hasText(thisProject.getConcursiveCRMUrl())) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> concursive crm url is empty for project: " + thisProject.getId() + " - " + thisProject.getUniqueId());
}
return "PermissionError";
}
// Make sure this user is on the team
TeamMember thisMember = thisProject.getTeam().getTeamMember(getUserId(context));
if (thisMember == null || !thisMember.getTools()) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> user doesn't have access to tools");
}
return "PermissionError";
}
// Retrieve owner's email address to create a relationship in tools
String ownerEmail = null;
Connection db = null;
try {
db = getConnection(context);
// Get owner's email address in case the user needs to be added
int ownerId = thisProject.getOwner();
if (ownerId > -1) {
User owner = UserUtils.loadUser(ownerId);
ownerEmail = owner.getEmail();
}
} catch (Exception e) {
e.printStackTrace();
return "SystemError";
} finally {
freeConnection(context, db);
}
// Determine the user's current role
LookupList roleList = CacheUtils.getLookupList("lookup_project_role");
String role = roleList.getValueFromId(thisMember.getUserLevel());
// Then generate token and use CRM API to pass token, and then redirect to CRM
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> generating token");
}
String token = generateRandomToken();
if (sendToken(thisProject, getUser(context), token, ownerEmail, role)) {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> sending redirect");
}
// if successful, send the redirect...
String redirect = "MyCFS.do?command=Home";
if ("campaign".equals(linkTo)) {
redirect = "CampaignManager.do?command=Default";
}
// Link back to this page
String returnURL = (String) context.getRequest().getParameter("returnURL");
if (returnURL != null) {
try {
returnURL = RequestUtils.getAbsoluteServerUrl(context.getRequest()) + URLEncoder.encode(returnURL, "UTF-8");
} catch (Exception e) {
}
}
LOG.debug("Return URL: " + returnURL);
context.getRequest().setAttribute("redirectTo", thisProject.getConcursiveCRMUrl() + "/" + redirect + "&token=" + token + (returnURL != null ? "&returnURL=" + returnURL : ""));
return ("Redirect301");
} else {
return "ToolsError";
}
} catch (SQLException e) {
e.printStackTrace();
}
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementTools-> End reached");
}
return "SystemError";
}
|
diff --git a/src/org/hyperion/rs2/event/impl/UpdateEvent.java b/src/org/hyperion/rs2/event/impl/UpdateEvent.java
index ffa48eb..fc96f93 100644
--- a/src/org/hyperion/rs2/event/impl/UpdateEvent.java
+++ b/src/org/hyperion/rs2/event/impl/UpdateEvent.java
@@ -1,70 +1,71 @@
package org.hyperion.rs2.event.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hyperion.rs2.event.Event;
import org.hyperion.rs2.model.NPC;
import org.hyperion.rs2.model.Player;
import org.hyperion.rs2.model.World;
import org.hyperion.rs2.task.ConsecutiveTask;
import org.hyperion.rs2.task.ParallelTask;
import org.hyperion.rs2.task.Task;
import org.hyperion.rs2.task.impl.NPCResetTask;
import org.hyperion.rs2.task.impl.NPCTickTask;
import org.hyperion.rs2.task.impl.NPCUpdateTask;
import org.hyperion.rs2.task.impl.PlayerResetTask;
import org.hyperion.rs2.task.impl.PlayerTickTask;
import org.hyperion.rs2.task.impl.PlayerUpdateTask;
/**
* An event which starts player update tasks.
* @author Graham Edgecombe
*
*/
public class UpdateEvent extends Event {
/**
* The cycle time, in milliseconds.
*/
public static final int CYCLE_TIME = 600;
/**
* Creates the update event to cycle every 600 milliseconds.
*/
public UpdateEvent() {
super(CYCLE_TIME);
}
@Override
public void execute() {
List<Task> tickTasks = new ArrayList<Task>();
List<Task> updateTasks = new ArrayList<Task>();
List<Task> resetTasks = new ArrayList<Task>();
for(NPC npc : World.getWorld().getNPCs()) {
tickTasks.add(new NPCTickTask(npc));
resetTasks.add(new NPCResetTask(npc));
}
Iterator<Player> it$ = World.getWorld().getPlayers().iterator();
while(it$.hasNext()) {
Player player = it$.next();
if(!player.getSession().isConnected()) {
it$.remove();
+ } else {
+ tickTasks.add(new PlayerTickTask(player));
+ updateTasks.add(new ConsecutiveTask(new PlayerUpdateTask(player), new NPCUpdateTask(player)));
+ resetTasks.add(new PlayerResetTask(player));
}
- tickTasks.add(new PlayerTickTask(player));
- updateTasks.add(new ConsecutiveTask(new PlayerUpdateTask(player), new NPCUpdateTask(player)));
- resetTasks.add(new PlayerResetTask(player));
}
// ticks can no longer be parallel due to region code
Task tickTask = new ConsecutiveTask(tickTasks.toArray(new Task[0]));
Task updateTask = new ParallelTask(updateTasks.toArray(new Task[0]));
Task resetTask = new ParallelTask(resetTasks.toArray(new Task[0]));
World.getWorld().submit(new ConsecutiveTask(tickTask, updateTask, resetTask));
}
}
| false | true | public void execute() {
List<Task> tickTasks = new ArrayList<Task>();
List<Task> updateTasks = new ArrayList<Task>();
List<Task> resetTasks = new ArrayList<Task>();
for(NPC npc : World.getWorld().getNPCs()) {
tickTasks.add(new NPCTickTask(npc));
resetTasks.add(new NPCResetTask(npc));
}
Iterator<Player> it$ = World.getWorld().getPlayers().iterator();
while(it$.hasNext()) {
Player player = it$.next();
if(!player.getSession().isConnected()) {
it$.remove();
}
tickTasks.add(new PlayerTickTask(player));
updateTasks.add(new ConsecutiveTask(new PlayerUpdateTask(player), new NPCUpdateTask(player)));
resetTasks.add(new PlayerResetTask(player));
}
// ticks can no longer be parallel due to region code
Task tickTask = new ConsecutiveTask(tickTasks.toArray(new Task[0]));
Task updateTask = new ParallelTask(updateTasks.toArray(new Task[0]));
Task resetTask = new ParallelTask(resetTasks.toArray(new Task[0]));
World.getWorld().submit(new ConsecutiveTask(tickTask, updateTask, resetTask));
}
| public void execute() {
List<Task> tickTasks = new ArrayList<Task>();
List<Task> updateTasks = new ArrayList<Task>();
List<Task> resetTasks = new ArrayList<Task>();
for(NPC npc : World.getWorld().getNPCs()) {
tickTasks.add(new NPCTickTask(npc));
resetTasks.add(new NPCResetTask(npc));
}
Iterator<Player> it$ = World.getWorld().getPlayers().iterator();
while(it$.hasNext()) {
Player player = it$.next();
if(!player.getSession().isConnected()) {
it$.remove();
} else {
tickTasks.add(new PlayerTickTask(player));
updateTasks.add(new ConsecutiveTask(new PlayerUpdateTask(player), new NPCUpdateTask(player)));
resetTasks.add(new PlayerResetTask(player));
}
}
// ticks can no longer be parallel due to region code
Task tickTask = new ConsecutiveTask(tickTasks.toArray(new Task[0]));
Task updateTask = new ParallelTask(updateTasks.toArray(new Task[0]));
Task resetTask = new ParallelTask(resetTasks.toArray(new Task[0]));
World.getWorld().submit(new ConsecutiveTask(tickTask, updateTask, resetTask));
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/MainMenuActivity.java b/MPDroid/src/com/namelessdev/mpdroid/MainMenuActivity.java
index a335d014..e0822b11 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/MainMenuActivity.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/MainMenuActivity.java
@@ -1,622 +1,624 @@
package com.namelessdev.mpdroid;
import java.util.ArrayList;
import java.util.List;
import org.a0z.mpd.MPD;
import org.a0z.mpd.MPDStatus;
import org.a0z.mpd.exception.MPDServerException;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.namelessdev.mpdroid.MPDroidActivities.MPDroidFragmentActivity;
import com.namelessdev.mpdroid.fragments.BrowseFragment;
import com.namelessdev.mpdroid.fragments.LibraryFragment;
import com.namelessdev.mpdroid.fragments.NowPlayingFragment;
import com.namelessdev.mpdroid.library.ILibraryFragmentActivity;
import com.namelessdev.mpdroid.library.ILibraryTabActivity;
import com.namelessdev.mpdroid.tools.LibraryTabsUtil;
import com.namelessdev.mpdroid.tools.Tools;
public class MainMenuActivity extends MPDroidFragmentActivity implements OnNavigationListener, ILibraryFragmentActivity,
ILibraryTabActivity, OnBackStackChangedListener {
public static enum DisplayMode {
MODE_NOWPLAYING,
MODE_QUEUE,
MODE_LIBRARY
}
public static class DrawerItem {
public static enum Action {
ACTION_NOWPLAYING,
ACTION_LIBRARY,
ACTION_OUTPUTS
}
public Action action;
public String label;
public DrawerItem(String label, Action action) {
this.label = label;
this.action = action;
}
@Override
public String toString() {
return label;
}
}
public static final int PLAYLIST = 1;
public static final int ARTISTS = 2;
public static final int SETTINGS = 5;
public static final int STREAM = 6;
public static final int LIBRARY = 7;
public static final int CONNECT = 8;
private static final String FRAGMENT_TAG_LIBRARY = "library";
private int backPressExitCount;
private Handler exitCounterReset;
private boolean isDualPaneMode;
private MPDApplication app;
private View nowPlayingDualPane;
private ViewPager nowPlayingPager;
private View libraryRootFrame;
private List<DrawerItem> mDrawerItems;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private int oldDrawerPosition;
private LibraryFragment libraryFragment;
private FragmentManager fragmentManager;
private ArrayList<String> mTabList;
private DisplayMode currentDisplayMode;
@SuppressLint("NewApi")
@TargetApi(11)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MPDApplication) getApplication();
setContentView(app.isTabletUiEnabled() ? R.layout.main_activity_nagvigation_tablet : R.layout.main_activity_nagvigation);
nowPlayingDualPane = findViewById(R.id.nowplaying_dual_pane);
nowPlayingPager = (ViewPager) findViewById(R.id.pager);
libraryRootFrame = findViewById(R.id.library_root_frame);
isDualPaneMode = (nowPlayingDualPane != null);
switchMode(DisplayMode.MODE_NOWPLAYING);
exitCounterReset = new Handler();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerItems = new ArrayList<DrawerItem>();
mDrawerItems.add(new DrawerItem(getString(R.string.nowPlaying), DrawerItem.Action.ACTION_NOWPLAYING));
mDrawerItems.add(new DrawerItem(getString(R.string.libraryTabActivity), DrawerItem.Action.ACTION_LIBRARY));
mDrawerItems.add(new DrawerItem(getString(R.string.outputs), DrawerItem.Action.ACTION_OUTPUTS));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
refreshActionBarTitle();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<DrawerItem>(this,
R.layout.drawer_list_item, mDrawerItems));
oldDrawerPosition = 0;
mDrawerList.setItemChecked(oldDrawerPosition, true);
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
/*
* Setup the library tab
*/
fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
// Get the list of the currently visible tabs
mTabList = LibraryTabsUtil.getCurrentLibraryTabs(this.getApplicationContext());
ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(actionBar.getThemedContext(),
android.R.layout.simple_spinner_item);
for (int i = 0; i < mTabList.size(); i++) {
actionBarAdapter.add(getText(LibraryTabsUtil.getTabTitleResId(mTabList.get(i))));
}
actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
actionBar.setListNavigationCallbacks(actionBarAdapter, this);
libraryFragment = (LibraryFragment) fragmentManager.findFragmentByTag(FRAGMENT_TAG_LIBRARY);
if (libraryFragment == null) {
libraryFragment = new LibraryFragment();
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.library_root_frame, libraryFragment, FRAGMENT_TAG_LIBRARY);
ft.commit();
}
// Setup the pager
- nowPlayingPager.setAdapter(new MainMenuPagerAdapter());
- nowPlayingPager.setOnPageChangeListener(
- new ViewPager.SimpleOnPageChangeListener() {
- @Override
- public void onPageSelected(int position) {
- refreshActionBarTitle();
- }
- });
+ if (nowPlayingPager != null) {
+ nowPlayingPager.setAdapter(new MainMenuPagerAdapter());
+ nowPlayingPager.setOnPageChangeListener(
+ new ViewPager.SimpleOnPageChangeListener() {
+ @Override
+ public void onPageSelected(int position) {
+ refreshActionBarTitle();
+ }
+ });
+ }
}
@Override
public void onStart() {
super.onStart();
MPDApplication app = (MPDApplication) getApplicationContext();
app.setActivity(this);
}
@Override
public void onStop() {
super.onStop();
MPDApplication app = (MPDApplication) getApplicationContext();
app.unsetActivity(this);
}
@Override
protected void onResume() {
super.onResume();
backPressExitCount = 0;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Called when Back button is pressed, displays message to user indicating the if back button is pressed again the application will
* exit. We keep a count of how many time back
* button is pressed within 5 seconds. If the count is greater than 1 then call system.exit(0)
*
* Starts a post delay handler to reset the back press count to zero after 5 seconds
*
* @return None
*/
@Override
public void onBackPressed() {
if (currentDisplayMode == DisplayMode.MODE_LIBRARY) {
final int fmStackCount = fragmentManager.getBackStackEntryCount();
if (fmStackCount > 0) {
super.onBackPressed();
return;
}
}
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final boolean exitConfirmationRequired = settings.getBoolean("enableExitConfirmation", false);
if (exitConfirmationRequired && backPressExitCount < 1) {
Tools.notifyUser(String.format(getResources().getString(R.string.backpressToQuit)), this);
backPressExitCount += 1;
exitCounterReset.postDelayed(new Runnable() {
@Override
public void run() {
backPressExitCount = 0;
}
}, 5000);
} else {
/*
* Nasty force quit, should shutdown everything nicely but there just too many async tasks maybe I'll correctly implement
* app.terminateApplication();
*/
System.exit(0);
}
return;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.mpd_mainmenu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Reminder : never disable buttons that are shown as actionbar actions here
super.onPrepareOptionsMenu(menu);
MPDApplication app = (MPDApplication) this.getApplication();
MPD mpd = app.oMPDAsyncHelper.oMPD;
if (!mpd.isConnected()) {
if (menu.findItem(CONNECT) == null) {
menu.add(0, CONNECT, 0, R.string.connect);
}
} else {
if (menu.findItem(CONNECT) != null) {
menu.removeItem(CONNECT);
}
}
setMenuChecked(menu.findItem(R.id.GMM_Stream), app.getApplicationState().streamingMode);
final MPDStatus mpdStatus = app.getApplicationState().currentMpdStatus;
if (mpdStatus != null) {
setMenuChecked(menu.findItem(R.id.GMM_Single), mpdStatus.isSingle());
setMenuChecked(menu.findItem(R.id.GMM_Consume), mpdStatus.isConsume());
}
return true;
}
private void setMenuChecked(MenuItem item, boolean checked) {
// Set the icon to a checkbox so 2.x users also get one
item.setChecked(checked);
item.setIcon(checked ? R.drawable.btn_check_buttonless_on : R.drawable.btn_check_buttonless_off);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
Intent i = null;
final MPDApplication app = (MPDApplication) this.getApplication();
final MPD mpd = app.oMPDAsyncHelper.oMPD;
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_search:
this.onSearchRequested();
return true;
case R.id.GMM_Settings:
i = new Intent(this, SettingsActivity.class);
startActivityForResult(i, SETTINGS);
return true;
case CONNECT:
((MPDApplication) this.getApplication()).connect();
return true;
case R.id.GMM_Stream:
if (app.getApplicationState().streamingMode) {
i = new Intent(this, StreamingService.class);
i.setAction("com.namelessdev.mpdroid.DIE");
this.startService(i);
((MPDApplication) this.getApplication()).getApplicationState().streamingMode = false;
// Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show();
} else {
if (app.oMPDAsyncHelper.oMPD.isConnected()) {
i = new Intent(this, StreamingService.class);
i.setAction("com.namelessdev.mpdroid.START_STREAMING");
this.startService(i);
((MPDApplication) this.getApplication()).getApplicationState().streamingMode = true;
// Toast.makeText(this, "MPD Streaming Started", Toast.LENGTH_SHORT).show();
}
}
return true;
case R.id.GMM_bonjour:
startActivity(new Intent(this, ServerListActivity.class));
return true;
case R.id.GMM_Consume:
try {
mpd.setConsume(!mpd.getStatus().isConsume());
} catch (MPDServerException e) {
}
return true;
case R.id.GMM_Single:
try {
mpd.setSingle(!mpd.getStatus().isSingle());
} catch (MPDServerException e) {
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
final MPDApplication app = (MPDApplication) getApplicationContext();
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_VOLUME_UP:
new Thread(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD.next();
} catch (MPDServerException e) {
e.printStackTrace();
}
}
}).start();
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
new Thread(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD.previous();
} catch (MPDServerException e) {
e.printStackTrace();
}
}
}).start();
return true;
}
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
// For onKeyLongPress to work
event.startTracking();
return !app.getApplicationState().streamingMode;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, final KeyEvent event) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (event.isTracking() && !event.isCanceled() && !app.getApplicationState().streamingMode) {
new Thread(new Runnable() {
@Override
public void run() {
try {
app.oMPDAsyncHelper.oMPD
.adjustVolume(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP ? NowPlayingFragment.VOLUME_STEP
: -NowPlayingFragment.VOLUME_STEP);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
}).start();
}
return true;
}
return super.onKeyUp(keyCode, event);
}
/**
* Library methods
*/
@Override
public void onBackStackChanged() {
refreshActionBarTitle();
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
libraryFragment.setCurrentItem(itemPosition, true);
return true;
}
@Override
public void pushLibraryFragment(Fragment fragment, String label) {
String title = "";
if (fragment instanceof BrowseFragment) {
title = ((BrowseFragment) fragment).getTitle();
} else {
title = fragment.toString();
}
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.library_root_frame, fragment);
ft.addToBackStack(label);
ft.setBreadCrumbTitle(title);
ft.commit();
}
@Override
public ArrayList<String> getTabList() {
return mTabList;
}
@Override
public void pageChanged(int position) {
final ActionBar actionBar = getActionBar();
if (currentDisplayMode == DisplayMode.MODE_LIBRARY && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST)
actionBar.setSelectedNavigationItem(position);
}
/**
* Navigation Drawer helpers
*/
private void refreshActionBarTitle()
{
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
switch (currentDisplayMode)
{
case MODE_QUEUE:
case MODE_NOWPLAYING:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
if (nowPlayingPager != null && nowPlayingPager.getCurrentItem() > 0) {
actionBar.setTitle(R.string.playQueue);
} else {
actionBar.setTitle(R.string.nowPlaying);
}
break;
case MODE_LIBRARY:
final int fmStackCount = fragmentManager.getBackStackEntryCount();
if (fmStackCount > 0) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(fragmentManager.getBackStackEntryAt(fmStackCount - 1).getBreadCrumbTitle());
} else {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setDisplayShowTitleEnabled(false);
}
break;
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mDrawerList);
switch (((DrawerItem) parent.getItemAtPosition(position)).action) {
default:
case ACTION_LIBRARY:
switchMode(DisplayMode.MODE_LIBRARY);
// If we are already on the library, pop the whole stack. Acts like an "up" button
if (currentDisplayMode == DisplayMode.MODE_LIBRARY) {
final int fmStackCount = fragmentManager.getBackStackEntryCount();
if (fmStackCount > 0) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
break;
case ACTION_NOWPLAYING:
switchMode(DisplayMode.MODE_NOWPLAYING);
break;
case ACTION_OUTPUTS:
mDrawerList.setItemChecked(oldDrawerPosition, true);
final Intent i = new Intent(MainMenuActivity.this, SettingsActivity.class);
i.putExtra(SettingsActivity.OPEN_OUTPUT, true);
startActivityForResult(i, SETTINGS);
break;
}
oldDrawerPosition = position;
}
}
/** Swaps fragments in the main content view */
public void switchMode(DisplayMode newMode) {
currentDisplayMode = newMode;
switch (currentDisplayMode)
{
case MODE_QUEUE:
case MODE_NOWPLAYING:
if (isDualPaneMode) {
nowPlayingDualPane.setVisibility(View.VISIBLE);
} else {
nowPlayingPager.setVisibility(View.VISIBLE);
if (currentDisplayMode == DisplayMode.MODE_NOWPLAYING) {
nowPlayingPager.setCurrentItem(0, true);
} else {
nowPlayingPager.setCurrentItem(1, true);
}
}
libraryRootFrame.setVisibility(View.GONE);
// Force MODE_NOWPLAYING even if MODE_QUEUE was asked
currentDisplayMode = DisplayMode.MODE_NOWPLAYING;
break;
case MODE_LIBRARY:
if (isDualPaneMode) {
nowPlayingDualPane.setVisibility(View.GONE);
} else {
nowPlayingPager.setVisibility(View.GONE);
}
libraryRootFrame.setVisibility(View.VISIBLE);
break;
}
refreshActionBarTitle();
}
class MainMenuPagerAdapter extends PagerAdapter {
public Object instantiateItem(View collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.nowplaying_fragment;
break;
case 1:
resId = R.id.playlist_fragment;
break;
}
return findViewById(resId);
}
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
return;
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MPDApplication) getApplication();
setContentView(app.isTabletUiEnabled() ? R.layout.main_activity_nagvigation_tablet : R.layout.main_activity_nagvigation);
nowPlayingDualPane = findViewById(R.id.nowplaying_dual_pane);
nowPlayingPager = (ViewPager) findViewById(R.id.pager);
libraryRootFrame = findViewById(R.id.library_root_frame);
isDualPaneMode = (nowPlayingDualPane != null);
switchMode(DisplayMode.MODE_NOWPLAYING);
exitCounterReset = new Handler();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerItems = new ArrayList<DrawerItem>();
mDrawerItems.add(new DrawerItem(getString(R.string.nowPlaying), DrawerItem.Action.ACTION_NOWPLAYING));
mDrawerItems.add(new DrawerItem(getString(R.string.libraryTabActivity), DrawerItem.Action.ACTION_LIBRARY));
mDrawerItems.add(new DrawerItem(getString(R.string.outputs), DrawerItem.Action.ACTION_OUTPUTS));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
refreshActionBarTitle();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<DrawerItem>(this,
R.layout.drawer_list_item, mDrawerItems));
oldDrawerPosition = 0;
mDrawerList.setItemChecked(oldDrawerPosition, true);
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
/*
* Setup the library tab
*/
fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
// Get the list of the currently visible tabs
mTabList = LibraryTabsUtil.getCurrentLibraryTabs(this.getApplicationContext());
ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(actionBar.getThemedContext(),
android.R.layout.simple_spinner_item);
for (int i = 0; i < mTabList.size(); i++) {
actionBarAdapter.add(getText(LibraryTabsUtil.getTabTitleResId(mTabList.get(i))));
}
actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
actionBar.setListNavigationCallbacks(actionBarAdapter, this);
libraryFragment = (LibraryFragment) fragmentManager.findFragmentByTag(FRAGMENT_TAG_LIBRARY);
if (libraryFragment == null) {
libraryFragment = new LibraryFragment();
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.library_root_frame, libraryFragment, FRAGMENT_TAG_LIBRARY);
ft.commit();
}
// Setup the pager
nowPlayingPager.setAdapter(new MainMenuPagerAdapter());
nowPlayingPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
refreshActionBarTitle();
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MPDApplication) getApplication();
setContentView(app.isTabletUiEnabled() ? R.layout.main_activity_nagvigation_tablet : R.layout.main_activity_nagvigation);
nowPlayingDualPane = findViewById(R.id.nowplaying_dual_pane);
nowPlayingPager = (ViewPager) findViewById(R.id.pager);
libraryRootFrame = findViewById(R.id.library_root_frame);
isDualPaneMode = (nowPlayingDualPane != null);
switchMode(DisplayMode.MODE_NOWPLAYING);
exitCounterReset = new Handler();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerItems = new ArrayList<DrawerItem>();
mDrawerItems.add(new DrawerItem(getString(R.string.nowPlaying), DrawerItem.Action.ACTION_NOWPLAYING));
mDrawerItems.add(new DrawerItem(getString(R.string.libraryTabActivity), DrawerItem.Action.ACTION_LIBRARY));
mDrawerItems.add(new DrawerItem(getString(R.string.outputs), DrawerItem.Action.ACTION_OUTPUTS));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
refreshActionBarTitle();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<DrawerItem>(this,
R.layout.drawer_list_item, mDrawerItems));
oldDrawerPosition = 0;
mDrawerList.setItemChecked(oldDrawerPosition, true);
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
/*
* Setup the library tab
*/
fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
// Get the list of the currently visible tabs
mTabList = LibraryTabsUtil.getCurrentLibraryTabs(this.getApplicationContext());
ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(actionBar.getThemedContext(),
android.R.layout.simple_spinner_item);
for (int i = 0; i < mTabList.size(); i++) {
actionBarAdapter.add(getText(LibraryTabsUtil.getTabTitleResId(mTabList.get(i))));
}
actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
actionBar.setListNavigationCallbacks(actionBarAdapter, this);
libraryFragment = (LibraryFragment) fragmentManager.findFragmentByTag(FRAGMENT_TAG_LIBRARY);
if (libraryFragment == null) {
libraryFragment = new LibraryFragment();
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.replace(R.id.library_root_frame, libraryFragment, FRAGMENT_TAG_LIBRARY);
ft.commit();
}
// Setup the pager
if (nowPlayingPager != null) {
nowPlayingPager.setAdapter(new MainMenuPagerAdapter());
nowPlayingPager.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
refreshActionBarTitle();
}
});
}
}
|
diff --git a/bindings/java/src/org/hyperic/sigar/FileWatcherThread.java b/bindings/java/src/org/hyperic/sigar/FileWatcherThread.java
index f83abfe7..f174587a 100644
--- a/bindings/java/src/org/hyperic/sigar/FileWatcherThread.java
+++ b/bindings/java/src/org/hyperic/sigar/FileWatcherThread.java
@@ -1,108 +1,109 @@
/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.sigar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class FileWatcherThread implements Runnable {
public static final int DEFAULT_INTERVAL = 60 * 5 * 1000;
private Thread thread = null;
private static FileWatcherThread instance = null;
private boolean shouldDie = false;
private long interval = DEFAULT_INTERVAL;
private Set watchers =
Collections.synchronizedSet(new HashSet());
public static synchronized FileWatcherThread getInstance() {
if (instance == null) {
instance = new FileWatcherThread();
}
return instance;
}
public synchronized void doStart() {
if (this.thread != null) {
return;
}
this.thread = new Thread(this, "FileWatcherThread");
this.thread.setDaemon(true);
this.thread.start();
}
public synchronized void doStop() {
if (this.thread == null) {
return;
}
die();
this.thread.interrupt();
this.thread = null;
}
public void setInterval(long interval) {
this.interval = interval;
}
public long getInterval() {
return this.interval;
}
public void add(FileWatcher watcher) {
this.watchers.add(watcher);
}
public void remove(FileWatcher watcher) {
this.watchers.remove(watcher);
}
public void run() {
while (!shouldDie) {
check();
try {
Thread.sleep(this.interval);
} catch (InterruptedException e) {
}
}
}
public void die() {
this.shouldDie = true;
}
public void check() {
synchronized (this.watchers) {
for (Iterator it = this.watchers.iterator();
it.hasNext();)
{
FileWatcher watcher = (FileWatcher)it.next();
try {
watcher.check();
} catch (Exception e) {
- FileTail.error("Unexception exception", e);
+ FileTail.error("Unexpected exception: " +
+ e.getMessage(), e);
}
}
}
}
}
| true | true | public void check() {
synchronized (this.watchers) {
for (Iterator it = this.watchers.iterator();
it.hasNext();)
{
FileWatcher watcher = (FileWatcher)it.next();
try {
watcher.check();
} catch (Exception e) {
FileTail.error("Unexception exception", e);
}
}
}
}
| public void check() {
synchronized (this.watchers) {
for (Iterator it = this.watchers.iterator();
it.hasNext();)
{
FileWatcher watcher = (FileWatcher)it.next();
try {
watcher.check();
} catch (Exception e) {
FileTail.error("Unexpected exception: " +
e.getMessage(), e);
}
}
}
}
|
diff --git a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/Metadata.java b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/Metadata.java
index 8ade46efa..ef66ecfb8 100644
--- a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/Metadata.java
+++ b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/Metadata.java
@@ -1,181 +1,188 @@
/*-
* Copyright 2012 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.diamond.scisoft.analysis.io;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.SerializationUtils;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
/**
* Basic implementation of metadata
*/
public class Metadata implements IMetaData {
private static final long serialVersionUID = IMetaData.serialVersionUID;
private Map<String, ? extends Serializable> metadata;
// NOTE shapes is LinkedHashMap here because the names collection
// maintained order. Now that we do not need this collection but if we
// do not keep the shapes in a LinkedHashMap, we lose order.
private Map<String,int[]> shapes = new LinkedHashMap<String,int[]>(7);
private Collection<Serializable> userObjects;
private String filePath;
public Metadata() {
}
public Metadata(Map<String, ? extends Serializable> metadata) {
this.metadata = metadata;
}
public Metadata(Collection<String> names) {
if (names != null) {
for (String n : names) {
shapes.put(n, null);
}
}
}
/**
* Set metadata map
* @param metadata
*/
public void setMetadata(Map<String, ? extends Serializable> metadata) {
this.metadata = metadata;
}
/**
* Internal use only
* @return metadata map
*/
protected Map<String, ? extends Serializable> getInternalMetadata() {
return metadata;
}
/**
* Set user objects
* @param objects
*/
public void setUserObjects(Collection<Serializable> objects) {
userObjects = objects;
}
/**
* Add name and shape of a dataset to metadata
*
* @param name
* @param shape (can be null or zero-length)
*
* (NOTE method should be public, people can define loaders outside this
* package like the DESY FIO loader for instance.)
*/
public void addDataInfo(String name, int... shape) {
shapes.put(name, shape == null || shape.length == 0 ? null : shape);
}
@Override
public Collection<String> getDataNames() {
return Collections.unmodifiableCollection(shapes.keySet());
}
@Override
public Map<String, int[]> getDataShapes() {
return Collections.unmodifiableMap(shapes);
}
@Override
public Map<String, Integer> getDataSizes() {
Map<String, Integer> sizes = new HashMap<String, Integer>(1);
for (Entry<String, int[]> e : shapes.entrySet()) {
int[] shape = e.getValue();
if (shape != null && shape.length > 1)
sizes.put(e.getKey(), AbstractDataset.calcSize(shape));
else
sizes.put(e.getKey(), null);
}
if (sizes.size() > 0) {
return Collections.unmodifiableMap(sizes);
}
return null;
}
@Override
public Serializable getMetaValue(String key) throws Exception {
return metadata == null ? null : metadata.get(key);
}
@SuppressWarnings("unchecked")
@Override
public Collection<String> getMetaNames() throws Exception {
return metadata == null ? (Collection<String>) Collections.EMPTY_SET : Collections.unmodifiableCollection(metadata.keySet());
}
@Override
public Collection<Serializable> getUserObjects() {
return userObjects;
}
@Override
public IMetaData clone() {
Metadata c = null;
try {
c = (Metadata) super.clone();
if (metadata != null) {
HashMap<String, Serializable> md = new HashMap<String, Serializable>();
c.metadata = md;
ByteArrayOutputStream os = new ByteArrayOutputStream(512);
for (String k : metadata.keySet()) {
Serializable v = metadata.get(k);
if (v != null) {
SerializationUtils.serialize(v, os);
Serializable nv = (Serializable) SerializationUtils.deserialize(os.toByteArray());
os.reset();
md.put(k, nv);
} else {
md.put(k, null);
}
}
}
c.shapes = new HashMap<String, int[]>(1);
for (Entry<String, int[]> e : shapes.entrySet()) {
int[] s = e.getValue();
c.shapes.put(e.getKey(), s == null ? null : s.clone());
}
} catch (CloneNotSupportedException e) {
+ // Allowed for some objects not to be cloned.
+ } catch (Throwable e) {
+ if (e instanceof ClassNotFoundException) {
+ // Fix to http://jira.diamond.ac.uk/browse/SCI-1644
+ // Happens when cloning meta data with GridPreferences
+ }
+ throw e;
}
return c;
}
@Override
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| true | true | public IMetaData clone() {
Metadata c = null;
try {
c = (Metadata) super.clone();
if (metadata != null) {
HashMap<String, Serializable> md = new HashMap<String, Serializable>();
c.metadata = md;
ByteArrayOutputStream os = new ByteArrayOutputStream(512);
for (String k : metadata.keySet()) {
Serializable v = metadata.get(k);
if (v != null) {
SerializationUtils.serialize(v, os);
Serializable nv = (Serializable) SerializationUtils.deserialize(os.toByteArray());
os.reset();
md.put(k, nv);
} else {
md.put(k, null);
}
}
}
c.shapes = new HashMap<String, int[]>(1);
for (Entry<String, int[]> e : shapes.entrySet()) {
int[] s = e.getValue();
c.shapes.put(e.getKey(), s == null ? null : s.clone());
}
} catch (CloneNotSupportedException e) {
}
return c;
}
| public IMetaData clone() {
Metadata c = null;
try {
c = (Metadata) super.clone();
if (metadata != null) {
HashMap<String, Serializable> md = new HashMap<String, Serializable>();
c.metadata = md;
ByteArrayOutputStream os = new ByteArrayOutputStream(512);
for (String k : metadata.keySet()) {
Serializable v = metadata.get(k);
if (v != null) {
SerializationUtils.serialize(v, os);
Serializable nv = (Serializable) SerializationUtils.deserialize(os.toByteArray());
os.reset();
md.put(k, nv);
} else {
md.put(k, null);
}
}
}
c.shapes = new HashMap<String, int[]>(1);
for (Entry<String, int[]> e : shapes.entrySet()) {
int[] s = e.getValue();
c.shapes.put(e.getKey(), s == null ? null : s.clone());
}
} catch (CloneNotSupportedException e) {
// Allowed for some objects not to be cloned.
} catch (Throwable e) {
if (e instanceof ClassNotFoundException) {
// Fix to http://jira.diamond.ac.uk/browse/SCI-1644
// Happens when cloning meta data with GridPreferences
}
throw e;
}
return c;
}
|
diff --git a/src/nu/validator/htmlparser/impl/Tokenizer.java b/src/nu/validator/htmlparser/impl/Tokenizer.java
index 6c1c6f1..a63347c 100755
--- a/src/nu/validator/htmlparser/impl/Tokenizer.java
+++ b/src/nu/validator/htmlparser/impl/Tokenizer.java
@@ -1,5264 +1,5264 @@
/*
* Copyright (c) 2005, 2006, 2007 Henri Sivonen
* Copyright (c) 2007-2008 Mozilla Foundation
* Portions of comments Copyright 2004-2007 Apple Computer, Inc., Mozilla
* Foundation, and Opera Software ASA.
*
* 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.
*/
/*
* The comments following this one that use the same comment syntax as this
* comment are quotes from the WHATWG HTML 5 spec as of 2 June 2007
* amended as of June 18 2008.
* That document came with this statement:
* "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and
* Opera Software ASA. You are granted a license to use, reproduce and
* create derivative works of this document."
*/
package nu.validator.htmlparser.impl;
import nu.validator.htmlparser.annotation.Local;
import nu.validator.htmlparser.annotation.NoLength;
import nu.validator.htmlparser.common.EncodingDeclarationHandler;
import nu.validator.htmlparser.common.TokenHandler;
import nu.validator.htmlparser.common.XmlViolationPolicy;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* An implementation of
* http://www.whatwg.org/specs/web-apps/current-work/multipage/section-tokenisation.html
*
* This class implements the <code>Locator</code> interface. This is not an
* incidental implementation detail: Users of this class are encouraged to make
* use of the <code>Locator</code> nature.
*
* By default, the tokenizer may report data that XML 1.0 bans. The tokenizer
* can be configured to treat these conditions as fatal or to coerce the infoset
* to something that XML 1.0 allows.
*
* @version $Id$
* @author hsivonen
*/
public final class Tokenizer implements Locator {
private static final int DATA = 0;
private static final int RCDATA = 1;
private static final int CDATA = 2;
private static final int PLAINTEXT = 3;
private static final int TAG_OPEN = 49;
private static final int CLOSE_TAG_OPEN_PCDATA = 50;
private static final int TAG_NAME = 58;
private static final int BEFORE_ATTRIBUTE_NAME = 4;
private static final int ATTRIBUTE_NAME = 5;
private static final int AFTER_ATTRIBUTE_NAME = 6;
private static final int BEFORE_ATTRIBUTE_VALUE = 7;
private static final int ATTRIBUTE_VALUE_DOUBLE_QUOTED = 8;
private static final int ATTRIBUTE_VALUE_SINGLE_QUOTED = 9;
private static final int ATTRIBUTE_VALUE_UNQUOTED = 10;
private static final int AFTER_ATTRIBUTE_VALUE_QUOTED = 11;
private static final int BOGUS_COMMENT = 12;
private static final int MARKUP_DECLARATION_OPEN = 13;
private static final int DOCTYPE = 14;
private static final int BEFORE_DOCTYPE_NAME = 15;
private static final int DOCTYPE_NAME = 16;
private static final int AFTER_DOCTYPE_NAME = 17;
private static final int BEFORE_DOCTYPE_PUBLIC_IDENTIFIER = 18;
private static final int DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED = 19;
private static final int DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED = 20;
private static final int AFTER_DOCTYPE_PUBLIC_IDENTIFIER = 21;
private static final int BEFORE_DOCTYPE_SYSTEM_IDENTIFIER = 22;
private static final int DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED = 23;
private static final int DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED = 24;
private static final int AFTER_DOCTYPE_SYSTEM_IDENTIFIER = 25;
private static final int BOGUS_DOCTYPE = 26;
private static final int COMMENT_START = 27;
private static final int COMMENT_START_DASH = 28;
private static final int COMMENT = 29;
private static final int COMMENT_END_DASH = 30;
private static final int COMMENT_END = 31;
private static final int CLOSE_TAG_OPEN_NOT_PCDATA = 32;
private static final int MARKUP_DECLARATION_HYPHEN = 33;
private static final int MARKUP_DECLARATION_OCTYPE = 34;
private static final int DOCTYPE_UBLIC = 35;
private static final int DOCTYPE_YSTEM = 36;
private static final int CONSUME_CHARACTER_REFERENCE = 37;
private static final int CONSUME_NCR = 38;
private static final int CHARACTER_REFERENCE_LOOP = 39;
private static final int HEX_NCR_LOOP = 41;
private static final int DECIMAL_NRC_LOOP = 42;
private static final int HANDLE_NCR_VALUE = 43;
private static final int SELF_CLOSING_START_TAG = 44;
private static final int CDATA_START = 45;
private static final int CDATA_SECTION = 46;
private static final int CDATA_RSQB = 47;
private static final int CDATA_RSQB_RSQB = 48;
private static final int TAG_OPEN_NON_PCDATA = 51;
private static final int ESCAPE_EXCLAMATION = 52;
private static final int ESCAPE_EXCLAMATION_HYPHEN = 53;
private static final int ESCAPE = 54;
private static final int ESCAPE_HYPHEN = 55;
private static final int ESCAPE_HYPHEN_HYPHEN = 56;
private static final int BOGUS_COMMENT_HYPHEN = 57;
/**
* Magic value for UTF-16 operations.
*/
private static final int LEAD_OFFSET = 0xD800 - (0x10000 >> 10);
/**
* Magic value for UTF-16 operations.
*/
private static final int SURROGATE_OFFSET = 0x10000 - (0xD800 << 10) - 0xDC00;
/**
* UTF-16 code unit array containing less than and greater than for emitting
* those characters on certain parse errors.
*/
private static final @NoLength char[] LT_GT = { '<', '>' };
/**
* UTF-16 code unit array containing less than and solidus for emitting
* those characters on certain parse errors.
*/
private static final @NoLength char[] LT_SOLIDUS = { '<', '/' };
/**
* UTF-16 code unit array containing ]] for emitting those characters on
* state transitions.
*/
private static final @NoLength char[] RSQB_RSQB = { ']', ']' };
/**
* Array version of U+FFFD.
*/
private static final char[] REPLACEMENT_CHARACTER = { '\uFFFD' };
/**
* Array version of space.
*/
private static final char[] SPACE = { ' ' };
/**
* Array version of line feed.
*/
private static final char[] LF = { '\n' };
/**
* Buffer growth parameter.
*/
private static final int BUFFER_GROW_BY = 1024;
/**
* "CDATA[" as <code>char[]</code>
*/
private static final @NoLength char[] CDATA_LSQB = "CDATA[".toCharArray();
/**
* "octype" as <code>char[]</code>
*/
private static final @NoLength char[] OCTYPE = "octype".toCharArray();
/**
* "ublic" as <code>char[]</code>
*/
private static final @NoLength char[] UBLIC = "ublic".toCharArray();
/**
* "ystem" as <code>char[]</code>
*/
private static final @NoLength char[] YSTEM = "ystem".toCharArray();
private final EncodingDeclarationHandler encodingDeclarationHandler;
/**
* The token handler.
*/
private final TokenHandler tokenHandler;
/**
* The error handler.
*/
private ErrorHandler errorHandler;
/**
* The previous <code>char</code> read from the buffer with infoset
* alteration applied except for CR. Used for CRLF normalization and
* surrogate pair checking.
*/
private char prev;
/**
* The current line number in the current resource being parsed. (First line
* is 1.) Passed on as locator data.
*/
private int line;
private int linePrev;
/**
* The current column number in the current resource being tokenized. (First
* column is 1, counted by UTF-16 code units.) Passed on as locator data.
*/
private int col;
private int colPrev;
private boolean nextCharOnNewLine;
private int stateSave;
private int returnStateSave;
private int index;
private boolean forceQuirks;
private char additional;
private int entCol;
private int lo;
private int hi;
private int candidate;
private int strBufMark;
private int prevValue;
private int value;
private boolean seenDigits;
private int pos;
private int end;
private @NoLength char[] buf;
private int cstart;
/**
* The SAX public id for the resource being tokenized. (Only passed to back
* as part of locator data.)
*/
private String publicId;
/**
* The SAX system id for the resource being tokenized. (Only passed to back
* as part of locator data.)
*/
private String systemId;
/**
* Buffer for short identifiers.
*/
private char[] strBuf;
/**
* Number of significant <code>char</code>s in <code>strBuf</code>.
*/
private int strBufLen = 0;
/**
* <code>-1</code> to indicate that <code>strBuf</code> is used or
* otherwise an offset to the main buffer.
*/
private int strBufOffset = -1;
/**
* Buffer for long strings.
*/
private char[] longStrBuf;
/**
* Number of significant <code>char</code>s in <code>longStrBuf</code>.
*/
private int longStrBufLen = 0;
/**
* <code>-1</code> to indicate that <code>longStrBuf</code> is used or
* otherwise an offset to the main buffer.
*/
private int longStrBufOffset = -1;
/**
* The attribute holder.
*/
private HtmlAttributes attributes;
/**
* Buffer for expanding NCRs falling into the Basic Multilingual Plane.
*/
private final char[] bmpChar = new char[1];
/**
* Buffer for expanding astral NCRs.
*/
private final char[] astralChar = new char[2];
/**
* Keeps track of PUA warnings.
*/
private boolean alreadyWarnedAboutPrivateUseCharacters;
/**
* http://www.whatwg.org/specs/web-apps/current-work/#content2
*/
private ContentModelFlag contentModelFlag = ContentModelFlag.PCDATA;
/**
* The element whose end tag closes the current CDATA or RCDATA element.
*/
private ElementName contentModelElement = null;
/**
* <code>true</code> if tokenizing an end tag
*/
private boolean endTag;
/**
* The current tag token name.
*/
private ElementName tagName = null;
/**
* The current attribute name.
*/
private AttributeName attributeName = null;
/**
* Whether comment tokens are emitted.
*/
private boolean wantsComments = false;
/**
* If <code>false</code>, <code>addAttribute*()</code> are no-ops.
*/
private boolean shouldAddAttributes;
/**
* <code>true</code> when HTML4-specific additional errors are requested.
*/
private boolean html4;
/**
* Used together with <code>nonAsciiProhibited</code>.
*/
private boolean alreadyComplainedAboutNonAscii;
/**
* Whether the stream is past the first 512 bytes.
*/
private boolean metaBoundaryPassed;
/**
* The name of the current doctype token.
*/
private @Local String doctypeName;
/**
* The public id of the current doctype token.
*/
private String publicIdentifier;
/**
* The system id of the current doctype token.
*/
private String systemIdentifier;
// [NOCPP[
/**
* The policy for vertical tab and form feed.
*/
private XmlViolationPolicy contentSpacePolicy = XmlViolationPolicy.ALTER_INFOSET;
/**
* The policy for non-space non-XML characters.
*/
private XmlViolationPolicy contentNonXmlCharPolicy = XmlViolationPolicy.ALTER_INFOSET;
/**
* The policy for comments.
*/
private XmlViolationPolicy commentPolicy = XmlViolationPolicy.ALTER_INFOSET;
private XmlViolationPolicy xmlnsPolicy = XmlViolationPolicy.ALTER_INFOSET;
private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET;
private boolean html4ModeCompatibleWithXhtml1Schemata;
private final boolean newAttributesEachTime;
// ]NOCPP]
private int mappingLangToXmlLang;
private boolean shouldSuspend;
private Confidence confidence;
private PushedLocation pushedLocation;
/**
* The constructor.
*
* @param tokenHandler
* the handler for receiving tokens
*/
public Tokenizer(TokenHandler tokenHandler) {
this.tokenHandler = tokenHandler;
this.encodingDeclarationHandler = null;
this.newAttributesEachTime = false;
}
public Tokenizer(TokenHandler tokenHandler, EncodingDeclarationHandler encodingDeclarationHandler) {
this.tokenHandler = tokenHandler;
this.encodingDeclarationHandler = encodingDeclarationHandler;
this.newAttributesEachTime = false;
}
public void initLocation(String newPublicId, String newSystemId) {
this.systemId = newSystemId;
this.publicId = newPublicId;
}
// [NOCPP[
public Tokenizer(TokenHandler tokenHandler, EncodingDeclarationHandler encodingDeclarationHandler, boolean newAttributesEachTime) {
this.tokenHandler = tokenHandler;
this.encodingDeclarationHandler = encodingDeclarationHandler;
this.newAttributesEachTime = newAttributesEachTime;
}
// ]NOCPP]
/**
* Returns the mappingLangToXmlLang.
*
* @return the mappingLangToXmlLang
*/
public boolean isMappingLangToXmlLang() {
return mappingLangToXmlLang == AttributeName.HTML_LANG;
}
/**
* Sets the mappingLangToXmlLang.
*
* @param mappingLangToXmlLang
* the mappingLangToXmlLang to set
*/
public void setMappingLangToXmlLang(boolean mappingLangToXmlLang) {
this.mappingLangToXmlLang = mappingLangToXmlLang ? AttributeName.HTML_LANG
: AttributeName.HTML;
}
/**
* Sets the error handler.
*
* @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler)
*/
public void setErrorHandler(ErrorHandler eh) {
this.errorHandler = eh;
}
public ErrorHandler getErrorHandler() {
return this.errorHandler;
}
// [NOCPP[
/**
* Sets the commentPolicy.
*
* @param commentPolicy
* the commentPolicy to set
*/
public void setCommentPolicy(XmlViolationPolicy commentPolicy) {
this.commentPolicy = commentPolicy;
}
/**
* Sets the contentNonXmlCharPolicy.
*
* @param contentNonXmlCharPolicy
* the contentNonXmlCharPolicy to set
*/
public void setContentNonXmlCharPolicy(
XmlViolationPolicy contentNonXmlCharPolicy) {
this.contentNonXmlCharPolicy = contentNonXmlCharPolicy;
}
/**
* Sets the contentSpacePolicy.
*
* @param contentSpacePolicy
* the contentSpacePolicy to set
*/
public void setContentSpacePolicy(XmlViolationPolicy contentSpacePolicy) {
this.contentSpacePolicy = contentSpacePolicy;
}
/**
* Sets the xmlnsPolicy.
*
* @param xmlnsPolicy
* the xmlnsPolicy to set
*/
public void setXmlnsPolicy(XmlViolationPolicy xmlnsPolicy) {
if (xmlnsPolicy == XmlViolationPolicy.FATAL) {
throw new IllegalArgumentException("Can't use FATAL here.");
}
this.xmlnsPolicy = xmlnsPolicy;
}
public void setNamePolicy(XmlViolationPolicy namePolicy) {
this.namePolicy = namePolicy;
}
/**
* Sets the html4ModeCompatibleWithXhtml1Schemata.
*
* @param html4ModeCompatibleWithXhtml1Schemata
* the html4ModeCompatibleWithXhtml1Schemata to set
*/
public void setHtml4ModeCompatibleWithXhtml1Schemata(
boolean html4ModeCompatibleWithXhtml1Schemata) {
this.html4ModeCompatibleWithXhtml1Schemata = html4ModeCompatibleWithXhtml1Schemata;
}
// ]NOCPP]
// For the token handler to call
/**
* Sets the content model flag and the associated element name.
*
* @param contentModelFlag
* the flag
* @param contentModelElement
* the element causing the flag to be set
*/
public void setContentModelFlag(ContentModelFlag contentModelFlag,
@Local String contentModelElement) {
this.contentModelFlag = contentModelFlag;
char[] asArray = Portability.newCharArrayFromLocal(contentModelElement);
this.contentModelElement = ElementName.elementNameByBuffer(asArray, 0,
asArray.length);
}
/**
* Sets the content model flag and the associated element name.
*
* @param contentModelFlag
* the flag
* @param contentModelElement
* the element causing the flag to be set
*/
public void setContentModelFlag(ContentModelFlag contentModelFlag,
ElementName contentModelElement) {
this.contentModelFlag = contentModelFlag;
this.contentModelElement = contentModelElement;
}
// start Locator impl
/**
* @see org.xml.sax.Locator#getPublicId()
*/
public String getPublicId() {
return publicId;
}
/**
* @see org.xml.sax.Locator#getSystemId()
*/
public String getSystemId() {
return systemId;
}
/**
* @see org.xml.sax.Locator#getLineNumber()
*/
public int getLineNumber() {
if (line > 0) {
return line;
} else {
return -1;
}
}
/**
* @see org.xml.sax.Locator#getColumnNumber()
*/
public int getColumnNumber() {
if (col > 0) {
return col;
} else {
return -1;
}
}
// end Locator impl
// end public API
public void notifyAboutMetaBoundary() {
metaBoundaryPassed = true;
}
// [NOCPP[
void turnOnAdditionalHtml4Errors() {
html4 = true;
}
// ]NOCPP]
HtmlAttributes emptyAttributes() {
// [NOCPP[
if (newAttributesEachTime) {
return new HtmlAttributes(mappingLangToXmlLang);
} else {
// ]NOCPP]
return HtmlAttributes.EMPTY_ATTRIBUTES;
// [NOCPP[
}
// ]NOCPP]
}
private void detachStrBuf() {
// if (strBufOffset == -1) {
// return;
// }
// if (strBufLen > 0) {
// if (strBuf.length < strBufLen) {
// Portability.releaseArray(strBuf);
// strBuf = new char[strBufLen + (strBufLen >> 1)];
// }
// System.arraycopy(buf, strBufOffset, strBuf, 0, strBufLen);
// }
// strBufOffset = -1;
}
private void detachLongStrBuf() {
// if (longStrBufOffset == -1) {
// return;
// }
// if (longStrBufLen > 0) {
// if (longStrBuf.length < longStrBufLen) {
// Portability.releaseArray(longStrBuf);
// longStrBuf = new char[longStrBufLen + (longStrBufLen >> 1)];
// }
// System.arraycopy(buf, longStrBufOffset, longStrBuf, 0,
// longStrBufLen);
// }
// longStrBufOffset = -1;
}
private void clearStrBufAndAppendCurrentC() {
strBuf[0] = buf[pos]; // test
strBufLen = 1;
// strBufOffset = pos;
}
private void clearStrBufAndAppendForceWrite(char c) {
strBuf[0] = c; // test
strBufLen = 1;
// strBufOffset = pos;
// buf[pos] = c;
}
private void clearStrBufForNextState() {
strBufLen = 0;
// strBufOffset = pos + 1;
}
/**
* Appends to the smaller buffer.
*
* @param c
* the UTF-16 code unit to append
*/
private void appendStrBuf(char c) {
// if (strBufOffset != -1) {
// strBufLen++;
// } else {
if (strBufLen == strBuf.length) {
char[] newBuf = new char[strBuf.length
+ Tokenizer.BUFFER_GROW_BY];
System.arraycopy(strBuf, 0, newBuf, 0, strBuf.length);
strBuf = newBuf;
}
strBuf[strBufLen++] = c;
// }
}
/**
* Appends to the smaller buffer.
*
* @param c
* the UTF-16 code unit to append
*/
private void appendStrBufForceWrite(char c) {
// if (strBufOffset != -1) {
// strBufLen++;
// buf[pos] = c;
// } else {
if (strBufLen == strBuf.length) {
char[] newBuf = new char[strBuf.length
+ Tokenizer.BUFFER_GROW_BY];
System.arraycopy(strBuf, 0, newBuf, 0, strBuf.length);
strBuf = newBuf;
}
strBuf[strBufLen++] = c;
// }
}
/**
* The smaller buffer as a String.
*
* @return the smaller buffer as a string
*/
private String strBufToString() {
// if (strBufOffset != -1) {
// return Portability.newStringFromBuffer(buf, strBufOffset, strBufLen);
// } else {
return Portability.newStringFromBuffer(strBuf, 0, strBufLen);
// }
}
/**
* Emits the smaller buffer as character tokens.
*
* @throws SAXException
* if the token handler threw
*/
private void emitStrBuf() throws SAXException {
if (strBufLen > 0) {
// if (strBufOffset != -1) {
// tokenHandler.characters(buf, strBufOffset, strBufLen);
// } else {
tokenHandler.characters(strBuf, 0, strBufLen);
// }
}
}
private void clearLongStrBufForNextState() {
// longStrBufOffset = pos + 1;
longStrBufLen = 0;
}
private void clearLongStrBuf() {
// longStrBufOffset = pos;
longStrBufLen = 0;
}
private void clearLongStrBufAndAppendCurrentC() {
longStrBuf[0] = buf[pos];
longStrBufLen = 1;
// longStrBufOffset = pos;
}
private void clearLongStrBufAndAppendToComment(char c) {
longStrBuf[0] = c;
// longStrBufOffset = pos;
longStrBufLen = 1;
}
/**
* Appends to the larger buffer.
*
* @param c
* the UTF-16 code unit to append
*/
private void appendLongStrBuf(char c) {
// if (longStrBufOffset != -1) {
// longStrBufLen++;
// } else {
if (longStrBufLen == longStrBuf.length) {
char[] newBuf = new char[longStrBufLen + (longStrBufLen >> 1)];
System.arraycopy(longStrBuf, 0, newBuf, 0, longStrBuf.length);
Portability.releaseArray(longStrBuf);
longStrBuf = newBuf;
}
longStrBuf[longStrBufLen++] = c;
// }
}
private void appendSecondHyphenToBogusComment() throws SAXException {
switch (commentPolicy) {
case ALTER_INFOSET:
// detachLongStrBuf();
appendLongStrBuf(' ');
// FALLTHROUGH
case ALLOW:
warn("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment.");
appendLongStrBuf('-');
break;
case FATAL:
fatal("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment.");
break;
}
}
private void maybeAppendSpaceToBogusComment() throws SAXException {
switch (commentPolicy) {
case ALTER_INFOSET:
// detachLongStrBuf();
appendLongStrBuf(' ');
// FALLTHROUGH
case ALLOW:
warn("The document is not mappable to XML 1.0 due to a trailing hyphen in a comment.");
break;
case FATAL:
fatal("The document is not mappable to XML 1.0 due to a trailing hyphen in a comment.");
break;
}
}
private void adjustDoubleHyphenAndAppendToLongStrBuf(char c)
throws SAXException {
switch (commentPolicy) {
case ALTER_INFOSET:
// detachLongStrBuf();
longStrBufLen--;
appendLongStrBuf(' ');
appendLongStrBuf('-');
// FALLTHROUGH
case ALLOW:
warn("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment.");
appendLongStrBuf(c);
break;
case FATAL:
fatal("The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment.");
break;
}
}
private void appendLongStrBuf(char[] buffer, int offset, int length) {
int reqLen = longStrBufLen + length;
if (longStrBuf.length < reqLen) {
char[] newBuf = new char[reqLen + (reqLen >> 1)];
System.arraycopy(longStrBuf, 0, newBuf, 0, longStrBuf.length);
Portability.releaseArray(longStrBuf);
longStrBuf = newBuf;
}
System.arraycopy(buffer, offset, longStrBuf, longStrBufLen, length);
longStrBufLen = reqLen;
}
/**
* Appends to the larger buffer.
*
* @param arr
* the UTF-16 code units to append
*/
private void appendLongStrBuf(char[] arr) {
// assert longStrBufOffset == -1;
appendLongStrBuf(arr, 0, arr.length);
}
/**
* Append the contents of the smaller buffer to the larger one.
*/
private void appendStrBufToLongStrBuf() {
// assert longStrBufOffset == -1;
// if (strBufOffset != -1) {
// appendLongStrBuf(buf, strBufOffset, strBufLen);
// } else {
appendLongStrBuf(strBuf, 0, strBufLen);
// }
}
/**
* The larger buffer as a string.
*
* @return the larger buffer as a string
*/
private String longStrBufToString() {
// if (longStrBufOffset != -1) {
// return Portability.newStringFromBuffer(buf, longStrBufOffset,
// longStrBufLen);
// } else {
return Portability.newStringFromBuffer(longStrBuf, 0, longStrBufLen);
// }
}
/**
* Emits the current comment token.
*
* @throws SAXException
*/
private void emitComment(int provisionalHyphens) throws SAXException {
if (wantsComments) {
// if (longStrBufOffset != -1) {
// tokenHandler.comment(buf, longStrBufOffset, longStrBufLen
// - provisionalHyphens);
// } else {
tokenHandler.comment(longStrBuf, 0, longStrBufLen
- provisionalHyphens);
// }
}
cstart = pos + 1;
}
// [NOCPP[
private String toUPlusString(char c) {
String hexString = Integer.toHexString(c);
switch (hexString.length()) {
case 1:
return "U+000" + hexString;
case 2:
return "U+00" + hexString;
case 3:
return "U+0" + hexString;
case 4:
return "U+" + hexString;
default:
throw new RuntimeException("Unreachable.");
}
}
// ]NOCPP]
/**
* Emits a warning about private use characters if the warning has not been
* emitted yet.
*
* @throws SAXException
*/
private void warnAboutPrivateUseChar() throws SAXException {
if (!alreadyWarnedAboutPrivateUseCharacters) {
warn("Document uses the Unicode Private Use Area(s), which should not be used in publicly exchanged documents. (Charmod C073)");
alreadyWarnedAboutPrivateUseCharacters = true;
}
}
/**
* Tells if the argument is a BMP PUA character.
*
* @param c
* the UTF-16 code unit to check
* @return <code>true</code> if PUA character
*/
private boolean isPrivateUse(char c) {
return c >= '\uE000' && c <= '\uF8FF';
}
/**
* Tells if the argument is an astral PUA character.
*
* @param c
* the code point to check
* @return <code>true</code> if astral private use
*/
private boolean isAstralPrivateUse(int c) {
return (c >= 0xF0000 && c <= 0xFFFFD)
|| (c >= 0x100000 && c <= 0x10FFFD);
}
/**
* Tells if the argument is a non-character (works for BMP and astral).
*
* @param c
* the code point to check
* @return <code>true</code> if non-character
*/
private boolean isNonCharacter(int c) {
return (c & 0xFFFE) == 0xFFFE;
}
/**
* Flushes coalesced character tokens.
*
* @throws SAXException
*/
private void flushChars() throws SAXException {
if (pos > cstart) {
int currLine = line;
int currCol = col;
line = linePrev;
col = colPrev;
tokenHandler.characters(buf, cstart, pos - cstart);
line = currLine;
col = currCol;
}
cstart = Integer.MAX_VALUE;
}
/**
* Reports an condition that would make the infoset incompatible with XML
* 1.0 as fatal.
*
* @param message
* the message
* @throws SAXException
* @throws SAXParseException
*/
public void fatal(String message) throws SAXException {
SAXParseException spe = new SAXParseException(message, this);
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
/**
* Reports a Parse Error.
*
* @param message
* the message
* @throws SAXException
*/
public void err(String message) throws SAXException {
if (errorHandler == null) {
return;
}
SAXParseException spe = new SAXParseException(message, this);
errorHandler.error(spe);
}
public void errTreeBuilder(String message) throws SAXException {
ErrorHandler eh = null;
if (tokenHandler instanceof TreeBuilder<?>) {
TreeBuilder<?> treeBuilder = (TreeBuilder<?>) tokenHandler;
eh = treeBuilder.getErrorHandler();
}
if (eh == null) {
eh = errorHandler;
}
if (eh == null) {
return;
}
SAXParseException spe = new SAXParseException(message, this);
eh.error(spe);
}
/**
* Reports a warning
*
* @param message
* the message
* @throws SAXException
*/
public void warn(String message) throws SAXException {
if (errorHandler == null) {
return;
}
SAXParseException spe = new SAXParseException(message, this);
errorHandler.warning(spe);
}
/**
*
*/
private void resetAttributes() {
// [NOCPP[
if (newAttributesEachTime) {
attributes = null;
} else {
// ]NOCPP]
attributes.clear();
// [NOCPP[
}
// ]NOCPP]
}
private ElementName strBufToElementNameString() {
// if (strBufOffset != -1) {
// return ElementName.elementNameByBuffer(buf, strBufOffset, strBufLen);
// } else {
return ElementName.elementNameByBuffer(strBuf, 0, strBufLen);
// }
}
private int emitCurrentTagToken(boolean selfClosing) throws SAXException {
cstart = pos + 1;
if (selfClosing && endTag) {
err("Stray \u201C/\u201D at the end of an end tag.");
}
int rv = Tokenizer.DATA;
HtmlAttributes attrs = (attributes == null ? HtmlAttributes.EMPTY_ATTRIBUTES
: attributes);
if (endTag) {
/*
* When an end tag token is emitted, the content model flag must be
* switched to the PCDATA state.
*/
contentModelFlag = ContentModelFlag.PCDATA;
if (attrs.getLength() != 0) {
/*
* When an end tag token is emitted with attributes, that is a
* parse error.
*/
err("End tag had attributes.");
}
tokenHandler.endTag(tagName);
} else {
tokenHandler.startTag(tagName, attrs, selfClosing);
switch (contentModelFlag) {
case PCDATA:
rv = Tokenizer.DATA;
break;
case CDATA:
rv = Tokenizer.CDATA;
break;
case RCDATA:
rv = Tokenizer.RCDATA;
break;
case PLAINTEXT:
rv = Tokenizer.PLAINTEXT;
}
}
return rv;
}
private void attributeNameComplete() throws SAXException {
// if (strBufOffset != -1) {
// attributeName = AttributeName.nameByBuffer(buf, strBufOffset,
// strBufLen, namePolicy != XmlViolationPolicy.ALLOW);
// } else {
attributeName = AttributeName.nameByBuffer(strBuf, 0, strBufLen,
namePolicy != XmlViolationPolicy.ALLOW);
// }
// [NOCPP[
if (attributes == null) {
attributes = new HtmlAttributes(mappingLangToXmlLang);
}
// ]NOCPP]
/*
* When the user agent leaves the attribute name state (and before
* emitting the tag token, if appropriate), the complete attribute's
* name must be compared to the other attributes on the same token; if
* there is already an attribute on the token with the exact same name,
* then this is a parse error and the new attribute must be dropped,
* along with the value that gets associated with it (if any).
*/
if (attributes.contains(attributeName)) {
shouldAddAttributes = false;
err("Duplicate attribute \u201C"
+ attributeName.getLocal(AttributeName.HTML) + "\u201D.");
} else {
shouldAddAttributes = true;
// if (namePolicy == XmlViolationPolicy.ALLOW) {
// shouldAddAttributes = true;
// } else {
// if (NCName.isNCName(attributeName)) {
// shouldAddAttributes = true;
// } else {
// if (namePolicy == XmlViolationPolicy.FATAL) {
// fatal("Attribute name \u201C" + attributeName
// + "\u201D is not an NCName.");
// } else {
// shouldAddAttributes = false;
// warn("Attribute name \u201C"
// + attributeName
// + "\u201D is not an NCName. Ignoring the attribute.");
// }
// }
// }
}
}
private void addAttributeWithoutValue() throws SAXException {
// [NOCPP[
if (metaBoundaryPassed && AttributeName.CHARSET == attributeName
&& ElementName.META == tagName) {
err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes.");
}
// ]NOCPP]
if (shouldAddAttributes) {
// [NOCPP[
if (html4) {
if (attributeName.isBoolean()) {
if (html4ModeCompatibleWithXhtml1Schemata) {
attributes.addAttribute(attributeName,
attributeName.getLocal(AttributeName.HTML),
xmlnsPolicy);
} else {
attributes.addAttribute(attributeName, "", xmlnsPolicy);
}
} else {
err("Attribute value omitted for a non-boolean attribute. (HTML4-only error.)");
attributes.addAttribute(attributeName, "", xmlnsPolicy);
}
} else {
if (AttributeName.SRC == attributeName
|| AttributeName.HREF == attributeName) {
warn("Attribute \u201C"
+ attributeName.getLocal(AttributeName.HTML)
+ "\u201D without an explicit value seen. The attribute may be dropped by IE7.");
}
// ]NOCPP]
attributes.addAttribute(attributeName, "", xmlnsPolicy);
// [NOCPP[
}
// ]NOCPP]
}
}
private void addAttributeWithValue() throws SAXException {
// [NOCPP[
if (metaBoundaryPassed && ElementName.META == tagName
&& AttributeName.CHARSET == attributeName) {
err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes.");
}
// ]NOCPP]
if (shouldAddAttributes) {
String value = longStrBufToString();
// [NOCPP[
if (!endTag && html4 && html4ModeCompatibleWithXhtml1Schemata
&& attributeName.isCaseFolded()) {
value = newAsciiLowerCaseStringFromString(value);
}
// ]NOCPP]
attributes.addAttribute(attributeName, value, xmlnsPolicy);
}
}
// [NOCPP[
private static String newAsciiLowerCaseStringFromString(String str) {
if (str == null) {
return null;
}
char[] buf = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'A' && c <= 'Z') {
c += 0x20;
}
buf[i] = c;
}
return new String(buf);
}
// ]NOCPP]
public void start() throws SAXException {
strBuf = new char[64];
longStrBuf = new char[1024];
alreadyComplainedAboutNonAscii = false;
contentModelFlag = ContentModelFlag.PCDATA;
line = linePrev = 0;
col = colPrev = 1;
nextCharOnNewLine = true;
prev = '\u0000';
html4 = false;
alreadyWarnedAboutPrivateUseCharacters = false;
metaBoundaryPassed = false;
tokenHandler.startTokenization(this);
wantsComments = tokenHandler.wantsComments();
switch (contentModelFlag) {
case PCDATA:
stateSave = Tokenizer.DATA;
break;
case CDATA:
stateSave = Tokenizer.CDATA;
break;
case RCDATA:
stateSave = Tokenizer.RCDATA;
break;
case PLAINTEXT:
stateSave = Tokenizer.PLAINTEXT;
}
index = 0;
forceQuirks = false;
additional = '\u0000';
entCol = -1;
lo = 0;
hi = (NamedCharacters.NAMES.length - 1);
candidate = -1;
strBufMark = 0;
prevValue = -1;
value = 0;
seenDigits = false;
shouldSuspend = false;
// [NOCPP[
if (!newAttributesEachTime) {
// ]NOCPP]
attributes = new HtmlAttributes(mappingLangToXmlLang);
// [NOCPP[
}
// ]NOCPP]
}
public boolean tokenizeBuffer(UTF16Buffer buffer) throws SAXException {
buf = buffer.getBuffer();
int state = stateSave;
int returnState = returnStateSave;
char c = '\u0000';
shouldSuspend = false;
int start = buffer.getStart();
/**
* The index of the last <code>char</code> read from <code>buf</code>.
*/
pos = start - 1;
/**
* The index of the first <code>char</code> in <code>buf</code> that
* is part of a coalesced run of character tokens or
* <code>Integer.MAX_VALUE</code> if there is not a current run being
* coalesced.
*/
switch (state) {
case DATA:
case RCDATA:
case CDATA:
case PLAINTEXT:
case CDATA_SECTION:
case ESCAPE:
case ESCAPE_EXCLAMATION:
case ESCAPE_EXCLAMATION_HYPHEN:
case ESCAPE_HYPHEN:
case ESCAPE_HYPHEN_HYPHEN:
cstart = start;
break;
default:
cstart = Integer.MAX_VALUE;
break;
}
/**
* The number of <code>char</code>s in <code>buf</code> that have
* meaning. (The rest of the array is garbage and should not be
* examined.)
*/
end = buffer.getEnd();
boolean reconsume = false;
stateLoop(state, c, reconsume, returnState);
detachStrBuf();
detachLongStrBuf();
if (pos == end) {
// exiting due to end of buffer
buffer.setStart(pos);
} else {
buffer.setStart(pos + 1);
}
if (prev == '\r') {
prev = ' ';
return true;
} else {
return false;
}
}
// WARNING When editing this, makes sure the bytecode length shown by javap
// stays under 8000 bytes!
private void stateLoop(int state, char c, boolean reconsume, int returnState)
throws SAXException {
stateloop: for (;;) {
switch (state) {
case DATA:
dataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) When the content model
* flag is set to one of the PCDATA or RCDATA
* states and the escape flag is false: switch
* to the character reference data state.
* Otherwise: treat it as per the "anything
* else" entry below.
*/
flushChars();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
state = Tokenizer.TAG_OPEN;
break dataloop; // FALL THROUGH continue
// stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case TAG_OPEN:
tagopenloop: for (;;) {
/*
* The behavior of this state depends on the content
* model flag.
*/
/*
* If the content model flag is set to the PCDATA state
* Consume the next input character:
*/
c = read();
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to U+005A
* LATIN CAPITAL LETTER Z Create a new start tag
* token,
*/
endTag = false;
/*
* set its tag name to the lowercase version of the
* input character (add 0x0020 to the character's
* code point),
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
/* then switch to the tag name state. */
state = Tokenizer.TAG_NAME;
/*
* (Don't emit the token yet; further details will
* be filled in before it is emitted.)
*/
break tagopenloop;
// continue stateloop;
} else if (c >= 'a' && c <= 'z') {
/*
* U+0061 LATIN SMALL LETTER A through to U+007A
* LATIN SMALL LETTER Z Create a new start tag
* token,
*/
endTag = false;
/*
* set its tag name to the input character,
*/
clearStrBufAndAppendCurrentC();
/* then switch to the tag name state. */
state = Tokenizer.TAG_NAME;
/*
* (Don't emit the token yet; further details will
* be filled in before it is emitted.)
*/
break tagopenloop;
// continue stateloop;
}
switch (c) {
case '\u0000':
break stateloop;
case '!':
/*
* U+0021 EXCLAMATION MARK (!) Switch to the
* markup declaration open state.
*/
state = Tokenizer.MARKUP_DECLARATION_OPEN;
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the close tag
* open state.
*/
state = Tokenizer.CLOSE_TAG_OPEN_PCDATA;
continue stateloop;
case '?':
/*
* U+003F QUESTION MARK (?) Parse error.
*/
err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)");
/*
* Switch to the bogus comment state.
*/
clearLongStrBufAndAppendToComment('?');
state = Tokenizer.BOGUS_COMMENT;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C<\u201D) or mistyped start tag.");
/*
* Emit a U+003C LESS-THAN SIGN character token
* and a U+003E GREATER-THAN SIGN character
* token.
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 2);
/* Switch to the data state. */
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("Bad character \u201C"
+ c
+ "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C<\u201D.");
/*
* Emit a U+003C LESS-THAN SIGN character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in
* the data state.
*/
cstart = pos;
state = Tokenizer.DATA;
reconsume = true;
continue stateloop;
}
}
// FALL THROUGH DON'T REORDER
case TAG_NAME:
tagnameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
tagName = strBufToElementNameString();
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
break tagnameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
tagName = strBufToElementNameString();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
tagName = strBufToElementNameString();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
default:
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Append the
* lowercase version of the current input
* character (add 0x0020 to the character's
* code point) to the current tag token's
* tag name.
*/
appendStrBufForceWrite((char) (c + 0x20));
} else {
/*
* Anything else Append the current input
* character to the current tag token's tag
* name.
*/
appendStrBuf(c);
}
/*
* Stay in the tag name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_ATTRIBUTE_NAME:
beforeattributenameloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before attribute name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
case '\"':
case '\'':
case '=':
/*
* U+0022 QUOTATION MARK (") U+0027 APOSTROPHE
* (') U+003D EQUALS SIGN (=) Parse error.
*/
if (c == '=') {
err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing.");
} else {
err("Saw \u201C"
+ c
+ "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before.");
}
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
/*
* Anything else Start a new attribute in the
* current tag token.
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Set that
* attribute's name to the lowercase version
* of the current input character (add
* 0x0020 to the character's code point)
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
} else {
/*
* Set that attribute's name to the current
* input character,
*/
clearStrBufAndAppendCurrentC();
}
/*
* and its value to the empty string.
*/
// Will do later.
/*
* Switch to the attribute name state.
*/
state = Tokenizer.ATTRIBUTE_NAME;
break beforeattributenameloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case ATTRIBUTE_NAME:
attributenameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the after attribute name state.
*/
attributeNameComplete();
state = Tokenizer.AFTER_ATTRIBUTE_NAME;
continue stateloop;
case '=':
/*
* U+003D EQUALS SIGN (=) Switch to the before
* attribute value state.
*/
attributeNameComplete();
state = Tokenizer.BEFORE_ATTRIBUTE_VALUE;
break attributenameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
attributeNameComplete();
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
attributeNameComplete();
addAttributeWithoutValue();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
case '\"':
case '\'':
/*
* U+0022 QUOTATION MARK (") U+0027 APOSTROPHE
* (') Parse error.
*/
err("Quote \u201C"
+ c
+ "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier.");
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Append the
* lowercase version of the current input
* character (add 0x0020 to the character's
* code point) to the current attribute's
* name.
*/
appendStrBufForceWrite((char) (c + 0x20));
} else {
/*
* Anything else Append the current input
* character to the current attribute's
* name.
*/
appendStrBuf(c);
}
/*
* Stay in the attribute name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_ATTRIBUTE_VALUE:
beforeattributevalueloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before attribute value state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the
* attribute value (double-quoted) state.
*/
clearLongStrBufForNextState();
state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
break beforeattributevalueloop;
// continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the attribute
* value (unquoted) state and reconsume this
* input character.
*/
clearLongStrBuf();
state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED;
reconsume = true;
continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the attribute
* value (single-quoted) state.
*/
clearLongStrBufForNextState();
state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '=':
/*
* U+003D EQUALS SIGN (=) Parse error.
*/
err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign.");
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
if (html4
&& !((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '.' || c == '-'
|| c == '_' || c == ':')) {
err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)");
}
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
clearLongStrBufAndAppendCurrentC();
/*
* Switch to the attribute value (unquoted)
* state.
*/
state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case ATTRIBUTE_VALUE_DOUBLE_QUOTED:
attributevaluedoublequotedloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* attribute value (quoted) state.
*/
addAttributeWithValue();
state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED;
break attributevaluedoublequotedloop;
// continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with the
* additional allowed character being U+0022
* QUOTATION MARK (").
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\"';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (double-quoted)
* state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_ATTRIBUTE_VALUE_QUOTED:
afterattributevaluequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
state = Tokenizer.SELF_CLOSING_START_TAG;
break afterattributevaluequotedloop;
// continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("No space between attributes.");
/*
* Reconsume the character in the before
* attribute name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case SELF_CLOSING_START_TAG:
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Set the self-closing
* flag of the current tag token. Emit the current
* tag token.
*/
state = emitCurrentTagToken(true);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
default:
/* Anything else Parse error. */
err("A slash was not immediate followed by \u201C>\u201D.");
/*
* Reconsume the character in the before attribute
* name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
reconsume = true;
continue stateloop;
}
// XXX reorder point
case ATTRIBUTE_VALUE_UNQUOTED:
for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
addAttributeWithValue();
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with no +
* additional allowed character.
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '<':
case '\"':
case '\'':
case '=':
if (c == '<') {
warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before.");
} else {
/*
* U+0022 QUOTATION MARK (") U+0027
* APOSTROPHE (') U+003D EQUALS SIGN (=)
* Parse error.
*/
err("\u201C"
+ c
+ "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value.");
/*
* Treat it as per the "anything else" entry
* below.
*/
}
// fall through
default:
if (html4
&& !((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '.' || c == '-'
|| c == '_' || c == ':')) {
err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)");
}
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (unquoted) state.
*/
continue;
}
}
// XXX reorder point
case AFTER_ATTRIBUTE_NAME:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after attribute name state.
*/
continue;
case '=':
/*
* U+003D EQUALS SIGN (=) Switch to the before
* attribute value state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_VALUE;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
addAttributeWithoutValue();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
default:
addAttributeWithoutValue();
/*
* Anything else Start a new attribute in the
* current tag token.
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Set that
* attribute's name to the lowercase version
* of the current input character (add
* 0x0020 to the character's code point)
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
} else {
/*
* Set that attribute's name to the current
* input character,
*/
clearStrBufAndAppendCurrentC();
}
/*
* and its value to the empty string.
*/
// Will do later.
/*
* Switch to the attribute name state.
*/
state = Tokenizer.ATTRIBUTE_NAME;
continue stateloop;
}
}
// XXX reorder point
case BOGUS_COMMENT:
boguscommentloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* (This can only happen if the content model flag is
* set to the PCDATA state.)
*
* Consume every character up to and including the first
* U+003E GREATER-THAN SIGN character (>) or the end of
* the file (EOF), whichever comes first. Emit a comment
* token whose data is the concatenation of all the
* characters starting from and including the character
* that caused the state machine to switch into the
* bogus comment state, up to and including the
* character immediately before the last consumed
* character (i.e. up to the character just before the
* U+003E or EOF character). (If the comment was started
* by the end of the file (EOF), the token is empty.)
*
* Switch to the data state.
*
* If the end of the file was reached, reconsume the EOF
* character.
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
emitComment(0);
state = Tokenizer.DATA;
continue stateloop;
case '-':
appendLongStrBuf(c);
state = Tokenizer.BOGUS_COMMENT_HYPHEN;
break boguscommentloop;
default:
appendLongStrBuf(c);
continue;
}
}
// FALLTHRU DON'T REORDER
case BOGUS_COMMENT_HYPHEN:
boguscommenthyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '>':
maybeAppendSpaceToBogusComment();
emitComment(0);
state = Tokenizer.DATA;
continue stateloop;
case '-':
appendSecondHyphenToBogusComment();
continue boguscommenthyphenloop;
default:
appendLongStrBuf(c);
continue stateloop;
}
}
// XXX reorder point
case MARKUP_DECLARATION_OPEN:
markupdeclarationopenloop: for (;;) {
c = read();
/*
* (This can only happen if the content model flag is
* set to the PCDATA state.)
*
* If the next two characters are both U+002D
* HYPHEN-MINUS (-) characters, consume those two
* characters, create a comment token whose data is the
* empty string, and switch to the comment start state.
*
* Otherwise, if the next seven characters are a
* case-insensitive match for the word "DOCTYPE", then
* consume those characters and switch to the DOCTYPE
* state.
*
* Otherwise, if the insertion mode is "in foreign
* content" and the current node is not an element in
* the HTML namespace and the next seven characters are
* a case-sensitive match for the string "[CDATA[" (the
* five uppercase letters "CDATA" with a U+005B LEFT
* SQUARE BRACKET character before and after), then
* consume those characters and switch to the CDATA
* section state (which is unrelated to the content
* model flag's CDATA state).
*
* Otherwise, is is a parse error. Switch to the bogus
* comment state. The next character that is consumed,
* if any, is the first character that will be in the
* comment.
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
clearLongStrBufAndAppendToComment(c);
state = Tokenizer.MARKUP_DECLARATION_HYPHEN;
break markupdeclarationopenloop;
// continue stateloop;
case 'd':
case 'D':
clearLongStrBufAndAppendToComment(c);
index = 0;
state = Tokenizer.MARKUP_DECLARATION_OCTYPE;
continue stateloop;
case '[':
if (tokenHandler.inForeign()) {
clearLongStrBufAndAppendToComment(c);
index = 0;
state = Tokenizer.CDATA_START;
continue stateloop;
} else {
// fall through
}
default:
err("Bogus comment.");
clearLongStrBuf();
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case MARKUP_DECLARATION_HYPHEN:
markupdeclarationhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
clearLongStrBufForNextState();
state = Tokenizer.COMMENT_START;
break markupdeclarationhyphenloop;
// continue stateloop;
default:
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_START:
commentstartloop: for (;;) {
c = read();
/*
* Comment start state
*
*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* start dash state.
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_START_DASH;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Premature end of comment. Use \u201C-->\u201D to end a comment properly.");
/* Emit the comment token. */
emitComment(0);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the input character to
* the comment token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
break commentstartloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT:
commentloop: for (;;) {
c = read();
/*
* Comment state Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* end dash state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END_DASH;
break commentloop;
// continue stateloop;
default:
/*
* Anything else Append the input character to
* the comment token's data.
*/
appendLongStrBuf(c);
/*
* Stay in the comment state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_END_DASH:
commentenddashloop: for (;;) {
c = read();
/*
* Comment end dash state Consume the next input
* character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* end state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END;
break commentenddashloop;
// continue stateloop;
default:
/*
* Anything else Append a U+002D HYPHEN-MINUS
* (-) character and the input character to the
* comment token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_END:
for (;;) {
c = read();
/*
* Comment end dash state Consume the next input
* character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the comment
* token.
*/
emitComment(2);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
case '-':
/* U+002D HYPHEN-MINUS (-) Parse error. */
err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is.");
/*
* Append a U+002D HYPHEN-MINUS (-) character to
* the comment token's data.
*/
adjustDoubleHyphenAndAppendToLongStrBuf(c);
/*
* Stay in the comment end state.
*/
continue;
default:
/*
* Anything else Parse error.
*/
err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is.");
/*
* Append two U+002D HYPHEN-MINUS (-) characters
* and the input character to the comment
* token's data.
*/
adjustDoubleHyphenAndAppendToLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
}
// XXX reorder point
case COMMENT_START_DASH:
c = read();
/*
* Comment start dash state
*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment end
* state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Premature end of comment. Use \u201C-->\u201D to end a comment properly.");
/* Emit the comment token. */
emitComment(1);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append a U+002D HYPHEN-MINUS (-)
* character and the input character to the comment
* token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
// XXX reorder point
case MARKUP_DECLARATION_OCTYPE:
markupdeclarationdoctypeloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
if (index < 6) { // OCTYPE.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded == Tokenizer.OCTYPE[index]) {
appendLongStrBuf(c);
} else {
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
state = Tokenizer.DOCTYPE;
reconsume = true;
break markupdeclarationdoctypeloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE:
doctypeloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
systemIdentifier = null;
publicIdentifier = null;
doctypeName = null;
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before DOCTYPE name state.
*/
state = Tokenizer.BEFORE_DOCTYPE_NAME;
break doctypeloop;
// continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("Missing space before doctype name.");
/*
* Reconsume the current character in the before
* DOCTYPE name state.
*/
state = Tokenizer.BEFORE_DOCTYPE_NAME;
reconsume = true;
break doctypeloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_NAME:
beforedoctypenameloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Nameless doctype.");
/*
* Create a new DOCTYPE token. Set its
* force-quirks flag to on. Emit the token.
*/
tokenHandler.doctype("", null, null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/* Anything else Create a new DOCTYPE token. */
/*
* Set the token's name name to the current
* input character.
*/
clearStrBufAndAppendCurrentC();
/*
* Switch to the DOCTYPE name state.
*/
state = Tokenizer.DOCTYPE_NAME;
break beforedoctypenameloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_NAME:
doctypenameloop: for (;;) {
c = read();
/*
* First, consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the after DOCTYPE name state.
*/
doctypeName = strBufToString();
state = Tokenizer.AFTER_DOCTYPE_NAME;
break doctypenameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(strBufToString(), null,
null, false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* name.
*/
appendStrBuf(c);
/*
* Stay in the DOCTYPE name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_NAME:
afterdoctypenameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
case 'p':
case 'P':
index = 0;
state = Tokenizer.DOCTYPE_UBLIC;
break afterdoctypenameloop;
// continue stateloop;
case 's':
case 'S':
index = 0;
state = Tokenizer.DOCTYPE_YSTEM;
continue stateloop;
default:
/*
* Otherwise, this is the parse error.
*/
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_UBLIC:
doctypeublicloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* If the next six characters are a case-insensitive
* match for the word "PUBLIC", then consume those
* characters and switch to the before DOCTYPE public
* identifier state.
*/
if (index < 5) { // UBLIC.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != Tokenizer.UBLIC[index]) {
bogusDoctype();
// forceQuirks = true;
state = Tokenizer.BOGUS_DOCTYPE;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;
reconsume = true;
break doctypeublicloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:
beforedoctypepublicidentifierloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE public identifier
* state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's public identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE public identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
break beforedoctypepublicidentifierloop;
// continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* public identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE public identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
continue stateloop;
case '>':
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Expected a public identifier but the doctype ended.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:
doctypepublicidentifierdoublequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* DOCTYPE public identifier state.
*/
publicIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
break doctypepublicidentifierdoublequotedloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in public identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
longStrBufToString(), null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* public identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE public identifier
* (double-quoted) state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_PUBLIC_IDENTIFIER:
afterdoctypepublicidentifierloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE public identifier state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's system identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
break afterdoctypepublicidentifierloop;
// continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* system identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, null, false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:
doctypesystemidentifierdoublequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* DOCTYPE system identifier state.
*/
systemIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in system identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, longStrBufToString(),
true);
/*
* Switch to the data state.
*
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* system identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE system identifier
* (double-quoted) state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_SYSTEM_IDENTIFIER:
afterdoctypesystemidentifierloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE system identifier state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, systemIdentifier,
false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Switch to the bogus DOCTYPE state. (This does
* not set the DOCTYPE token's force-quirks flag
* to on.)
*/
bogusDoctypeWithoutQuirks();
state = Tokenizer.BOGUS_DOCTYPE;
break afterdoctypesystemidentifierloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BOGUS_DOCTYPE:
for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit that
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, systemIdentifier,
forceQuirks);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Stay in the bogus DOCTYPE
* state.
*/
continue;
}
}
// XXX reorder point
case DOCTYPE_YSTEM:
doctypeystemloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Otherwise, if the next six characters are a
* case-insensitive match for the word "SYSTEM", then
* consume those characters and switch to the before
* DOCTYPE system identifier state.
*/
if (index < 5) { // YSTEM.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != Tokenizer.YSTEM[index]) {
bogusDoctype();
state = Tokenizer.BOGUS_DOCTYPE;
reconsume = true;
continue stateloop;
}
index++;
continue stateloop;
} else {
state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;
reconsume = true;
break doctypeystemloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:
beforedoctypesystemidentifierloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE system identifier
* state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's system identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* system identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
break beforedoctypesystemidentifierloop;
// continue stateloop;
case '>':
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Expected a system identifier but the doctype ended.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* DOCTYPE system identifier state.
*/
systemIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in system identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, longStrBufToString(),
true);
/*
* Switch to the data state.
*
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* system identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE system identifier
* (double-quoted) state.
*/
continue;
}
}
// XXX reorder point
case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* DOCTYPE public identifier state.
*/
publicIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in public identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
longStrBufToString(), null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* public identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE public identifier
* (single-quoted) state.
*/
continue;
}
}
// XXX reorder point
case CDATA_START:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
if (index < 6) { // CDATA_LSQB.length
if (c == Tokenizer.CDATA_LSQB[index]) {
appendLongStrBuf(c);
} else {
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
cstart = pos; // start coalescing
state = Tokenizer.CDATA_SECTION;
reconsume = true;
break; // FALL THROUGH continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_SECTION:
cdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case ']':
flushChars();
state = Tokenizer.CDATA_RSQB;
break cdataloop; // FALL THROUGH
default:
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_RSQB:
cdatarsqb: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case ']':
state = Tokenizer.CDATA_RSQB_RSQB;
break cdatarsqb;
default:
tokenHandler.characters(Tokenizer.RSQB_RSQB, 0,
1);
cstart = pos;
state = Tokenizer.CDATA_SECTION;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_RSQB_RSQB:
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '>':
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2);
cstart = pos;
state = Tokenizer.CDATA_SECTION;
reconsume = true;
continue stateloop;
}
// XXX reorder point
case ATTRIBUTE_VALUE_SINGLE_QUOTED:
attributevaluesinglequotedloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* attribute value (quoted) state.
*/
addAttributeWithValue();
state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED;
continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with the +
* additional allowed character being U+0027
* APOSTROPHE (').
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\'';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
break attributevaluesinglequotedloop;
// continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (double-quoted)
* state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case CONSUME_CHARACTER_REFERENCE:
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Unlike the definition is the spec, this state does not
* return a value and never requires the caller to
* backtrack. This state takes care of emitting characters
* or appending to the current attribute value. It also
* takes care of that in the case when consuming the
* character reference fails.
*/
/*
* This section defines how to consume a character
* reference. This definition is used when parsing character
* references in text and in attributes.
*
* The behavior depends on the identity of the next
* character (the one immediately after the U+0026 AMPERSAND
* character):
*/
switch (c) {
case ' ':
case '\t':
case '\n':
case '\u000C':
case '<':
case '&':
emitOrAppendStrBuf(returnState);
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
case '#':
/*
* U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER
* SIGN.
*/
appendStrBuf('#');
state = Tokenizer.CONSUME_NCR;
continue stateloop;
default:
if (c == additional) {
emitOrAppendStrBuf(returnState);
state = returnState;
reconsume = true;
continue stateloop;
}
entCol = -1;
lo = 0;
hi = (NamedCharacters.NAMES.length - 1);
candidate = -1;
strBufMark = 0;
state = Tokenizer.CHARACTER_REFERENCE_LOOP;
reconsume = true;
// FALL THROUGH continue stateloop;
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CHARACTER_REFERENCE_LOOP:
outer: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
if (c == '\u0000') {
break stateloop;
}
entCol++;
/*
* Anything else Consume the maximum number of
* characters possible, with the consumed characters
* case-sensitively matching one of the identifiers in
* the first column of the named character references
* table.
*/
hiloop: for (;;) {
if (hi == -1) {
break hiloop;
}
if (entCol == NamedCharacters.NAMES[hi].length) {
break hiloop;
}
if (entCol > NamedCharacters.NAMES[hi].length) {
break outer;
} else if (c < NamedCharacters.NAMES[hi][entCol]) {
hi--;
} else {
break hiloop;
}
}
loloop: for (;;) {
if (hi < lo) {
break outer;
}
if (entCol == NamedCharacters.NAMES[lo].length) {
candidate = lo;
strBufMark = strBufLen;
lo++;
} else if (entCol > NamedCharacters.NAMES[lo].length) {
break outer;
} else if (c > NamedCharacters.NAMES[lo][entCol]) {
lo++;
} else {
break loloop;
}
}
if (hi < lo) {
break outer;
}
appendStrBuf(c);
continue;
}
// TODO warn about apos (IE) and TRADE (Opera)
if (candidate == -1) {
/*
* If no match can be made, then this is a parse error.
*/
err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
char[] candidateArr = NamedCharacters.NAMES[candidate];
if (candidateArr[candidateArr.length - 1] != ';') {
/*
* If the last character matched is not a U+003B
* SEMICOLON (;), there is a parse error.
*/
err("Entity reference was not terminated by a semicolon.");
if ((returnState & (~1)) != 0) {
/*
* If the entity is being consumed as part of an
* attribute, and the last character matched is
* not a U+003B SEMICOLON (;),
*/
char ch;
if (strBufMark == strBufLen) {
ch = c;
} else {
// if (strBufOffset != -1) {
// ch = buf[strBufOffset + strBufMark];
// } else {
ch = strBuf[strBufMark];
// }
}
if ((ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')) {
/*
* and the next character is in the range
* U+0030 DIGIT ZERO to U+0039 DIGIT NINE,
* U+0041 LATIN CAPITAL LETTER A to U+005A
* LATIN CAPITAL LETTER Z, or U+0061 LATIN
* SMALL LETTER A to U+007A LATIN SMALL
* LETTER Z, then, for historical reasons,
* all the characters that were matched
* after the U+0026 AMPERSAND (&) must be
* unconsumed, and nothing is returned.
*/
appendStrBufToLongStrBuf();
state = returnState;
reconsume = true;
continue stateloop;
}
}
}
/*
* Otherwise, return a character token for the character
* corresponding to the entity name (as given by the
* second column of the named character references
* table).
*/
char[] val = NamedCharacters.VALUES[candidate];
emitOrAppend(val, returnState);
// this is so complicated!
if (strBufMark < strBufLen) {
if (strBufOffset != -1) {
if ((returnState & (~1)) != 0) {
for (int i = strBufMark; i < strBufLen; i++) {
appendLongStrBuf(buf[strBufOffset + i]);
}
} else {
tokenHandler.characters(buf, strBufOffset
+ strBufMark, strBufLen
- strBufMark);
}
} else {
if ((returnState & (~1)) != 0) {
for (int i = strBufMark; i < strBufLen; i++) {
appendLongStrBuf(strBuf[i]);
}
} else {
tokenHandler.characters(strBuf, strBufMark,
strBufLen - strBufMark);
}
}
}
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
/*
* If the markup contains I'm ¬it; I tell you, the
* entity is parsed as "not", as in, I'm ¬it; I tell
* you. But if the markup was I'm ∉ I tell you,
* the entity would be parsed as "notin;", resulting in
* I'm ∉ I tell you.
*/
}
// XXX reorder point
case CONSUME_NCR:
c = read();
prevValue = -1;
value = 0;
seenDigits = false;
/*
* The behavior further depends on the character after the
* U+0023 NUMBER SIGN:
*/
switch (c) {
case '\u0000':
break stateloop;
case 'x':
case 'X':
/*
* U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL
* LETTER X Consume the X.
*
* Follow the steps below, but using the range of
* characters U+0030 DIGIT ZERO through to U+0039
* DIGIT NINE, U+0061 LATIN SMALL LETTER A through
* to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN
* CAPITAL LETTER A, through to U+0046 LATIN CAPITAL
* LETTER F (in other words, 0-9, A-F, a-f).
*
* When it comes to interpreting the number,
* interpret it as a hexadecimal number.
*/
appendStrBuf(c);
state = Tokenizer.HEX_NCR_LOOP;
continue stateloop;
default:
/*
* Anything else Follow the steps below, but using
* the range of characters U+0030 DIGIT ZERO through
* to U+0039 DIGIT NINE (i.e. just 0-9).
*
* When it comes to interpreting the number,
* interpret it as a decimal number.
*/
state = Tokenizer.DECIMAL_NRC_LOOP;
reconsume = true;
// FALL THROUGH continue stateloop;
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case DECIMAL_NRC_LOOP:
decimalloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
if (c == '\u0000') {
break stateloop;
}
// Deal with overflow gracefully
if (value < prevValue) {
value = 0x110000; // Value above Unicode range but
// within int
// range
}
prevValue = value;
/*
* Consume as many characters as match the range of
* characters given above.
*/
if (c >= '0' && c <= '9') {
seenDigits = true;
value *= 10;
value += c - '0';
continue;
} else if (c == ';') {
if (seenDigits) {
state = Tokenizer.HANDLE_NCR_VALUE;
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
// FALL THROUGH continue stateloop;
break decimalloop;
} else {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
appendStrBuf(';');
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
state = returnState;
continue stateloop;
}
} else {
/*
* If no characters match the range, then don't
* consume any characters (and unconsume the U+0023
* NUMBER SIGN character and, if appropriate, the X
* character). This is a parse error; nothing is
* returned.
*
* Otherwise, if the next character is a U+003B
* SEMICOLON, consume that too. If it isn't, there
* is a parse error.
*/
if (!seenDigits) {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
err("Character reference was not terminated by a semicolon.");
state = Tokenizer.HANDLE_NCR_VALUE;
reconsume = true;
if ((returnState & (~1)) == 0) {
cstart = pos;
}
// FALL THROUGH continue stateloop;
break decimalloop;
}
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case HANDLE_NCR_VALUE:
// WARNING previous state sets reconsume
// XXX inline this case if the method size can take it
handleNcrValue(returnState);
state = returnState;
continue stateloop;
// XXX reorder point
case HEX_NCR_LOOP:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
// Deal with overflow gracefully
if (value < prevValue) {
value = 0x110000; // Value above Unicode range but
// within int
// range
}
prevValue = value;
/*
* Consume as many characters as match the range of
* characters given above.
*/
if (c >= '0' && c <= '9') {
seenDigits = true;
value *= 16;
value += c - '0';
continue;
} else if (c >= 'A' && c <= 'F') {
seenDigits = true;
value *= 16;
value += c - 'A' + 10;
continue;
} else if (c >= 'a' && c <= 'f') {
seenDigits = true;
value *= 16;
value += c - 'a' + 10;
continue;
} else if (c == ';') {
if (seenDigits) {
state = Tokenizer.HANDLE_NCR_VALUE;
cstart = pos + 1;
continue stateloop;
} else {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
appendStrBuf(';');
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
state = returnState;
continue stateloop;
}
} else {
/*
* If no characters match the range, then don't
* consume any characters (and unconsume the U+0023
* NUMBER SIGN character and, if appropriate, the X
* character). This is a parse error; nothing is
* returned.
*
* Otherwise, if the next character is a U+003B
* SEMICOLON, consume that too. If it isn't, there
* is a parse error.
*/
if (!seenDigits) {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
err("Character reference was not terminated by a semicolon.");
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = Tokenizer.HANDLE_NCR_VALUE;
reconsume = true;
continue stateloop;
}
}
}
// XXX reorder point
case PLAINTEXT:
plaintextloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// XXX reorder point
case CDATA:
cdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
returnState = state;
state = Tokenizer.TAG_OPEN_NON_PCDATA;
break cdataloop; // FALL THRU continue
// stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case TAG_OPEN_NON_PCDATA:
tagopennonpcdataloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '!':
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
cstart = pos;
state = Tokenizer.ESCAPE_EXCLAMATION;
break tagopennonpcdataloop; // FALL THRU
// continue
// stateloop;
case '/':
/*
* If the content model flag is set to the
* RCDATA or CDATA states Consume the next input
* character.
*/
if (contentModelElement != null) {
/*
* If it is a U+002F SOLIDUS (/) character,
* switch to the close tag open state.
*/
index = 0;
clearStrBufForNextState();
state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA;
continue stateloop;
} // else fall through
default:
/*
* Otherwise, emit a U+003C LESS-THAN SIGN
* character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in
* the data state.
*/
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_EXCLAMATION:
escapeexclamationloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN;
break escapeexclamationloop; // FALL THRU
// continue
// stateloop;
default:
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_EXCLAMATION_HYPHEN:
escapeexclamationhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN_HYPHEN;
break escapeexclamationhyphenloop;
// continue stateloop;
default:
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_HYPHEN_HYPHEN:
escapehyphenhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
continue;
case '>':
state = returnState;
continue stateloop;
default:
state = Tokenizer.ESCAPE;
break escapehyphenhyphenloop;
// continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE:
escapeloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN;
break escapeloop; // FALL THRU continue
// stateloop;
default:
continue escapeloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_HYPHEN:
escapehyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN_HYPHEN;
continue stateloop;
default:
state = Tokenizer.ESCAPE;
continue stateloop;
}
}
// XXX reorder point
case CLOSE_TAG_OPEN_NOT_PCDATA:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
// ASSERT! when entering this state, set index to 0 and
// call clearStrBuf()
assert (contentModelElement != null);
/*
* If the content model flag is set to the RCDATA or
* CDATA states but no start tag token has ever been
* emitted by this instance of the tokenizer (fragment
* case), or, if the content model flag is set to the
* RCDATA or CDATA states and the next few characters do
* not match the tag name of the last start tag token
* emitted (case insensitively), or if they do but they
* are not immediately followed by one of the following
* characters: + U+0009 CHARACTER TABULATION + U+000A
* LINE FEED (LF) + + U+000C FORM FEED (FF) + U+0020
* SPACE + U+003E GREATER-THAN SIGN (>) + U+002F SOLIDUS
* (/) + EOF
*
* ...then emit a U+003C LESS-THAN SIGN character token,
* a U+002F SOLIDUS character token, and switch to the
* data state to process the next input character.
*/
// Let's implement the above without lookahead. strBuf
// holds
// characters that need to be emitted if looking for an
// end tag
// fails.
// Duplicating the relevant part of tag name state here
// as well.
if (index < contentModelElement.name.length()) {
char e = contentModelElement.name.charAt(index);
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != e) {
if (index > 0
|| (folded >= 'a' && folded <= 'z')) {
// [NOCPP[
if (html4) {
if (ElementName.IFRAME != contentModelElement) {
err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)");
}
} else {
// ]NOCPP]
warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but this did not close the element.");
// [NOCPP[
}
// ]NOCPP]
}
tokenHandler.characters(Tokenizer.LT_SOLIDUS,
0, 2);
emitStrBuf();
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
}
appendStrBuf(c);
index++;
continue;
} else {
endTag = true;
// XXX replace contentModelElement with different
// type
tagName = contentModelElement;
switch (c) {
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE
* FEED (LF) U+000C FORM FEED (FF) U+0020
* SPACE Switch to the before attribute name
* state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the
* current tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Parse error unless
* this is a permitted slash.
*/
// never permitted here
err("Stray \u201C/\u201D in end tag.");
/*
* Switch to the before attribute name
* state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
default:
if (html4) {
err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)");
} else {
warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but this did not close the element.");
}
tokenHandler.characters(
Tokenizer.LT_SOLIDUS, 0, 2);
emitStrBuf();
cstart = pos; // don't drop the character
- state = Tokenizer.DATA;
+ state = returnState;
continue stateloop;
}
}
}
// XXX reorder point
case CLOSE_TAG_OPEN_PCDATA:
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Otherwise, if the content model flag is set to the PCDATA
* state, or if the next few characters do match that tag
* name, consume the next input character:
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN
* CAPITAL LETTER Z Create a new end tag token,
*/
endTag = true;
/*
* set its tag name to the lowercase version of the
* input character (add 0x0020 to the character's code
* point),
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
/*
* then switch to the tag name state. (Don't emit the
* token yet; further details will be filled in before
* it is emitted.)
*/
state = Tokenizer.TAG_NAME;
continue stateloop;
} else if (c >= 'a' && c <= 'z') {
/*
* U+0061 LATIN SMALL LETTER A through to U+007A LATIN
* SMALL LETTER Z Create a new end tag token,
*/
endTag = true;
/*
* set its tag name to the input character,
*/
clearStrBufAndAppendCurrentC();
/*
* then switch to the tag name state. (Don't emit the
* token yet; further details will be filled in before
* it is emitted.)
*/
state = Tokenizer.TAG_NAME;
continue stateloop;
} else if (c == '>') {
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C<\u201D) or mistyped end tag.");
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
} else {
/* Anything else Parse error. */
err("Garbage after \u201C</\u201D.");
/*
* Switch to the bogus comment state.
*/
clearLongStrBufAndAppendToComment(c);
state = Tokenizer.BOGUS_COMMENT;
continue stateloop;
}
// XXX reorder point
case RCDATA:
rcdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) When the content model
* flag is set to one of the PCDATA or RCDATA
* states and the escape flag is false: switch
* to the character reference data state.
* Otherwise: treat it as per the "anything
* else" entry below.
*/
flushChars();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
returnState = state;
state = Tokenizer.TAG_OPEN_NON_PCDATA;
continue stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
}
}
flushChars();
if (prev == '\r' && pos != end) {
pos--;
col--;
}
// Save locals
stateSave = state;
returnStateSave = returnState;
}
private void bogusDoctype() throws SAXException {
err("Bogus doctype.");
forceQuirks = true;
}
private void bogusDoctypeWithoutQuirks() throws SAXException {
err("Bogus doctype.");
forceQuirks = false;
}
private void emitOrAppendStrBuf(int returnState) throws SAXException {
if ((returnState & (~1)) != 0) {
appendStrBufToLongStrBuf();
} else {
emitStrBuf();
}
}
private void handleNcrValue(int returnState) throws SAXException {
/*
* If one or more characters match the range, then take them all and
* interpret the string of characters as a number (either hexadecimal or
* decimal as appropriate).
*/
if (value >= 0x80 && value <= 0x9f) {
/*
* If that number is one of the numbers in the first column of the
* following table, then this is a parse error.
*/
err("A numeric character reference expanded to the C1 controls range.");
/*
* Find the row with that number in the first column, and return a
* character token for the Unicode character given in the second
* column of that row.
*/
char[] val = NamedCharacters.WINDOWS_1252[value - 0x80];
emitOrAppend(val, returnState);
} else if (value == 0x0D) {
err("A numeric character reference expanded to carriage return.");
emitOrAppend(Tokenizer.LF, returnState);
} else if (value == 0xC
&& contentSpacePolicy != XmlViolationPolicy.ALLOW) {
if (contentSpacePolicy == XmlViolationPolicy.ALTER_INFOSET) {
emitOrAppend(Tokenizer.SPACE, returnState);
} else if (contentSpacePolicy == XmlViolationPolicy.FATAL) {
fatal("A character reference expanded to a form feed which is not legal XML 1.0 white space.");
}
} else if (value == 0xB
&& contentNonXmlCharPolicy != XmlViolationPolicy.ALLOW) {
if (contentSpacePolicy == XmlViolationPolicy.ALTER_INFOSET) {
emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState);
} else if (contentSpacePolicy == XmlViolationPolicy.FATAL) {
fatal("A character reference expanded to a vtab which is not a legal XML 1.0 character.");
}
} else if ((value >= 0x0000 && value <= 0x0008)
|| (value >= 0x000E && value <= 0x001F) || value == 0x007F) {
/*
* Otherwise, if the number is in the range 0x0000 to 0x0008, 0x000E
* to 0x001F, 0x007F to 0x009F, 0xD800 to 0xDFFF , 0xFDD0 to 0xFDDF,
* or is one of 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF,
* 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE,
* 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF,
* 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE,
* 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, or
* 0x10FFFF, or is higher than 0x10FFFF, then this is a parse error;
* return a character token for the U+FFFD REPLACEMENT CHARACTER
* character instead.
*/
err("Character reference expands to a control character ("
+ toUPlusString((char) value) + ").");
emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState);
} else if ((value & 0xF800) == 0xD800) {
err("Character reference expands to a surrogate.");
emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState);
} else if (isNonCharacter(value)) {
err("Character reference expands to a non-character.");
emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState);
} else if (value <= 0xFFFF) {
/*
* Otherwise, return a character token for the Unicode character
* whose code point is that number.
*/
char ch = (char) value;
if (errorHandler != null && isPrivateUse(ch)) {
warnAboutPrivateUseChar();
}
bmpChar[0] = ch;
emitOrAppend(bmpChar, returnState);
} else if (value <= 0x10FFFF) {
if (errorHandler != null && isAstralPrivateUse(value)) {
warnAboutPrivateUseChar();
}
astralChar[0] = (char) (Tokenizer.LEAD_OFFSET + (value >> 10));
astralChar[1] = (char) (0xDC00 + (value & 0x3FF));
emitOrAppend(astralChar, returnState);
} else {
err("Character reference outside the permissible Unicode range.");
emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState);
}
}
public void eof() throws SAXException {
int state = stateSave;
int returnState = returnStateSave;
eofloop: for (;;) {
switch (state) {
case TAG_OPEN_NON_PCDATA:
/*
* Otherwise, emit a U+003C LESS-THAN SIGN character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in the data
* state.
*/
break eofloop;
case TAG_OPEN:
/*
* The behavior of this state depends on the content model
* flag.
*/
/*
* Anything else Parse error.
*/
err("End of file in the tag open state.");
/*
* Emit a U+003C LESS-THAN SIGN character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in the data
* state.
*/
break eofloop;
case CLOSE_TAG_OPEN_NOT_PCDATA:
break eofloop;
case CLOSE_TAG_OPEN_PCDATA:
/* EOF Parse error. */
err("Saw \u201C</\u201D immediately before end of file.");
/*
* Emit a U+003C LESS-THAN SIGN character token and a U+002F
* SOLIDUS character token.
*/
tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case TAG_NAME:
/*
* EOF Parse error.
*/
err("End of file seen when looking for tag name");
/*
* Emit the current tag token.
*/
tagName = strBufToElementNameString();
emitCurrentTagToken(false);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case BEFORE_ATTRIBUTE_NAME:
case AFTER_ATTRIBUTE_VALUE_QUOTED:
case SELF_CLOSING_START_TAG:
/* EOF Parse error. */
err("Saw end of file without the previous tag ending with \u201C>\u201D.");
/*
* Emit the current tag token.
*/
emitCurrentTagToken(false);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case ATTRIBUTE_NAME:
/*
* EOF Parse error.
*/
err("End of file occurred in an attribute name.");
/*
* Emit the current tag token.
*/
attributeNameComplete();
addAttributeWithoutValue();
emitCurrentTagToken(false);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case AFTER_ATTRIBUTE_NAME:
case BEFORE_ATTRIBUTE_VALUE:
/* EOF Parse error. */
err("Saw end of file without the previous tag ending with \u201C>\u201D.");
/*
* Emit the current tag token.
*/
addAttributeWithoutValue();
emitCurrentTagToken(false);
/*
* Reconsume the character in the data state.
*/
break eofloop;
case ATTRIBUTE_VALUE_DOUBLE_QUOTED:
case ATTRIBUTE_VALUE_SINGLE_QUOTED:
case ATTRIBUTE_VALUE_UNQUOTED:
/* EOF Parse error. */
err("End of file reached when inside an attribute value.");
/* Emit the current tag token. */
addAttributeWithValue();
emitCurrentTagToken(false);
/*
* Reconsume the character in the data state.
*/
break eofloop;
case BOGUS_COMMENT:
emitComment(0);
break eofloop;
case BOGUS_COMMENT_HYPHEN:
maybeAppendSpaceToBogusComment();
emitComment(0);
break eofloop;
case MARKUP_DECLARATION_OPEN:
err("Bogus comment.");
clearLongStrBuf();
emitComment(0);
break eofloop;
case MARKUP_DECLARATION_HYPHEN:
err("Bogus comment.");
emitComment(0);
break eofloop;
case MARKUP_DECLARATION_OCTYPE:
err("Bogus comment.");
emitComment(0);
break eofloop;
case COMMENT_START:
case COMMENT:
/*
* EOF Parse error.
*/
err("End of file inside comment.");
/* Emit the comment token. */
emitComment(0);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case COMMENT_END:
/*
* EOF Parse error.
*/
err("End of file inside comment.");
/* Emit the comment token. */
emitComment(2);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case COMMENT_END_DASH:
case COMMENT_START_DASH:
/*
* EOF Parse error.
*/
err("End of file inside comment.");
/* Emit the comment token. */
emitComment(1);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case DOCTYPE:
case BEFORE_DOCTYPE_NAME:
/* EOF Parse error. */
err("End of file inside doctype.");
/*
* Create a new DOCTYPE token. Set its force-quirks flag to
* on. Emit the token.
*/
tokenHandler.doctype("", null, null, true);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case DOCTYPE_NAME:
/* EOF Parse error. */
err("End of file inside doctype.");
/*
* Set the DOCTYPE token's force-quirks flag to on. Emit
* that DOCTYPE token.
*/
tokenHandler.doctype(strBufToString(), null, null, true);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case DOCTYPE_UBLIC:
case DOCTYPE_YSTEM:
case AFTER_DOCTYPE_NAME:
case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:
/* EOF Parse error. */
err("End of file inside doctype.");
/*
* Set the DOCTYPE token's force-quirks flag to on. Emit
* that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null, true);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:
case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:
/* EOF Parse error. */
err("End of file inside public identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to on. Emit
* that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, longStrBufToString(),
null, true);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case AFTER_DOCTYPE_PUBLIC_IDENTIFIER:
case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:
/* EOF Parse error. */
err("End of file inside doctype.");
/*
* Set the DOCTYPE token's force-quirks flag to on. Emit
* that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, publicIdentifier, null,
true);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:
case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:
/* EOF Parse error. */
err("End of file inside system identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to on. Emit
* that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, publicIdentifier,
longStrBufToString(), true);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case AFTER_DOCTYPE_SYSTEM_IDENTIFIER:
/* EOF Parse error. */
err("End of file inside doctype.");
/*
* Set the DOCTYPE token's force-quirks flag to on. Emit
* that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, publicIdentifier,
systemIdentifier, true);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case BOGUS_DOCTYPE:
/*
* Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, publicIdentifier,
systemIdentifier, forceQuirks);
/*
* Reconsume the EOF character in the data state.
*/
break eofloop;
case CONSUME_CHARACTER_REFERENCE:
/*
* Unlike the definition is the spec, this state does not
* return a value and never requires the caller to
* backtrack. This state takes care of emitting characters
* or appending to the current attribute value. It also
* takes care of that in the case when consuming the entity
* fails.
*/
/*
* This section defines how to consume an entity. This
* definition is used when parsing entities in text and in
* attributes.
*
* The behavior depends on the identity of the next
* character (the one immediately after the U+0026 AMPERSAND
* character):
*/
emitOrAppendStrBuf(returnState);
state = returnState;
continue;
case CHARACTER_REFERENCE_LOOP:
outer: for (;;) {
char c = '\u0000';
entCol++;
/*
* Anything else Consume the maximum number of
* characters possible, with the consumed characters
* case-sensitively matching one of the identifiers in
* the first column of the named character references
* table.
*/
hiloop: for (;;) {
if (hi == -1) {
break hiloop;
}
if (entCol == NamedCharacters.NAMES[hi].length) {
break hiloop;
}
if (entCol > NamedCharacters.NAMES[hi].length) {
break outer;
} else if (c < NamedCharacters.NAMES[hi][entCol]) {
hi--;
} else {
break hiloop;
}
}
loloop: for (;;) {
if (hi < lo) {
break outer;
}
if (entCol == NamedCharacters.NAMES[lo].length) {
candidate = lo;
strBufMark = strBufLen;
lo++;
} else if (entCol > NamedCharacters.NAMES[lo].length) {
break outer;
} else if (c > NamedCharacters.NAMES[lo][entCol]) {
lo++;
} else {
break loloop;
}
}
if (hi < lo) {
break outer;
}
continue;
}
// TODO warn about apos (IE) and TRADE (Opera)
if (candidate == -1) {
/*
* If no match can be made, then this is a parse error.
*/
err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&\201D.");
emitOrAppendStrBuf(returnState);
state = returnState;
continue eofloop;
} else {
char[] candidateArr = NamedCharacters.NAMES[candidate];
if (candidateArr[candidateArr.length - 1] != ';') {
/*
* If the last character matched is not a U+003B
* SEMICOLON (;), there is a parse error.
*/
err("Entity reference was not terminated by a semicolon.");
if ((returnState & (~1)) != 0) {
/*
* If the entity is being consumed as part of an
* attribute, and the last character matched is
* not a U+003B SEMICOLON (;),
*/
char ch;
if (strBufMark == strBufLen) {
ch = '\u0000';
} else {
ch = strBuf[strBufMark];
}
if ((ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')) {
/*
* and the next character is in the range
* U+0030 DIGIT ZERO to U+0039 DIGIT NINE,
* U+0041 LATIN CAPITAL LETTER A to U+005A
* LATIN CAPITAL LETTER Z, or U+0061 LATIN
* SMALL LETTER A to U+007A LATIN SMALL
* LETTER Z, then, for historical reasons,
* all the characters that were matched
* after the U+0026 AMPERSAND (&) must be
* unconsumed, and nothing is returned.
*/
appendStrBufToLongStrBuf();
state = returnState;
continue eofloop;
}
}
}
/*
* Otherwise, return a character token for the character
* corresponding to the entity name (as given by the
* second column of the named character references
* table).
*/
char[] val = NamedCharacters.VALUES[candidate];
emitOrAppend(val, returnState);
// this is so complicated!
if (strBufMark < strBufLen) {
if ((returnState & (~1)) != 0) {
for (int i = strBufMark; i < strBufLen; i++) {
appendLongStrBuf(strBuf[i]);
}
} else {
tokenHandler.characters(strBuf, strBufMark,
strBufLen - strBufMark);
}
}
state = returnState;
continue eofloop;
/*
* If the markup contains I'm ¬it; I tell you, the
* entity is parsed as "not", as in, I'm ¬it; I tell
* you. But if the markup was I'm ∉ I tell you,
* the entity would be parsed as "notin;", resulting in
* I'm ∉ I tell you.
*/
}
case CONSUME_NCR:
case DECIMAL_NRC_LOOP:
case HEX_NCR_LOOP:
/*
* If no characters match the range, then don't consume any
* characters (and unconsume the U+0023 NUMBER SIGN
* character and, if appropriate, the X character). This is
* a parse error; nothing is returned.
*
* Otherwise, if the next character is a U+003B SEMICOLON,
* consume that too. If it isn't, there is a parse error.
*/
if (!seenDigits) {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
emitOrAppendStrBuf(returnState);
state = returnState;
continue;
} else {
err("Character reference was not terminated by a semicolon.");
// FALL THROUGH continue stateloop;
}
// WARNING previous state sets reconsume
handleNcrValue(returnState);
state = returnState;
continue;
case DATA:
default:
break eofloop;
}
}
// case DATA:
/*
* EOF Emit an end-of-file token.
*/
tokenHandler.eof();
return;
}
private char read() throws SAXException {
char c;
pos++;
if (pos == end) {
return '\u0000';
}
linePrev = line;
colPrev = col;
if (nextCharOnNewLine) {
line++;
col = 1;
nextCharOnNewLine = false;
} else {
col++;
}
c = buf[pos];
// [NOCPP[
if (errorHandler == null
&& contentNonXmlCharPolicy == XmlViolationPolicy.ALLOW) {
// ]NOCPP]
switch (c) {
case '\r':
nextCharOnNewLine = true;
buf[pos] = '\n';
prev = '\r';
return '\n';
case '\n':
if (prev == '\r') {
return '\u0000';
}
nextCharOnNewLine = true;
break;
case '\u0000':
/*
* All U+0000 NULL characters in the input must be replaced
* by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such
* characters is a parse error.
*/
c = buf[pos] = '\uFFFD';
break;
}
// [NOCPP[
} else {
if (confidence == Confidence.TENTATIVE
&& !alreadyComplainedAboutNonAscii && c > '\u007F') {
complainAboutNonAscii();
alreadyComplainedAboutNonAscii = true;
}
switch (c) {
case '\r':
nextCharOnNewLine = true;
buf[pos] = '\n';
prev = '\r';
return '\n';
case '\n':
if (prev == '\r') {
return '\u0000';
}
nextCharOnNewLine = true;
break;
case '\u0000':
/*
* All U+0000 NULL characters in the input must be replaced
* by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such
* characters is a parse error.
*/
err("Found U+0000 in the character stream.");
c = buf[pos] = '\uFFFD';
break;
case '\u000C':
if (contentNonXmlCharPolicy == XmlViolationPolicy.FATAL) {
fatal("This document is not mappable to XML 1.0 without data loss due to "
+ toUPlusString(c)
+ " which is not a legal XML 1.0 character.");
} else {
if (contentNonXmlCharPolicy == XmlViolationPolicy.ALTER_INFOSET) {
c = buf[pos] = ' ';
}
warn("This document is not mappable to XML 1.0 without data loss due to "
+ toUPlusString(c)
+ " which is not a legal XML 1.0 character.");
}
break;
default:
if ((c & 0xFC00) == 0xDC00) {
// Got a low surrogate. See if prev was high
// surrogate
if ((prev & 0xFC00) == 0xD800) {
int intVal = (prev << 10) + c
+ Tokenizer.SURROGATE_OFFSET;
if (isNonCharacter(intVal)) {
err("Astral non-character.");
}
if (isAstralPrivateUse(intVal)) {
warnAboutPrivateUseChar();
}
} else {
// XXX figure out what to do about lone high
// surrogates
err("Found low surrogate without high surrogate.");
// c = buf[pos] = '\uFFFD';
}
} else if ((c < ' ' || isNonCharacter(c)) && (c != '\t')) {
switch (contentNonXmlCharPolicy) {
case FATAL:
fatal("Forbidden code point "
+ toUPlusString(c) + ".");
break;
case ALTER_INFOSET:
c = buf[pos] = '\uFFFD';
// fall through
case ALLOW:
err("Forbidden code point " + toUPlusString(c)
+ ".");
}
} else if ((c >= '\u007F') && (c <= '\u009F')
|| (c >= '\uFDD0') && (c <= '\uFDDF')) {
err("Forbidden code point " + toUPlusString(c) + ".");
} else if (isPrivateUse(c)) {
warnAboutPrivateUseChar();
}
}
}
// ]NOCPP]
prev = c;
return c;
}
private void complainAboutNonAscii() throws SAXException {
String encoding = "";
if (true) {
err("The character encoding of the document was not explicit but the document contains non-ASCII.");
} else {
err("No explicit character encoding declaration has been seen yet (assumed \u201C"
+ encoding + "\u201D) but the document contains non-ASCII.");
}
}
public void internalEncodingDeclaration(String internalCharset)
throws SAXException {
if (encodingDeclarationHandler != null) {
encodingDeclarationHandler.internalEncodingDeclaration(internalCharset);
}
}
/**
* @param val
* @throws SAXException
*/
private void emitOrAppend(char[] val, int returnState) throws SAXException {
if ((returnState & (~1)) != 0) {
appendLongStrBuf(val);
} else {
tokenHandler.characters(val, 0, val.length);
}
}
public void end() throws SAXException {
strBuf = null;
longStrBuf = null;
systemIdentifier = null;
publicIdentifier = null;
doctypeName = null;
tagName = null;
attributeName = null;
tokenHandler.endTokenization();
if (attributes != null) {
attributes.clear();
attributes.release();
}
}
public void requestSuspension() {
shouldSuspend = true;
}
/**
* Returns the alreadyComplainedAboutNonAscii.
*
* @return the alreadyComplainedAboutNonAscii
*/
public boolean isAlreadyComplainedAboutNonAscii() {
return alreadyComplainedAboutNonAscii;
}
}
| true | true | private void stateLoop(int state, char c, boolean reconsume, int returnState)
throws SAXException {
stateloop: for (;;) {
switch (state) {
case DATA:
dataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) When the content model
* flag is set to one of the PCDATA or RCDATA
* states and the escape flag is false: switch
* to the character reference data state.
* Otherwise: treat it as per the "anything
* else" entry below.
*/
flushChars();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
state = Tokenizer.TAG_OPEN;
break dataloop; // FALL THROUGH continue
// stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case TAG_OPEN:
tagopenloop: for (;;) {
/*
* The behavior of this state depends on the content
* model flag.
*/
/*
* If the content model flag is set to the PCDATA state
* Consume the next input character:
*/
c = read();
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to U+005A
* LATIN CAPITAL LETTER Z Create a new start tag
* token,
*/
endTag = false;
/*
* set its tag name to the lowercase version of the
* input character (add 0x0020 to the character's
* code point),
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
/* then switch to the tag name state. */
state = Tokenizer.TAG_NAME;
/*
* (Don't emit the token yet; further details will
* be filled in before it is emitted.)
*/
break tagopenloop;
// continue stateloop;
} else if (c >= 'a' && c <= 'z') {
/*
* U+0061 LATIN SMALL LETTER A through to U+007A
* LATIN SMALL LETTER Z Create a new start tag
* token,
*/
endTag = false;
/*
* set its tag name to the input character,
*/
clearStrBufAndAppendCurrentC();
/* then switch to the tag name state. */
state = Tokenizer.TAG_NAME;
/*
* (Don't emit the token yet; further details will
* be filled in before it is emitted.)
*/
break tagopenloop;
// continue stateloop;
}
switch (c) {
case '\u0000':
break stateloop;
case '!':
/*
* U+0021 EXCLAMATION MARK (!) Switch to the
* markup declaration open state.
*/
state = Tokenizer.MARKUP_DECLARATION_OPEN;
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the close tag
* open state.
*/
state = Tokenizer.CLOSE_TAG_OPEN_PCDATA;
continue stateloop;
case '?':
/*
* U+003F QUESTION MARK (?) Parse error.
*/
err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)");
/*
* Switch to the bogus comment state.
*/
clearLongStrBufAndAppendToComment('?');
state = Tokenizer.BOGUS_COMMENT;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C<\u201D) or mistyped start tag.");
/*
* Emit a U+003C LESS-THAN SIGN character token
* and a U+003E GREATER-THAN SIGN character
* token.
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 2);
/* Switch to the data state. */
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("Bad character \u201C"
+ c
+ "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C<\u201D.");
/*
* Emit a U+003C LESS-THAN SIGN character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in
* the data state.
*/
cstart = pos;
state = Tokenizer.DATA;
reconsume = true;
continue stateloop;
}
}
// FALL THROUGH DON'T REORDER
case TAG_NAME:
tagnameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
tagName = strBufToElementNameString();
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
break tagnameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
tagName = strBufToElementNameString();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
tagName = strBufToElementNameString();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
default:
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Append the
* lowercase version of the current input
* character (add 0x0020 to the character's
* code point) to the current tag token's
* tag name.
*/
appendStrBufForceWrite((char) (c + 0x20));
} else {
/*
* Anything else Append the current input
* character to the current tag token's tag
* name.
*/
appendStrBuf(c);
}
/*
* Stay in the tag name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_ATTRIBUTE_NAME:
beforeattributenameloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before attribute name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
case '\"':
case '\'':
case '=':
/*
* U+0022 QUOTATION MARK (") U+0027 APOSTROPHE
* (') U+003D EQUALS SIGN (=) Parse error.
*/
if (c == '=') {
err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing.");
} else {
err("Saw \u201C"
+ c
+ "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before.");
}
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
/*
* Anything else Start a new attribute in the
* current tag token.
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Set that
* attribute's name to the lowercase version
* of the current input character (add
* 0x0020 to the character's code point)
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
} else {
/*
* Set that attribute's name to the current
* input character,
*/
clearStrBufAndAppendCurrentC();
}
/*
* and its value to the empty string.
*/
// Will do later.
/*
* Switch to the attribute name state.
*/
state = Tokenizer.ATTRIBUTE_NAME;
break beforeattributenameloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case ATTRIBUTE_NAME:
attributenameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the after attribute name state.
*/
attributeNameComplete();
state = Tokenizer.AFTER_ATTRIBUTE_NAME;
continue stateloop;
case '=':
/*
* U+003D EQUALS SIGN (=) Switch to the before
* attribute value state.
*/
attributeNameComplete();
state = Tokenizer.BEFORE_ATTRIBUTE_VALUE;
break attributenameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
attributeNameComplete();
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
attributeNameComplete();
addAttributeWithoutValue();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
case '\"':
case '\'':
/*
* U+0022 QUOTATION MARK (") U+0027 APOSTROPHE
* (') Parse error.
*/
err("Quote \u201C"
+ c
+ "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier.");
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Append the
* lowercase version of the current input
* character (add 0x0020 to the character's
* code point) to the current attribute's
* name.
*/
appendStrBufForceWrite((char) (c + 0x20));
} else {
/*
* Anything else Append the current input
* character to the current attribute's
* name.
*/
appendStrBuf(c);
}
/*
* Stay in the attribute name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_ATTRIBUTE_VALUE:
beforeattributevalueloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before attribute value state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the
* attribute value (double-quoted) state.
*/
clearLongStrBufForNextState();
state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
break beforeattributevalueloop;
// continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the attribute
* value (unquoted) state and reconsume this
* input character.
*/
clearLongStrBuf();
state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED;
reconsume = true;
continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the attribute
* value (single-quoted) state.
*/
clearLongStrBufForNextState();
state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '=':
/*
* U+003D EQUALS SIGN (=) Parse error.
*/
err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign.");
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
if (html4
&& !((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '.' || c == '-'
|| c == '_' || c == ':')) {
err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)");
}
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
clearLongStrBufAndAppendCurrentC();
/*
* Switch to the attribute value (unquoted)
* state.
*/
state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case ATTRIBUTE_VALUE_DOUBLE_QUOTED:
attributevaluedoublequotedloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* attribute value (quoted) state.
*/
addAttributeWithValue();
state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED;
break attributevaluedoublequotedloop;
// continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with the
* additional allowed character being U+0022
* QUOTATION MARK (").
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\"';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (double-quoted)
* state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_ATTRIBUTE_VALUE_QUOTED:
afterattributevaluequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
state = Tokenizer.SELF_CLOSING_START_TAG;
break afterattributevaluequotedloop;
// continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("No space between attributes.");
/*
* Reconsume the character in the before
* attribute name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case SELF_CLOSING_START_TAG:
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Set the self-closing
* flag of the current tag token. Emit the current
* tag token.
*/
state = emitCurrentTagToken(true);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
default:
/* Anything else Parse error. */
err("A slash was not immediate followed by \u201C>\u201D.");
/*
* Reconsume the character in the before attribute
* name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
reconsume = true;
continue stateloop;
}
// XXX reorder point
case ATTRIBUTE_VALUE_UNQUOTED:
for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
addAttributeWithValue();
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with no +
* additional allowed character.
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '<':
case '\"':
case '\'':
case '=':
if (c == '<') {
warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before.");
} else {
/*
* U+0022 QUOTATION MARK (") U+0027
* APOSTROPHE (') U+003D EQUALS SIGN (=)
* Parse error.
*/
err("\u201C"
+ c
+ "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value.");
/*
* Treat it as per the "anything else" entry
* below.
*/
}
// fall through
default:
if (html4
&& !((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '.' || c == '-'
|| c == '_' || c == ':')) {
err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)");
}
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (unquoted) state.
*/
continue;
}
}
// XXX reorder point
case AFTER_ATTRIBUTE_NAME:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after attribute name state.
*/
continue;
case '=':
/*
* U+003D EQUALS SIGN (=) Switch to the before
* attribute value state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_VALUE;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
addAttributeWithoutValue();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
default:
addAttributeWithoutValue();
/*
* Anything else Start a new attribute in the
* current tag token.
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Set that
* attribute's name to the lowercase version
* of the current input character (add
* 0x0020 to the character's code point)
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
} else {
/*
* Set that attribute's name to the current
* input character,
*/
clearStrBufAndAppendCurrentC();
}
/*
* and its value to the empty string.
*/
// Will do later.
/*
* Switch to the attribute name state.
*/
state = Tokenizer.ATTRIBUTE_NAME;
continue stateloop;
}
}
// XXX reorder point
case BOGUS_COMMENT:
boguscommentloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* (This can only happen if the content model flag is
* set to the PCDATA state.)
*
* Consume every character up to and including the first
* U+003E GREATER-THAN SIGN character (>) or the end of
* the file (EOF), whichever comes first. Emit a comment
* token whose data is the concatenation of all the
* characters starting from and including the character
* that caused the state machine to switch into the
* bogus comment state, up to and including the
* character immediately before the last consumed
* character (i.e. up to the character just before the
* U+003E or EOF character). (If the comment was started
* by the end of the file (EOF), the token is empty.)
*
* Switch to the data state.
*
* If the end of the file was reached, reconsume the EOF
* character.
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
emitComment(0);
state = Tokenizer.DATA;
continue stateloop;
case '-':
appendLongStrBuf(c);
state = Tokenizer.BOGUS_COMMENT_HYPHEN;
break boguscommentloop;
default:
appendLongStrBuf(c);
continue;
}
}
// FALLTHRU DON'T REORDER
case BOGUS_COMMENT_HYPHEN:
boguscommenthyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '>':
maybeAppendSpaceToBogusComment();
emitComment(0);
state = Tokenizer.DATA;
continue stateloop;
case '-':
appendSecondHyphenToBogusComment();
continue boguscommenthyphenloop;
default:
appendLongStrBuf(c);
continue stateloop;
}
}
// XXX reorder point
case MARKUP_DECLARATION_OPEN:
markupdeclarationopenloop: for (;;) {
c = read();
/*
* (This can only happen if the content model flag is
* set to the PCDATA state.)
*
* If the next two characters are both U+002D
* HYPHEN-MINUS (-) characters, consume those two
* characters, create a comment token whose data is the
* empty string, and switch to the comment start state.
*
* Otherwise, if the next seven characters are a
* case-insensitive match for the word "DOCTYPE", then
* consume those characters and switch to the DOCTYPE
* state.
*
* Otherwise, if the insertion mode is "in foreign
* content" and the current node is not an element in
* the HTML namespace and the next seven characters are
* a case-sensitive match for the string "[CDATA[" (the
* five uppercase letters "CDATA" with a U+005B LEFT
* SQUARE BRACKET character before and after), then
* consume those characters and switch to the CDATA
* section state (which is unrelated to the content
* model flag's CDATA state).
*
* Otherwise, is is a parse error. Switch to the bogus
* comment state. The next character that is consumed,
* if any, is the first character that will be in the
* comment.
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
clearLongStrBufAndAppendToComment(c);
state = Tokenizer.MARKUP_DECLARATION_HYPHEN;
break markupdeclarationopenloop;
// continue stateloop;
case 'd':
case 'D':
clearLongStrBufAndAppendToComment(c);
index = 0;
state = Tokenizer.MARKUP_DECLARATION_OCTYPE;
continue stateloop;
case '[':
if (tokenHandler.inForeign()) {
clearLongStrBufAndAppendToComment(c);
index = 0;
state = Tokenizer.CDATA_START;
continue stateloop;
} else {
// fall through
}
default:
err("Bogus comment.");
clearLongStrBuf();
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case MARKUP_DECLARATION_HYPHEN:
markupdeclarationhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
clearLongStrBufForNextState();
state = Tokenizer.COMMENT_START;
break markupdeclarationhyphenloop;
// continue stateloop;
default:
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_START:
commentstartloop: for (;;) {
c = read();
/*
* Comment start state
*
*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* start dash state.
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_START_DASH;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Premature end of comment. Use \u201C-->\u201D to end a comment properly.");
/* Emit the comment token. */
emitComment(0);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the input character to
* the comment token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
break commentstartloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT:
commentloop: for (;;) {
c = read();
/*
* Comment state Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* end dash state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END_DASH;
break commentloop;
// continue stateloop;
default:
/*
* Anything else Append the input character to
* the comment token's data.
*/
appendLongStrBuf(c);
/*
* Stay in the comment state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_END_DASH:
commentenddashloop: for (;;) {
c = read();
/*
* Comment end dash state Consume the next input
* character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* end state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END;
break commentenddashloop;
// continue stateloop;
default:
/*
* Anything else Append a U+002D HYPHEN-MINUS
* (-) character and the input character to the
* comment token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_END:
for (;;) {
c = read();
/*
* Comment end dash state Consume the next input
* character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the comment
* token.
*/
emitComment(2);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
case '-':
/* U+002D HYPHEN-MINUS (-) Parse error. */
err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is.");
/*
* Append a U+002D HYPHEN-MINUS (-) character to
* the comment token's data.
*/
adjustDoubleHyphenAndAppendToLongStrBuf(c);
/*
* Stay in the comment end state.
*/
continue;
default:
/*
* Anything else Parse error.
*/
err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is.");
/*
* Append two U+002D HYPHEN-MINUS (-) characters
* and the input character to the comment
* token's data.
*/
adjustDoubleHyphenAndAppendToLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
}
// XXX reorder point
case COMMENT_START_DASH:
c = read();
/*
* Comment start dash state
*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment end
* state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Premature end of comment. Use \u201C-->\u201D to end a comment properly.");
/* Emit the comment token. */
emitComment(1);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append a U+002D HYPHEN-MINUS (-)
* character and the input character to the comment
* token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
// XXX reorder point
case MARKUP_DECLARATION_OCTYPE:
markupdeclarationdoctypeloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
if (index < 6) { // OCTYPE.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded == Tokenizer.OCTYPE[index]) {
appendLongStrBuf(c);
} else {
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
state = Tokenizer.DOCTYPE;
reconsume = true;
break markupdeclarationdoctypeloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE:
doctypeloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
systemIdentifier = null;
publicIdentifier = null;
doctypeName = null;
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before DOCTYPE name state.
*/
state = Tokenizer.BEFORE_DOCTYPE_NAME;
break doctypeloop;
// continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("Missing space before doctype name.");
/*
* Reconsume the current character in the before
* DOCTYPE name state.
*/
state = Tokenizer.BEFORE_DOCTYPE_NAME;
reconsume = true;
break doctypeloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_NAME:
beforedoctypenameloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Nameless doctype.");
/*
* Create a new DOCTYPE token. Set its
* force-quirks flag to on. Emit the token.
*/
tokenHandler.doctype("", null, null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/* Anything else Create a new DOCTYPE token. */
/*
* Set the token's name name to the current
* input character.
*/
clearStrBufAndAppendCurrentC();
/*
* Switch to the DOCTYPE name state.
*/
state = Tokenizer.DOCTYPE_NAME;
break beforedoctypenameloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_NAME:
doctypenameloop: for (;;) {
c = read();
/*
* First, consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the after DOCTYPE name state.
*/
doctypeName = strBufToString();
state = Tokenizer.AFTER_DOCTYPE_NAME;
break doctypenameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(strBufToString(), null,
null, false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* name.
*/
appendStrBuf(c);
/*
* Stay in the DOCTYPE name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_NAME:
afterdoctypenameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
case 'p':
case 'P':
index = 0;
state = Tokenizer.DOCTYPE_UBLIC;
break afterdoctypenameloop;
// continue stateloop;
case 's':
case 'S':
index = 0;
state = Tokenizer.DOCTYPE_YSTEM;
continue stateloop;
default:
/*
* Otherwise, this is the parse error.
*/
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_UBLIC:
doctypeublicloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* If the next six characters are a case-insensitive
* match for the word "PUBLIC", then consume those
* characters and switch to the before DOCTYPE public
* identifier state.
*/
if (index < 5) { // UBLIC.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != Tokenizer.UBLIC[index]) {
bogusDoctype();
// forceQuirks = true;
state = Tokenizer.BOGUS_DOCTYPE;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;
reconsume = true;
break doctypeublicloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:
beforedoctypepublicidentifierloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE public identifier
* state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's public identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE public identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
break beforedoctypepublicidentifierloop;
// continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* public identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE public identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
continue stateloop;
case '>':
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Expected a public identifier but the doctype ended.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:
doctypepublicidentifierdoublequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* DOCTYPE public identifier state.
*/
publicIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
break doctypepublicidentifierdoublequotedloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in public identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
longStrBufToString(), null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* public identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE public identifier
* (double-quoted) state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_PUBLIC_IDENTIFIER:
afterdoctypepublicidentifierloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE public identifier state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's system identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
break afterdoctypepublicidentifierloop;
// continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* system identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, null, false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:
doctypesystemidentifierdoublequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* DOCTYPE system identifier state.
*/
systemIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in system identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, longStrBufToString(),
true);
/*
* Switch to the data state.
*
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* system identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE system identifier
* (double-quoted) state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_SYSTEM_IDENTIFIER:
afterdoctypesystemidentifierloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE system identifier state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, systemIdentifier,
false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Switch to the bogus DOCTYPE state. (This does
* not set the DOCTYPE token's force-quirks flag
* to on.)
*/
bogusDoctypeWithoutQuirks();
state = Tokenizer.BOGUS_DOCTYPE;
break afterdoctypesystemidentifierloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BOGUS_DOCTYPE:
for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit that
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, systemIdentifier,
forceQuirks);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Stay in the bogus DOCTYPE
* state.
*/
continue;
}
}
// XXX reorder point
case DOCTYPE_YSTEM:
doctypeystemloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Otherwise, if the next six characters are a
* case-insensitive match for the word "SYSTEM", then
* consume those characters and switch to the before
* DOCTYPE system identifier state.
*/
if (index < 5) { // YSTEM.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != Tokenizer.YSTEM[index]) {
bogusDoctype();
state = Tokenizer.BOGUS_DOCTYPE;
reconsume = true;
continue stateloop;
}
index++;
continue stateloop;
} else {
state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;
reconsume = true;
break doctypeystemloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:
beforedoctypesystemidentifierloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE system identifier
* state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's system identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* system identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
break beforedoctypesystemidentifierloop;
// continue stateloop;
case '>':
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Expected a system identifier but the doctype ended.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* DOCTYPE system identifier state.
*/
systemIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in system identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, longStrBufToString(),
true);
/*
* Switch to the data state.
*
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* system identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE system identifier
* (double-quoted) state.
*/
continue;
}
}
// XXX reorder point
case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* DOCTYPE public identifier state.
*/
publicIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in public identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
longStrBufToString(), null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* public identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE public identifier
* (single-quoted) state.
*/
continue;
}
}
// XXX reorder point
case CDATA_START:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
if (index < 6) { // CDATA_LSQB.length
if (c == Tokenizer.CDATA_LSQB[index]) {
appendLongStrBuf(c);
} else {
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
cstart = pos; // start coalescing
state = Tokenizer.CDATA_SECTION;
reconsume = true;
break; // FALL THROUGH continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_SECTION:
cdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case ']':
flushChars();
state = Tokenizer.CDATA_RSQB;
break cdataloop; // FALL THROUGH
default:
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_RSQB:
cdatarsqb: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case ']':
state = Tokenizer.CDATA_RSQB_RSQB;
break cdatarsqb;
default:
tokenHandler.characters(Tokenizer.RSQB_RSQB, 0,
1);
cstart = pos;
state = Tokenizer.CDATA_SECTION;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_RSQB_RSQB:
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '>':
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2);
cstart = pos;
state = Tokenizer.CDATA_SECTION;
reconsume = true;
continue stateloop;
}
// XXX reorder point
case ATTRIBUTE_VALUE_SINGLE_QUOTED:
attributevaluesinglequotedloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* attribute value (quoted) state.
*/
addAttributeWithValue();
state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED;
continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with the +
* additional allowed character being U+0027
* APOSTROPHE (').
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\'';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
break attributevaluesinglequotedloop;
// continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (double-quoted)
* state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case CONSUME_CHARACTER_REFERENCE:
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Unlike the definition is the spec, this state does not
* return a value and never requires the caller to
* backtrack. This state takes care of emitting characters
* or appending to the current attribute value. It also
* takes care of that in the case when consuming the
* character reference fails.
*/
/*
* This section defines how to consume a character
* reference. This definition is used when parsing character
* references in text and in attributes.
*
* The behavior depends on the identity of the next
* character (the one immediately after the U+0026 AMPERSAND
* character):
*/
switch (c) {
case ' ':
case '\t':
case '\n':
case '\u000C':
case '<':
case '&':
emitOrAppendStrBuf(returnState);
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
case '#':
/*
* U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER
* SIGN.
*/
appendStrBuf('#');
state = Tokenizer.CONSUME_NCR;
continue stateloop;
default:
if (c == additional) {
emitOrAppendStrBuf(returnState);
state = returnState;
reconsume = true;
continue stateloop;
}
entCol = -1;
lo = 0;
hi = (NamedCharacters.NAMES.length - 1);
candidate = -1;
strBufMark = 0;
state = Tokenizer.CHARACTER_REFERENCE_LOOP;
reconsume = true;
// FALL THROUGH continue stateloop;
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CHARACTER_REFERENCE_LOOP:
outer: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
if (c == '\u0000') {
break stateloop;
}
entCol++;
/*
* Anything else Consume the maximum number of
* characters possible, with the consumed characters
* case-sensitively matching one of the identifiers in
* the first column of the named character references
* table.
*/
hiloop: for (;;) {
if (hi == -1) {
break hiloop;
}
if (entCol == NamedCharacters.NAMES[hi].length) {
break hiloop;
}
if (entCol > NamedCharacters.NAMES[hi].length) {
break outer;
} else if (c < NamedCharacters.NAMES[hi][entCol]) {
hi--;
} else {
break hiloop;
}
}
loloop: for (;;) {
if (hi < lo) {
break outer;
}
if (entCol == NamedCharacters.NAMES[lo].length) {
candidate = lo;
strBufMark = strBufLen;
lo++;
} else if (entCol > NamedCharacters.NAMES[lo].length) {
break outer;
} else if (c > NamedCharacters.NAMES[lo][entCol]) {
lo++;
} else {
break loloop;
}
}
if (hi < lo) {
break outer;
}
appendStrBuf(c);
continue;
}
// TODO warn about apos (IE) and TRADE (Opera)
if (candidate == -1) {
/*
* If no match can be made, then this is a parse error.
*/
err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
char[] candidateArr = NamedCharacters.NAMES[candidate];
if (candidateArr[candidateArr.length - 1] != ';') {
/*
* If the last character matched is not a U+003B
* SEMICOLON (;), there is a parse error.
*/
err("Entity reference was not terminated by a semicolon.");
if ((returnState & (~1)) != 0) {
/*
* If the entity is being consumed as part of an
* attribute, and the last character matched is
* not a U+003B SEMICOLON (;),
*/
char ch;
if (strBufMark == strBufLen) {
ch = c;
} else {
// if (strBufOffset != -1) {
// ch = buf[strBufOffset + strBufMark];
// } else {
ch = strBuf[strBufMark];
// }
}
if ((ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')) {
/*
* and the next character is in the range
* U+0030 DIGIT ZERO to U+0039 DIGIT NINE,
* U+0041 LATIN CAPITAL LETTER A to U+005A
* LATIN CAPITAL LETTER Z, or U+0061 LATIN
* SMALL LETTER A to U+007A LATIN SMALL
* LETTER Z, then, for historical reasons,
* all the characters that were matched
* after the U+0026 AMPERSAND (&) must be
* unconsumed, and nothing is returned.
*/
appendStrBufToLongStrBuf();
state = returnState;
reconsume = true;
continue stateloop;
}
}
}
/*
* Otherwise, return a character token for the character
* corresponding to the entity name (as given by the
* second column of the named character references
* table).
*/
char[] val = NamedCharacters.VALUES[candidate];
emitOrAppend(val, returnState);
// this is so complicated!
if (strBufMark < strBufLen) {
if (strBufOffset != -1) {
if ((returnState & (~1)) != 0) {
for (int i = strBufMark; i < strBufLen; i++) {
appendLongStrBuf(buf[strBufOffset + i]);
}
} else {
tokenHandler.characters(buf, strBufOffset
+ strBufMark, strBufLen
- strBufMark);
}
} else {
if ((returnState & (~1)) != 0) {
for (int i = strBufMark; i < strBufLen; i++) {
appendLongStrBuf(strBuf[i]);
}
} else {
tokenHandler.characters(strBuf, strBufMark,
strBufLen - strBufMark);
}
}
}
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
/*
* If the markup contains I'm ¬it; I tell you, the
* entity is parsed as "not", as in, I'm ¬it; I tell
* you. But if the markup was I'm ∉ I tell you,
* the entity would be parsed as "notin;", resulting in
* I'm ∉ I tell you.
*/
}
// XXX reorder point
case CONSUME_NCR:
c = read();
prevValue = -1;
value = 0;
seenDigits = false;
/*
* The behavior further depends on the character after the
* U+0023 NUMBER SIGN:
*/
switch (c) {
case '\u0000':
break stateloop;
case 'x':
case 'X':
/*
* U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL
* LETTER X Consume the X.
*
* Follow the steps below, but using the range of
* characters U+0030 DIGIT ZERO through to U+0039
* DIGIT NINE, U+0061 LATIN SMALL LETTER A through
* to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN
* CAPITAL LETTER A, through to U+0046 LATIN CAPITAL
* LETTER F (in other words, 0-9, A-F, a-f).
*
* When it comes to interpreting the number,
* interpret it as a hexadecimal number.
*/
appendStrBuf(c);
state = Tokenizer.HEX_NCR_LOOP;
continue stateloop;
default:
/*
* Anything else Follow the steps below, but using
* the range of characters U+0030 DIGIT ZERO through
* to U+0039 DIGIT NINE (i.e. just 0-9).
*
* When it comes to interpreting the number,
* interpret it as a decimal number.
*/
state = Tokenizer.DECIMAL_NRC_LOOP;
reconsume = true;
// FALL THROUGH continue stateloop;
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case DECIMAL_NRC_LOOP:
decimalloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
if (c == '\u0000') {
break stateloop;
}
// Deal with overflow gracefully
if (value < prevValue) {
value = 0x110000; // Value above Unicode range but
// within int
// range
}
prevValue = value;
/*
* Consume as many characters as match the range of
* characters given above.
*/
if (c >= '0' && c <= '9') {
seenDigits = true;
value *= 10;
value += c - '0';
continue;
} else if (c == ';') {
if (seenDigits) {
state = Tokenizer.HANDLE_NCR_VALUE;
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
// FALL THROUGH continue stateloop;
break decimalloop;
} else {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
appendStrBuf(';');
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
state = returnState;
continue stateloop;
}
} else {
/*
* If no characters match the range, then don't
* consume any characters (and unconsume the U+0023
* NUMBER SIGN character and, if appropriate, the X
* character). This is a parse error; nothing is
* returned.
*
* Otherwise, if the next character is a U+003B
* SEMICOLON, consume that too. If it isn't, there
* is a parse error.
*/
if (!seenDigits) {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
err("Character reference was not terminated by a semicolon.");
state = Tokenizer.HANDLE_NCR_VALUE;
reconsume = true;
if ((returnState & (~1)) == 0) {
cstart = pos;
}
// FALL THROUGH continue stateloop;
break decimalloop;
}
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case HANDLE_NCR_VALUE:
// WARNING previous state sets reconsume
// XXX inline this case if the method size can take it
handleNcrValue(returnState);
state = returnState;
continue stateloop;
// XXX reorder point
case HEX_NCR_LOOP:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
// Deal with overflow gracefully
if (value < prevValue) {
value = 0x110000; // Value above Unicode range but
// within int
// range
}
prevValue = value;
/*
* Consume as many characters as match the range of
* characters given above.
*/
if (c >= '0' && c <= '9') {
seenDigits = true;
value *= 16;
value += c - '0';
continue;
} else if (c >= 'A' && c <= 'F') {
seenDigits = true;
value *= 16;
value += c - 'A' + 10;
continue;
} else if (c >= 'a' && c <= 'f') {
seenDigits = true;
value *= 16;
value += c - 'a' + 10;
continue;
} else if (c == ';') {
if (seenDigits) {
state = Tokenizer.HANDLE_NCR_VALUE;
cstart = pos + 1;
continue stateloop;
} else {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
appendStrBuf(';');
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
state = returnState;
continue stateloop;
}
} else {
/*
* If no characters match the range, then don't
* consume any characters (and unconsume the U+0023
* NUMBER SIGN character and, if appropriate, the X
* character). This is a parse error; nothing is
* returned.
*
* Otherwise, if the next character is a U+003B
* SEMICOLON, consume that too. If it isn't, there
* is a parse error.
*/
if (!seenDigits) {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
err("Character reference was not terminated by a semicolon.");
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = Tokenizer.HANDLE_NCR_VALUE;
reconsume = true;
continue stateloop;
}
}
}
// XXX reorder point
case PLAINTEXT:
plaintextloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// XXX reorder point
case CDATA:
cdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
returnState = state;
state = Tokenizer.TAG_OPEN_NON_PCDATA;
break cdataloop; // FALL THRU continue
// stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case TAG_OPEN_NON_PCDATA:
tagopennonpcdataloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '!':
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
cstart = pos;
state = Tokenizer.ESCAPE_EXCLAMATION;
break tagopennonpcdataloop; // FALL THRU
// continue
// stateloop;
case '/':
/*
* If the content model flag is set to the
* RCDATA or CDATA states Consume the next input
* character.
*/
if (contentModelElement != null) {
/*
* If it is a U+002F SOLIDUS (/) character,
* switch to the close tag open state.
*/
index = 0;
clearStrBufForNextState();
state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA;
continue stateloop;
} // else fall through
default:
/*
* Otherwise, emit a U+003C LESS-THAN SIGN
* character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in
* the data state.
*/
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_EXCLAMATION:
escapeexclamationloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN;
break escapeexclamationloop; // FALL THRU
// continue
// stateloop;
default:
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_EXCLAMATION_HYPHEN:
escapeexclamationhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN_HYPHEN;
break escapeexclamationhyphenloop;
// continue stateloop;
default:
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_HYPHEN_HYPHEN:
escapehyphenhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
continue;
case '>':
state = returnState;
continue stateloop;
default:
state = Tokenizer.ESCAPE;
break escapehyphenhyphenloop;
// continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE:
escapeloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN;
break escapeloop; // FALL THRU continue
// stateloop;
default:
continue escapeloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_HYPHEN:
escapehyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN_HYPHEN;
continue stateloop;
default:
state = Tokenizer.ESCAPE;
continue stateloop;
}
}
// XXX reorder point
case CLOSE_TAG_OPEN_NOT_PCDATA:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
// ASSERT! when entering this state, set index to 0 and
// call clearStrBuf()
assert (contentModelElement != null);
/*
* If the content model flag is set to the RCDATA or
* CDATA states but no start tag token has ever been
* emitted by this instance of the tokenizer (fragment
* case), or, if the content model flag is set to the
* RCDATA or CDATA states and the next few characters do
* not match the tag name of the last start tag token
* emitted (case insensitively), or if they do but they
* are not immediately followed by one of the following
* characters: + U+0009 CHARACTER TABULATION + U+000A
* LINE FEED (LF) + + U+000C FORM FEED (FF) + U+0020
* SPACE + U+003E GREATER-THAN SIGN (>) + U+002F SOLIDUS
* (/) + EOF
*
* ...then emit a U+003C LESS-THAN SIGN character token,
* a U+002F SOLIDUS character token, and switch to the
* data state to process the next input character.
*/
// Let's implement the above without lookahead. strBuf
// holds
// characters that need to be emitted if looking for an
// end tag
// fails.
// Duplicating the relevant part of tag name state here
// as well.
if (index < contentModelElement.name.length()) {
char e = contentModelElement.name.charAt(index);
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != e) {
if (index > 0
|| (folded >= 'a' && folded <= 'z')) {
// [NOCPP[
if (html4) {
if (ElementName.IFRAME != contentModelElement) {
err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)");
}
} else {
// ]NOCPP]
warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but this did not close the element.");
// [NOCPP[
}
// ]NOCPP]
}
tokenHandler.characters(Tokenizer.LT_SOLIDUS,
0, 2);
emitStrBuf();
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
}
appendStrBuf(c);
index++;
continue;
} else {
endTag = true;
// XXX replace contentModelElement with different
// type
tagName = contentModelElement;
switch (c) {
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE
* FEED (LF) U+000C FORM FEED (FF) U+0020
* SPACE Switch to the before attribute name
* state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the
* current tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Parse error unless
* this is a permitted slash.
*/
// never permitted here
err("Stray \u201C/\u201D in end tag.");
/*
* Switch to the before attribute name
* state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
default:
if (html4) {
err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)");
} else {
warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but this did not close the element.");
}
tokenHandler.characters(
Tokenizer.LT_SOLIDUS, 0, 2);
emitStrBuf();
cstart = pos; // don't drop the character
state = Tokenizer.DATA;
continue stateloop;
}
}
}
// XXX reorder point
case CLOSE_TAG_OPEN_PCDATA:
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Otherwise, if the content model flag is set to the PCDATA
* state, or if the next few characters do match that tag
* name, consume the next input character:
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN
* CAPITAL LETTER Z Create a new end tag token,
*/
endTag = true;
/*
* set its tag name to the lowercase version of the
* input character (add 0x0020 to the character's code
* point),
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
/*
* then switch to the tag name state. (Don't emit the
* token yet; further details will be filled in before
* it is emitted.)
*/
state = Tokenizer.TAG_NAME;
continue stateloop;
} else if (c >= 'a' && c <= 'z') {
/*
* U+0061 LATIN SMALL LETTER A through to U+007A LATIN
* SMALL LETTER Z Create a new end tag token,
*/
endTag = true;
/*
* set its tag name to the input character,
*/
clearStrBufAndAppendCurrentC();
/*
* then switch to the tag name state. (Don't emit the
* token yet; further details will be filled in before
* it is emitted.)
*/
state = Tokenizer.TAG_NAME;
continue stateloop;
} else if (c == '>') {
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C<\u201D) or mistyped end tag.");
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
} else {
/* Anything else Parse error. */
err("Garbage after \u201C</\u201D.");
/*
* Switch to the bogus comment state.
*/
clearLongStrBufAndAppendToComment(c);
state = Tokenizer.BOGUS_COMMENT;
continue stateloop;
}
// XXX reorder point
case RCDATA:
rcdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) When the content model
* flag is set to one of the PCDATA or RCDATA
* states and the escape flag is false: switch
* to the character reference data state.
* Otherwise: treat it as per the "anything
* else" entry below.
*/
flushChars();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
returnState = state;
state = Tokenizer.TAG_OPEN_NON_PCDATA;
continue stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
}
}
flushChars();
if (prev == '\r' && pos != end) {
pos--;
col--;
}
// Save locals
stateSave = state;
returnStateSave = returnState;
}
| private void stateLoop(int state, char c, boolean reconsume, int returnState)
throws SAXException {
stateloop: for (;;) {
switch (state) {
case DATA:
dataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) When the content model
* flag is set to one of the PCDATA or RCDATA
* states and the escape flag is false: switch
* to the character reference data state.
* Otherwise: treat it as per the "anything
* else" entry below.
*/
flushChars();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
state = Tokenizer.TAG_OPEN;
break dataloop; // FALL THROUGH continue
// stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case TAG_OPEN:
tagopenloop: for (;;) {
/*
* The behavior of this state depends on the content
* model flag.
*/
/*
* If the content model flag is set to the PCDATA state
* Consume the next input character:
*/
c = read();
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to U+005A
* LATIN CAPITAL LETTER Z Create a new start tag
* token,
*/
endTag = false;
/*
* set its tag name to the lowercase version of the
* input character (add 0x0020 to the character's
* code point),
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
/* then switch to the tag name state. */
state = Tokenizer.TAG_NAME;
/*
* (Don't emit the token yet; further details will
* be filled in before it is emitted.)
*/
break tagopenloop;
// continue stateloop;
} else if (c >= 'a' && c <= 'z') {
/*
* U+0061 LATIN SMALL LETTER A through to U+007A
* LATIN SMALL LETTER Z Create a new start tag
* token,
*/
endTag = false;
/*
* set its tag name to the input character,
*/
clearStrBufAndAppendCurrentC();
/* then switch to the tag name state. */
state = Tokenizer.TAG_NAME;
/*
* (Don't emit the token yet; further details will
* be filled in before it is emitted.)
*/
break tagopenloop;
// continue stateloop;
}
switch (c) {
case '\u0000':
break stateloop;
case '!':
/*
* U+0021 EXCLAMATION MARK (!) Switch to the
* markup declaration open state.
*/
state = Tokenizer.MARKUP_DECLARATION_OPEN;
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the close tag
* open state.
*/
state = Tokenizer.CLOSE_TAG_OPEN_PCDATA;
continue stateloop;
case '?':
/*
* U+003F QUESTION MARK (?) Parse error.
*/
err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)");
/*
* Switch to the bogus comment state.
*/
clearLongStrBufAndAppendToComment('?');
state = Tokenizer.BOGUS_COMMENT;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C<\u201D) or mistyped start tag.");
/*
* Emit a U+003C LESS-THAN SIGN character token
* and a U+003E GREATER-THAN SIGN character
* token.
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 2);
/* Switch to the data state. */
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("Bad character \u201C"
+ c
+ "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C<\u201D.");
/*
* Emit a U+003C LESS-THAN SIGN character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in
* the data state.
*/
cstart = pos;
state = Tokenizer.DATA;
reconsume = true;
continue stateloop;
}
}
// FALL THROUGH DON'T REORDER
case TAG_NAME:
tagnameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
tagName = strBufToElementNameString();
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
break tagnameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
tagName = strBufToElementNameString();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
tagName = strBufToElementNameString();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
default:
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Append the
* lowercase version of the current input
* character (add 0x0020 to the character's
* code point) to the current tag token's
* tag name.
*/
appendStrBufForceWrite((char) (c + 0x20));
} else {
/*
* Anything else Append the current input
* character to the current tag token's tag
* name.
*/
appendStrBuf(c);
}
/*
* Stay in the tag name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_ATTRIBUTE_NAME:
beforeattributenameloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before attribute name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
case '\"':
case '\'':
case '=':
/*
* U+0022 QUOTATION MARK (") U+0027 APOSTROPHE
* (') U+003D EQUALS SIGN (=) Parse error.
*/
if (c == '=') {
err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing.");
} else {
err("Saw \u201C"
+ c
+ "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before.");
}
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
/*
* Anything else Start a new attribute in the
* current tag token.
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Set that
* attribute's name to the lowercase version
* of the current input character (add
* 0x0020 to the character's code point)
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
} else {
/*
* Set that attribute's name to the current
* input character,
*/
clearStrBufAndAppendCurrentC();
}
/*
* and its value to the empty string.
*/
// Will do later.
/*
* Switch to the attribute name state.
*/
state = Tokenizer.ATTRIBUTE_NAME;
break beforeattributenameloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case ATTRIBUTE_NAME:
attributenameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the after attribute name state.
*/
attributeNameComplete();
state = Tokenizer.AFTER_ATTRIBUTE_NAME;
continue stateloop;
case '=':
/*
* U+003D EQUALS SIGN (=) Switch to the before
* attribute value state.
*/
attributeNameComplete();
state = Tokenizer.BEFORE_ATTRIBUTE_VALUE;
break attributenameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
attributeNameComplete();
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
attributeNameComplete();
addAttributeWithoutValue();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
case '\"':
case '\'':
/*
* U+0022 QUOTATION MARK (") U+0027 APOSTROPHE
* (') Parse error.
*/
err("Quote \u201C"
+ c
+ "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier.");
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Append the
* lowercase version of the current input
* character (add 0x0020 to the character's
* code point) to the current attribute's
* name.
*/
appendStrBufForceWrite((char) (c + 0x20));
} else {
/*
* Anything else Append the current input
* character to the current attribute's
* name.
*/
appendStrBuf(c);
}
/*
* Stay in the attribute name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_ATTRIBUTE_VALUE:
beforeattributevalueloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before attribute value state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the
* attribute value (double-quoted) state.
*/
clearLongStrBufForNextState();
state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
break beforeattributevalueloop;
// continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the attribute
* value (unquoted) state and reconsume this
* input character.
*/
clearLongStrBuf();
state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED;
reconsume = true;
continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the attribute
* value (single-quoted) state.
*/
clearLongStrBufForNextState();
state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '=':
/*
* U+003D EQUALS SIGN (=) Parse error.
*/
err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign.");
/*
* Treat it as per the "anything else" entry
* below.
*/
default:
if (html4
&& !((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '.' || c == '-'
|| c == '_' || c == ':')) {
err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)");
}
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
clearLongStrBufAndAppendCurrentC();
/*
* Switch to the attribute value (unquoted)
* state.
*/
state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case ATTRIBUTE_VALUE_DOUBLE_QUOTED:
attributevaluedoublequotedloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* attribute value (quoted) state.
*/
addAttributeWithValue();
state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED;
break attributevaluedoublequotedloop;
// continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with the
* additional allowed character being U+0022
* QUOTATION MARK (").
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\"';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (double-quoted)
* state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_ATTRIBUTE_VALUE_QUOTED:
afterattributevaluequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
state = Tokenizer.SELF_CLOSING_START_TAG;
break afterattributevaluequotedloop;
// continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("No space between attributes.");
/*
* Reconsume the character in the before
* attribute name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case SELF_CLOSING_START_TAG:
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Set the self-closing
* flag of the current tag token. Emit the current
* tag token.
*/
state = emitCurrentTagToken(true);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
default:
/* Anything else Parse error. */
err("A slash was not immediate followed by \u201C>\u201D.");
/*
* Reconsume the character in the before attribute
* name state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
reconsume = true;
continue stateloop;
}
// XXX reorder point
case ATTRIBUTE_VALUE_UNQUOTED:
for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before attribute name state.
*/
addAttributeWithValue();
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with no +
* additional allowed character.
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '<':
case '\"':
case '\'':
case '=':
if (c == '<') {
warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before.");
} else {
/*
* U+0022 QUOTATION MARK (") U+0027
* APOSTROPHE (') U+003D EQUALS SIGN (=)
* Parse error.
*/
err("\u201C"
+ c
+ "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value.");
/*
* Treat it as per the "anything else" entry
* below.
*/
}
// fall through
default:
if (html4
&& !((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '.' || c == '-'
|| c == '_' || c == ':')) {
err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)");
}
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (unquoted) state.
*/
continue;
}
}
// XXX reorder point
case AFTER_ATTRIBUTE_NAME:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after attribute name state.
*/
continue;
case '=':
/*
* U+003D EQUALS SIGN (=) Switch to the before
* attribute value state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_VALUE;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* tag token.
*/
addAttributeWithoutValue();
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Switch to the self-closing
* start tag state.
*/
addAttributeWithoutValue();
state = Tokenizer.SELF_CLOSING_START_TAG;
continue stateloop;
default:
addAttributeWithoutValue();
/*
* Anything else Start a new attribute in the
* current tag token.
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to
* U+005A LATIN CAPITAL LETTER Z Set that
* attribute's name to the lowercase version
* of the current input character (add
* 0x0020 to the character's code point)
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
} else {
/*
* Set that attribute's name to the current
* input character,
*/
clearStrBufAndAppendCurrentC();
}
/*
* and its value to the empty string.
*/
// Will do later.
/*
* Switch to the attribute name state.
*/
state = Tokenizer.ATTRIBUTE_NAME;
continue stateloop;
}
}
// XXX reorder point
case BOGUS_COMMENT:
boguscommentloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* (This can only happen if the content model flag is
* set to the PCDATA state.)
*
* Consume every character up to and including the first
* U+003E GREATER-THAN SIGN character (>) or the end of
* the file (EOF), whichever comes first. Emit a comment
* token whose data is the concatenation of all the
* characters starting from and including the character
* that caused the state machine to switch into the
* bogus comment state, up to and including the
* character immediately before the last consumed
* character (i.e. up to the character just before the
* U+003E or EOF character). (If the comment was started
* by the end of the file (EOF), the token is empty.)
*
* Switch to the data state.
*
* If the end of the file was reached, reconsume the EOF
* character.
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
emitComment(0);
state = Tokenizer.DATA;
continue stateloop;
case '-':
appendLongStrBuf(c);
state = Tokenizer.BOGUS_COMMENT_HYPHEN;
break boguscommentloop;
default:
appendLongStrBuf(c);
continue;
}
}
// FALLTHRU DON'T REORDER
case BOGUS_COMMENT_HYPHEN:
boguscommenthyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '>':
maybeAppendSpaceToBogusComment();
emitComment(0);
state = Tokenizer.DATA;
continue stateloop;
case '-':
appendSecondHyphenToBogusComment();
continue boguscommenthyphenloop;
default:
appendLongStrBuf(c);
continue stateloop;
}
}
// XXX reorder point
case MARKUP_DECLARATION_OPEN:
markupdeclarationopenloop: for (;;) {
c = read();
/*
* (This can only happen if the content model flag is
* set to the PCDATA state.)
*
* If the next two characters are both U+002D
* HYPHEN-MINUS (-) characters, consume those two
* characters, create a comment token whose data is the
* empty string, and switch to the comment start state.
*
* Otherwise, if the next seven characters are a
* case-insensitive match for the word "DOCTYPE", then
* consume those characters and switch to the DOCTYPE
* state.
*
* Otherwise, if the insertion mode is "in foreign
* content" and the current node is not an element in
* the HTML namespace and the next seven characters are
* a case-sensitive match for the string "[CDATA[" (the
* five uppercase letters "CDATA" with a U+005B LEFT
* SQUARE BRACKET character before and after), then
* consume those characters and switch to the CDATA
* section state (which is unrelated to the content
* model flag's CDATA state).
*
* Otherwise, is is a parse error. Switch to the bogus
* comment state. The next character that is consumed,
* if any, is the first character that will be in the
* comment.
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
clearLongStrBufAndAppendToComment(c);
state = Tokenizer.MARKUP_DECLARATION_HYPHEN;
break markupdeclarationopenloop;
// continue stateloop;
case 'd':
case 'D':
clearLongStrBufAndAppendToComment(c);
index = 0;
state = Tokenizer.MARKUP_DECLARATION_OCTYPE;
continue stateloop;
case '[':
if (tokenHandler.inForeign()) {
clearLongStrBufAndAppendToComment(c);
index = 0;
state = Tokenizer.CDATA_START;
continue stateloop;
} else {
// fall through
}
default:
err("Bogus comment.");
clearLongStrBuf();
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case MARKUP_DECLARATION_HYPHEN:
markupdeclarationhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
clearLongStrBufForNextState();
state = Tokenizer.COMMENT_START;
break markupdeclarationhyphenloop;
// continue stateloop;
default:
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_START:
commentstartloop: for (;;) {
c = read();
/*
* Comment start state
*
*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* start dash state.
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_START_DASH;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Premature end of comment. Use \u201C-->\u201D to end a comment properly.");
/* Emit the comment token. */
emitComment(0);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the input character to
* the comment token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
break commentstartloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT:
commentloop: for (;;) {
c = read();
/*
* Comment state Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* end dash state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END_DASH;
break commentloop;
// continue stateloop;
default:
/*
* Anything else Append the input character to
* the comment token's data.
*/
appendLongStrBuf(c);
/*
* Stay in the comment state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_END_DASH:
commentenddashloop: for (;;) {
c = read();
/*
* Comment end dash state Consume the next input
* character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment
* end state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END;
break commentenddashloop;
// continue stateloop;
default:
/*
* Anything else Append a U+002D HYPHEN-MINUS
* (-) character and the input character to the
* comment token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case COMMENT_END:
for (;;) {
c = read();
/*
* Comment end dash state Consume the next input
* character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the comment
* token.
*/
emitComment(2);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
case '-':
/* U+002D HYPHEN-MINUS (-) Parse error. */
err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is.");
/*
* Append a U+002D HYPHEN-MINUS (-) character to
* the comment token's data.
*/
adjustDoubleHyphenAndAppendToLongStrBuf(c);
/*
* Stay in the comment end state.
*/
continue;
default:
/*
* Anything else Parse error.
*/
err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is.");
/*
* Append two U+002D HYPHEN-MINUS (-) characters
* and the input character to the comment
* token's data.
*/
adjustDoubleHyphenAndAppendToLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
}
// XXX reorder point
case COMMENT_START_DASH:
c = read();
/*
* Comment start dash state
*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '-':
/*
* U+002D HYPHEN-MINUS (-) Switch to the comment end
* state
*/
appendLongStrBuf(c);
state = Tokenizer.COMMENT_END;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Premature end of comment. Use \u201C-->\u201D to end a comment properly.");
/* Emit the comment token. */
emitComment(1);
/*
* Switch to the data state.
*/
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append a U+002D HYPHEN-MINUS (-)
* character and the input character to the comment
* token's data.
*/
appendLongStrBuf(c);
/*
* Switch to the comment state.
*/
state = Tokenizer.COMMENT;
continue stateloop;
}
// XXX reorder point
case MARKUP_DECLARATION_OCTYPE:
markupdeclarationdoctypeloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
if (index < 6) { // OCTYPE.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded == Tokenizer.OCTYPE[index]) {
appendLongStrBuf(c);
} else {
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
state = Tokenizer.DOCTYPE;
reconsume = true;
break markupdeclarationdoctypeloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE:
doctypeloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
systemIdentifier = null;
publicIdentifier = null;
doctypeName = null;
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the before DOCTYPE name state.
*/
state = Tokenizer.BEFORE_DOCTYPE_NAME;
break doctypeloop;
// continue stateloop;
default:
/*
* Anything else Parse error.
*/
err("Missing space before doctype name.");
/*
* Reconsume the current character in the before
* DOCTYPE name state.
*/
state = Tokenizer.BEFORE_DOCTYPE_NAME;
reconsume = true;
break doctypeloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_NAME:
beforedoctypenameloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("Nameless doctype.");
/*
* Create a new DOCTYPE token. Set its
* force-quirks flag to on. Emit the token.
*/
tokenHandler.doctype("", null, null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/* Anything else Create a new DOCTYPE token. */
/*
* Set the token's name name to the current
* input character.
*/
clearStrBufAndAppendCurrentC();
/*
* Switch to the DOCTYPE name state.
*/
state = Tokenizer.DOCTYPE_NAME;
break beforedoctypenameloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_NAME:
doctypenameloop: for (;;) {
c = read();
/*
* First, consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE
* Switch to the after DOCTYPE name state.
*/
doctypeName = strBufToString();
state = Tokenizer.AFTER_DOCTYPE_NAME;
break doctypenameloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(strBufToString(), null,
null, false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* name.
*/
appendStrBuf(c);
/*
* Stay in the DOCTYPE name state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_NAME:
afterdoctypenameloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE name state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
case 'p':
case 'P':
index = 0;
state = Tokenizer.DOCTYPE_UBLIC;
break afterdoctypenameloop;
// continue stateloop;
case 's':
case 'S':
index = 0;
state = Tokenizer.DOCTYPE_YSTEM;
continue stateloop;
default:
/*
* Otherwise, this is the parse error.
*/
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_UBLIC:
doctypeublicloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* If the next six characters are a case-insensitive
* match for the word "PUBLIC", then consume those
* characters and switch to the before DOCTYPE public
* identifier state.
*/
if (index < 5) { // UBLIC.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != Tokenizer.UBLIC[index]) {
bogusDoctype();
// forceQuirks = true;
state = Tokenizer.BOGUS_DOCTYPE;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;
reconsume = true;
break doctypeublicloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:
beforedoctypepublicidentifierloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE public identifier
* state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's public identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE public identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
break beforedoctypepublicidentifierloop;
// continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* public identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE public identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
continue stateloop;
case '>':
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Expected a public identifier but the doctype ended.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:
doctypepublicidentifierdoublequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* DOCTYPE public identifier state.
*/
publicIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
break doctypepublicidentifierdoublequotedloop;
// continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in public identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
longStrBufToString(), null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* public identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE public identifier
* (double-quoted) state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_PUBLIC_IDENTIFIER:
afterdoctypepublicidentifierloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE public identifier state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's system identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
break afterdoctypepublicidentifierloop;
// continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* system identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, null, false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:
doctypesystemidentifierdoublequotedloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '"':
/*
* U+0022 QUOTATION MARK (") Switch to the after
* DOCTYPE system identifier state.
*/
systemIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in system identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, longStrBufToString(),
true);
/*
* Switch to the data state.
*
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* system identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE system identifier
* (double-quoted) state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case AFTER_DOCTYPE_SYSTEM_IDENTIFIER:
afterdoctypesystemidentifierloop: for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the after DOCTYPE system identifier state.
*/
continue;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the current
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, systemIdentifier,
false);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Switch to the bogus DOCTYPE state. (This does
* not set the DOCTYPE token's force-quirks flag
* to on.)
*/
bogusDoctypeWithoutQuirks();
state = Tokenizer.BOGUS_DOCTYPE;
break afterdoctypesystemidentifierloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BOGUS_DOCTYPE:
for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit that
* DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, systemIdentifier,
forceQuirks);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Stay in the bogus DOCTYPE
* state.
*/
continue;
}
}
// XXX reorder point
case DOCTYPE_YSTEM:
doctypeystemloop: for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Otherwise, if the next six characters are a
* case-insensitive match for the word "SYSTEM", then
* consume those characters and switch to the before
* DOCTYPE system identifier state.
*/
if (index < 5) { // YSTEM.length
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != Tokenizer.YSTEM[index]) {
bogusDoctype();
state = Tokenizer.BOGUS_DOCTYPE;
reconsume = true;
continue stateloop;
}
index++;
continue stateloop;
} else {
state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;
reconsume = true;
break doctypeystemloop;
// continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:
beforedoctypesystemidentifierloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE FEED
* (LF) U+000C FORM FEED (FF) U+0020 SPACE Stay
* in the before DOCTYPE system identifier
* state.
*/
continue;
case '"':
/*
* U+0022 QUOTATION MARK (") Set the DOCTYPE
* token's system identifier to the empty string
* (not missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (double-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
continue stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Set the DOCTYPE token's
* system identifier to the empty string (not
* missing),
*/
clearLongStrBufForNextState();
/*
* then switch to the DOCTYPE system identifier
* (single-quoted) state.
*/
state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
break beforedoctypesystemidentifierloop;
// continue stateloop;
case '>':
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Expected a system identifier but the doctype ended.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName, null, null,
true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
bogusDoctype();
/*
* Set the DOCTYPE token's force-quirks flag to
* on.
*/
// done by bogusDoctype();
/*
* Switch to the bogus DOCTYPE state.
*/
state = Tokenizer.BOGUS_DOCTYPE;
continue stateloop;
}
}
// FALLTHRU DON'T REORDER
case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* DOCTYPE system identifier state.
*/
systemIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in system identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
publicIdentifier, longStrBufToString(),
true);
/*
* Switch to the data state.
*
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* system identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE system identifier
* (double-quoted) state.
*/
continue;
}
}
// XXX reorder point
case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:
for (;;) {
c = read();
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* DOCTYPE public identifier state.
*/
publicIdentifier = longStrBufToString();
state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Parse error.
*/
err("\u201C>\u201D in public identifier.");
/*
* Set the DOCTYPE token's force-quirks flag to
* on. Emit that DOCTYPE token.
*/
tokenHandler.doctype(doctypeName,
longStrBufToString(), null, true);
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current DOCTYPE token's
* public identifier.
*/
appendLongStrBuf(c);
/*
* Stay in the DOCTYPE public identifier
* (single-quoted) state.
*/
continue;
}
}
// XXX reorder point
case CDATA_START:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
if (index < 6) { // CDATA_LSQB.length
if (c == Tokenizer.CDATA_LSQB[index]) {
appendLongStrBuf(c);
} else {
err("Bogus comment.");
state = Tokenizer.BOGUS_COMMENT;
reconsume = true;
continue stateloop;
}
index++;
continue;
} else {
cstart = pos; // start coalescing
state = Tokenizer.CDATA_SECTION;
reconsume = true;
break; // FALL THROUGH continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_SECTION:
cdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case ']':
flushChars();
state = Tokenizer.CDATA_RSQB;
break cdataloop; // FALL THROUGH
default:
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_RSQB:
cdatarsqb: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case ']':
state = Tokenizer.CDATA_RSQB_RSQB;
break cdatarsqb;
default:
tokenHandler.characters(Tokenizer.RSQB_RSQB, 0,
1);
cstart = pos;
state = Tokenizer.CDATA_SECTION;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CDATA_RSQB_RSQB:
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '>':
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
default:
tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2);
cstart = pos;
state = Tokenizer.CDATA_SECTION;
reconsume = true;
continue stateloop;
}
// XXX reorder point
case ATTRIBUTE_VALUE_SINGLE_QUOTED:
attributevaluesinglequotedloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
/*
* Consume the next input character:
*/
switch (c) {
case '\u0000':
break stateloop;
case '\'':
/*
* U+0027 APOSTROPHE (') Switch to the after
* attribute value (quoted) state.
*/
addAttributeWithValue();
state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED;
continue stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) Switch to the character
* reference in attribute value state, with the +
* additional allowed character being U+0027
* APOSTROPHE (').
*/
detachLongStrBuf();
clearStrBufAndAppendCurrentC();
additional = '\'';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
break attributevaluesinglequotedloop;
// continue stateloop;
default:
/*
* Anything else Append the current input
* character to the current attribute's value.
*/
appendLongStrBuf(c);
/*
* Stay in the attribute value (double-quoted)
* state.
*/
continue;
}
}
// FALLTHRU DON'T REORDER
case CONSUME_CHARACTER_REFERENCE:
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Unlike the definition is the spec, this state does not
* return a value and never requires the caller to
* backtrack. This state takes care of emitting characters
* or appending to the current attribute value. It also
* takes care of that in the case when consuming the
* character reference fails.
*/
/*
* This section defines how to consume a character
* reference. This definition is used when parsing character
* references in text and in attributes.
*
* The behavior depends on the identity of the next
* character (the one immediately after the U+0026 AMPERSAND
* character):
*/
switch (c) {
case ' ':
case '\t':
case '\n':
case '\u000C':
case '<':
case '&':
emitOrAppendStrBuf(returnState);
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
case '#':
/*
* U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER
* SIGN.
*/
appendStrBuf('#');
state = Tokenizer.CONSUME_NCR;
continue stateloop;
default:
if (c == additional) {
emitOrAppendStrBuf(returnState);
state = returnState;
reconsume = true;
continue stateloop;
}
entCol = -1;
lo = 0;
hi = (NamedCharacters.NAMES.length - 1);
candidate = -1;
strBufMark = 0;
state = Tokenizer.CHARACTER_REFERENCE_LOOP;
reconsume = true;
// FALL THROUGH continue stateloop;
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case CHARACTER_REFERENCE_LOOP:
outer: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
if (c == '\u0000') {
break stateloop;
}
entCol++;
/*
* Anything else Consume the maximum number of
* characters possible, with the consumed characters
* case-sensitively matching one of the identifiers in
* the first column of the named character references
* table.
*/
hiloop: for (;;) {
if (hi == -1) {
break hiloop;
}
if (entCol == NamedCharacters.NAMES[hi].length) {
break hiloop;
}
if (entCol > NamedCharacters.NAMES[hi].length) {
break outer;
} else if (c < NamedCharacters.NAMES[hi][entCol]) {
hi--;
} else {
break hiloop;
}
}
loloop: for (;;) {
if (hi < lo) {
break outer;
}
if (entCol == NamedCharacters.NAMES[lo].length) {
candidate = lo;
strBufMark = strBufLen;
lo++;
} else if (entCol > NamedCharacters.NAMES[lo].length) {
break outer;
} else if (c > NamedCharacters.NAMES[lo][entCol]) {
lo++;
} else {
break loloop;
}
}
if (hi < lo) {
break outer;
}
appendStrBuf(c);
continue;
}
// TODO warn about apos (IE) and TRADE (Opera)
if (candidate == -1) {
/*
* If no match can be made, then this is a parse error.
*/
err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
char[] candidateArr = NamedCharacters.NAMES[candidate];
if (candidateArr[candidateArr.length - 1] != ';') {
/*
* If the last character matched is not a U+003B
* SEMICOLON (;), there is a parse error.
*/
err("Entity reference was not terminated by a semicolon.");
if ((returnState & (~1)) != 0) {
/*
* If the entity is being consumed as part of an
* attribute, and the last character matched is
* not a U+003B SEMICOLON (;),
*/
char ch;
if (strBufMark == strBufLen) {
ch = c;
} else {
// if (strBufOffset != -1) {
// ch = buf[strBufOffset + strBufMark];
// } else {
ch = strBuf[strBufMark];
// }
}
if ((ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')) {
/*
* and the next character is in the range
* U+0030 DIGIT ZERO to U+0039 DIGIT NINE,
* U+0041 LATIN CAPITAL LETTER A to U+005A
* LATIN CAPITAL LETTER Z, or U+0061 LATIN
* SMALL LETTER A to U+007A LATIN SMALL
* LETTER Z, then, for historical reasons,
* all the characters that were matched
* after the U+0026 AMPERSAND (&) must be
* unconsumed, and nothing is returned.
*/
appendStrBufToLongStrBuf();
state = returnState;
reconsume = true;
continue stateloop;
}
}
}
/*
* Otherwise, return a character token for the character
* corresponding to the entity name (as given by the
* second column of the named character references
* table).
*/
char[] val = NamedCharacters.VALUES[candidate];
emitOrAppend(val, returnState);
// this is so complicated!
if (strBufMark < strBufLen) {
if (strBufOffset != -1) {
if ((returnState & (~1)) != 0) {
for (int i = strBufMark; i < strBufLen; i++) {
appendLongStrBuf(buf[strBufOffset + i]);
}
} else {
tokenHandler.characters(buf, strBufOffset
+ strBufMark, strBufLen
- strBufMark);
}
} else {
if ((returnState & (~1)) != 0) {
for (int i = strBufMark; i < strBufLen; i++) {
appendLongStrBuf(strBuf[i]);
}
} else {
tokenHandler.characters(strBuf, strBufMark,
strBufLen - strBufMark);
}
}
}
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
/*
* If the markup contains I'm ¬it; I tell you, the
* entity is parsed as "not", as in, I'm ¬it; I tell
* you. But if the markup was I'm ∉ I tell you,
* the entity would be parsed as "notin;", resulting in
* I'm ∉ I tell you.
*/
}
// XXX reorder point
case CONSUME_NCR:
c = read();
prevValue = -1;
value = 0;
seenDigits = false;
/*
* The behavior further depends on the character after the
* U+0023 NUMBER SIGN:
*/
switch (c) {
case '\u0000':
break stateloop;
case 'x':
case 'X':
/*
* U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL
* LETTER X Consume the X.
*
* Follow the steps below, but using the range of
* characters U+0030 DIGIT ZERO through to U+0039
* DIGIT NINE, U+0061 LATIN SMALL LETTER A through
* to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN
* CAPITAL LETTER A, through to U+0046 LATIN CAPITAL
* LETTER F (in other words, 0-9, A-F, a-f).
*
* When it comes to interpreting the number,
* interpret it as a hexadecimal number.
*/
appendStrBuf(c);
state = Tokenizer.HEX_NCR_LOOP;
continue stateloop;
default:
/*
* Anything else Follow the steps below, but using
* the range of characters U+0030 DIGIT ZERO through
* to U+0039 DIGIT NINE (i.e. just 0-9).
*
* When it comes to interpreting the number,
* interpret it as a decimal number.
*/
state = Tokenizer.DECIMAL_NRC_LOOP;
reconsume = true;
// FALL THROUGH continue stateloop;
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case DECIMAL_NRC_LOOP:
decimalloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
if (c == '\u0000') {
break stateloop;
}
// Deal with overflow gracefully
if (value < prevValue) {
value = 0x110000; // Value above Unicode range but
// within int
// range
}
prevValue = value;
/*
* Consume as many characters as match the range of
* characters given above.
*/
if (c >= '0' && c <= '9') {
seenDigits = true;
value *= 10;
value += c - '0';
continue;
} else if (c == ';') {
if (seenDigits) {
state = Tokenizer.HANDLE_NCR_VALUE;
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
// FALL THROUGH continue stateloop;
break decimalloop;
} else {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
appendStrBuf(';');
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
state = returnState;
continue stateloop;
}
} else {
/*
* If no characters match the range, then don't
* consume any characters (and unconsume the U+0023
* NUMBER SIGN character and, if appropriate, the X
* character). This is a parse error; nothing is
* returned.
*
* Otherwise, if the next character is a U+003B
* SEMICOLON, consume that too. If it isn't, there
* is a parse error.
*/
if (!seenDigits) {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
err("Character reference was not terminated by a semicolon.");
state = Tokenizer.HANDLE_NCR_VALUE;
reconsume = true;
if ((returnState & (~1)) == 0) {
cstart = pos;
}
// FALL THROUGH continue stateloop;
break decimalloop;
}
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case HANDLE_NCR_VALUE:
// WARNING previous state sets reconsume
// XXX inline this case if the method size can take it
handleNcrValue(returnState);
state = returnState;
continue stateloop;
// XXX reorder point
case HEX_NCR_LOOP:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
// Deal with overflow gracefully
if (value < prevValue) {
value = 0x110000; // Value above Unicode range but
// within int
// range
}
prevValue = value;
/*
* Consume as many characters as match the range of
* characters given above.
*/
if (c >= '0' && c <= '9') {
seenDigits = true;
value *= 16;
value += c - '0';
continue;
} else if (c >= 'A' && c <= 'F') {
seenDigits = true;
value *= 16;
value += c - 'A' + 10;
continue;
} else if (c >= 'a' && c <= 'f') {
seenDigits = true;
value *= 16;
value += c - 'a' + 10;
continue;
} else if (c == ';') {
if (seenDigits) {
state = Tokenizer.HANDLE_NCR_VALUE;
cstart = pos + 1;
continue stateloop;
} else {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
appendStrBuf(';');
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos + 1;
}
state = returnState;
continue stateloop;
}
} else {
/*
* If no characters match the range, then don't
* consume any characters (and unconsume the U+0023
* NUMBER SIGN character and, if appropriate, the X
* character). This is a parse error; nothing is
* returned.
*
* Otherwise, if the next character is a U+003B
* SEMICOLON, consume that too. If it isn't, there
* is a parse error.
*/
if (!seenDigits) {
err("No digits after \u201C" + strBufToString()
+ "\u201D.");
emitOrAppendStrBuf(returnState);
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = returnState;
reconsume = true;
continue stateloop;
} else {
err("Character reference was not terminated by a semicolon.");
if ((returnState & (~1)) == 0) {
cstart = pos;
}
state = Tokenizer.HANDLE_NCR_VALUE;
reconsume = true;
continue stateloop;
}
}
}
// XXX reorder point
case PLAINTEXT:
plaintextloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// XXX reorder point
case CDATA:
cdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
returnState = state;
state = Tokenizer.TAG_OPEN_NON_PCDATA;
break cdataloop; // FALL THRU continue
// stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case TAG_OPEN_NON_PCDATA:
tagopennonpcdataloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '!':
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
cstart = pos;
state = Tokenizer.ESCAPE_EXCLAMATION;
break tagopennonpcdataloop; // FALL THRU
// continue
// stateloop;
case '/':
/*
* If the content model flag is set to the
* RCDATA or CDATA states Consume the next input
* character.
*/
if (contentModelElement != null) {
/*
* If it is a U+002F SOLIDUS (/) character,
* switch to the close tag open state.
*/
index = 0;
clearStrBufForNextState();
state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA;
continue stateloop;
} // else fall through
default:
/*
* Otherwise, emit a U+003C LESS-THAN SIGN
* character token
*/
tokenHandler.characters(Tokenizer.LT_GT, 0, 1);
/*
* and reconsume the current input character in
* the data state.
*/
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_EXCLAMATION:
escapeexclamationloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN;
break escapeexclamationloop; // FALL THRU
// continue
// stateloop;
default:
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_EXCLAMATION_HYPHEN:
escapeexclamationhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN_HYPHEN;
break escapeexclamationhyphenloop;
// continue stateloop;
default:
state = returnState;
reconsume = true;
continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_HYPHEN_HYPHEN:
escapehyphenhyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
continue;
case '>':
state = returnState;
continue stateloop;
default:
state = Tokenizer.ESCAPE;
break escapehyphenhyphenloop;
// continue stateloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE:
escapeloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN;
break escapeloop; // FALL THRU continue
// stateloop;
default:
continue escapeloop;
}
}
// WARNING FALLTHRU CASE TRANSITION: DON'T REORDER
case ESCAPE_HYPHEN:
escapehyphenloop: for (;;) {
c = read();
switch (c) {
case '\u0000':
break stateloop;
case '-':
state = Tokenizer.ESCAPE_HYPHEN_HYPHEN;
continue stateloop;
default:
state = Tokenizer.ESCAPE;
continue stateloop;
}
}
// XXX reorder point
case CLOSE_TAG_OPEN_NOT_PCDATA:
for (;;) {
c = read();
if (c == '\u0000') {
break stateloop;
}
// ASSERT! when entering this state, set index to 0 and
// call clearStrBuf()
assert (contentModelElement != null);
/*
* If the content model flag is set to the RCDATA or
* CDATA states but no start tag token has ever been
* emitted by this instance of the tokenizer (fragment
* case), or, if the content model flag is set to the
* RCDATA or CDATA states and the next few characters do
* not match the tag name of the last start tag token
* emitted (case insensitively), or if they do but they
* are not immediately followed by one of the following
* characters: + U+0009 CHARACTER TABULATION + U+000A
* LINE FEED (LF) + + U+000C FORM FEED (FF) + U+0020
* SPACE + U+003E GREATER-THAN SIGN (>) + U+002F SOLIDUS
* (/) + EOF
*
* ...then emit a U+003C LESS-THAN SIGN character token,
* a U+002F SOLIDUS character token, and switch to the
* data state to process the next input character.
*/
// Let's implement the above without lookahead. strBuf
// holds
// characters that need to be emitted if looking for an
// end tag
// fails.
// Duplicating the relevant part of tag name state here
// as well.
if (index < contentModelElement.name.length()) {
char e = contentModelElement.name.charAt(index);
char folded = c;
if (c >= 'A' && c <= 'Z') {
folded += 0x20;
}
if (folded != e) {
if (index > 0
|| (folded >= 'a' && folded <= 'z')) {
// [NOCPP[
if (html4) {
if (ElementName.IFRAME != contentModelElement) {
err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)");
}
} else {
// ]NOCPP]
warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but this did not close the element.");
// [NOCPP[
}
// ]NOCPP]
}
tokenHandler.characters(Tokenizer.LT_SOLIDUS,
0, 2);
emitStrBuf();
cstart = pos;
state = returnState;
reconsume = true;
continue stateloop;
}
appendStrBuf(c);
index++;
continue;
} else {
endTag = true;
// XXX replace contentModelElement with different
// type
tagName = contentModelElement;
switch (c) {
case ' ':
case '\t':
case '\n':
case '\u000C':
/*
* U+0009 CHARACTER TABULATION U+000A LINE
* FEED (LF) U+000C FORM FEED (FF) U+0020
* SPACE Switch to the before attribute name
* state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
case '>':
/*
* U+003E GREATER-THAN SIGN (>) Emit the
* current tag token.
*/
state = emitCurrentTagToken(false);
if (shouldSuspend) {
break stateloop;
}
/*
* Switch to the data state.
*/
continue stateloop;
case '/':
/*
* U+002F SOLIDUS (/) Parse error unless
* this is a permitted slash.
*/
// never permitted here
err("Stray \u201C/\u201D in end tag.");
/*
* Switch to the before attribute name
* state.
*/
state = Tokenizer.BEFORE_ATTRIBUTE_NAME;
continue stateloop;
default:
if (html4) {
err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)");
} else {
warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA"
: "RCDATA")
+ " element \u201C"
+ contentModelElement
+ "\u201D contained the string \u201C</\u201D, but this did not close the element.");
}
tokenHandler.characters(
Tokenizer.LT_SOLIDUS, 0, 2);
emitStrBuf();
cstart = pos; // don't drop the character
state = returnState;
continue stateloop;
}
}
}
// XXX reorder point
case CLOSE_TAG_OPEN_PCDATA:
c = read();
if (c == '\u0000') {
break stateloop;
}
/*
* Otherwise, if the content model flag is set to the PCDATA
* state, or if the next few characters do match that tag
* name, consume the next input character:
*/
if (c >= 'A' && c <= 'Z') {
/*
* U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN
* CAPITAL LETTER Z Create a new end tag token,
*/
endTag = true;
/*
* set its tag name to the lowercase version of the
* input character (add 0x0020 to the character's code
* point),
*/
clearStrBufAndAppendForceWrite((char) (c + 0x20));
/*
* then switch to the tag name state. (Don't emit the
* token yet; further details will be filled in before
* it is emitted.)
*/
state = Tokenizer.TAG_NAME;
continue stateloop;
} else if (c >= 'a' && c <= 'z') {
/*
* U+0061 LATIN SMALL LETTER A through to U+007A LATIN
* SMALL LETTER Z Create a new end tag token,
*/
endTag = true;
/*
* set its tag name to the input character,
*/
clearStrBufAndAppendCurrentC();
/*
* then switch to the tag name state. (Don't emit the
* token yet; further details will be filled in before
* it is emitted.)
*/
state = Tokenizer.TAG_NAME;
continue stateloop;
} else if (c == '>') {
/* U+003E GREATER-THAN SIGN (>) Parse error. */
err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C<\u201D) or mistyped end tag.");
/*
* Switch to the data state.
*/
cstart = pos + 1;
state = Tokenizer.DATA;
continue stateloop;
} else {
/* Anything else Parse error. */
err("Garbage after \u201C</\u201D.");
/*
* Switch to the bogus comment state.
*/
clearLongStrBufAndAppendToComment(c);
state = Tokenizer.BOGUS_COMMENT;
continue stateloop;
}
// XXX reorder point
case RCDATA:
rcdataloop: for (;;) {
if (reconsume) {
reconsume = false;
} else {
c = read();
}
switch (c) {
case '\u0000':
break stateloop;
case '&':
/*
* U+0026 AMPERSAND (&) When the content model
* flag is set to one of the PCDATA or RCDATA
* states and the escape flag is false: switch
* to the character reference data state.
* Otherwise: treat it as per the "anything
* else" entry below.
*/
flushChars();
clearStrBufAndAppendCurrentC();
additional = '\u0000';
returnState = state;
state = Tokenizer.CONSUME_CHARACTER_REFERENCE;
continue stateloop;
case '<':
/*
* U+003C LESS-THAN SIGN (<) When the content
* model flag is set to the PCDATA state: switch
* to the tag open state. When the content model
* flag is set to either the RCDATA state or the
* CDATA state and the escape flag is false:
* switch to the tag open state. Otherwise:
* treat it as per the "anything else" entry
* below.
*/
flushChars();
resetAttributes();
returnState = state;
state = Tokenizer.TAG_OPEN_NON_PCDATA;
continue stateloop;
default:
/*
* Anything else Emit the input character as a
* character token.
*/
/*
* Stay in the data state.
*/
continue;
}
}
}
}
flushChars();
if (prev == '\r' && pos != end) {
pos--;
col--;
}
// Save locals
stateSave = state;
returnStateSave = returnState;
}
|
diff --git a/araqne-logdb/src/main/java/org/araqne/logdb/QueryParseException.java b/araqne-logdb/src/main/java/org/araqne/logdb/QueryParseException.java
index 5b956a72..cac95b43 100644
--- a/araqne-logdb/src/main/java/org/araqne/logdb/QueryParseException.java
+++ b/araqne-logdb/src/main/java/org/araqne/logdb/QueryParseException.java
@@ -1,93 +1,93 @@
/*
* Copyright 2013 Future Systems
*
* 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.araqne.logdb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class QueryParseException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String type;
private int offset;
private String note;
private Map<String, String> params;
private int offsetS;
private int offsetE;
private List<Integer> offsetList;
public QueryParseException(String type, int offset) {
this(type, offset, null);
}
public QueryParseException(String type, int offset, String note) {
this.type = type;
this.offset = offset;
this.note = note;
this.offsetS = -1;
this.offsetE = -1;
- this.params = null;
+ this.params = new HashMap<String, String>();
this.offsetList = new ArrayList<Integer>();
}
public QueryParseException(String type, int s, int e, Map<String, String> params) {
this.type = type;
this.offsetS = s;
this.offsetE = e;
this.params = (params == null) ? new HashMap<String, String>() : params;
this.offsetList = new ArrayList<Integer>();
}
public void addOffset(int offset) {
offsetList.add(offset);
}
public String getType() {
return type;
}
public int getOffset() {
return offset;
}
public int getStartOffset() {
return offsetS;
}
public int getEndOffset() {
return offsetE;
}
public Map<String, String> getParams() {
return params;
}
public List<Integer> getOffsets() {
return offsetList;
}
public boolean isDebugMode() {
return false;
}
@Override
public String getMessage() {
return "type=" + type + ", offset=" + offset + ", note=" + note;
}
}
| true | true | public QueryParseException(String type, int offset, String note) {
this.type = type;
this.offset = offset;
this.note = note;
this.offsetS = -1;
this.offsetE = -1;
this.params = null;
this.offsetList = new ArrayList<Integer>();
}
| public QueryParseException(String type, int offset, String note) {
this.type = type;
this.offset = offset;
this.note = note;
this.offsetS = -1;
this.offsetE = -1;
this.params = new HashMap<String, String>();
this.offsetList = new ArrayList<Integer>();
}
|
diff --git a/E-EYE-O_EntitiesJavaImpl/src/com/jtbdevelopment/e_eye_o/entities/impl/ObservationImpl.java b/E-EYE-O_EntitiesJavaImpl/src/com/jtbdevelopment/e_eye_o/entities/impl/ObservationImpl.java
index c238f2c..dcc4d76 100644
--- a/E-EYE-O_EntitiesJavaImpl/src/com/jtbdevelopment/e_eye_o/entities/impl/ObservationImpl.java
+++ b/E-EYE-O_EntitiesJavaImpl/src/com/jtbdevelopment/e_eye_o/entities/impl/ObservationImpl.java
@@ -1,137 +1,137 @@
package com.jtbdevelopment.e_eye_o.entities.impl;
import com.jtbdevelopment.e_eye_o.entities.AppUser;
import com.jtbdevelopment.e_eye_o.entities.AppUserOwnedObject;
import com.jtbdevelopment.e_eye_o.entities.Observation;
import com.jtbdevelopment.e_eye_o.entities.ObservationCategory;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Date: 11/4/12
* Time: 7:26 PM
*/
public class ObservationImpl extends AppUserOwnedObjectImpl implements Observation {
private String comment = "";
private LocalDateTime observationTimestamp = new LocalDateTime();
private AppUserOwnedObject observationSubject;
private boolean significant = false;
private Set<ObservationCategory> categories = new HashSet<>();
private boolean followUpNeeded = false;
private LocalDate followUpReminder;
private Observation followUpObservation;
ObservationImpl(final AppUser appUser) {
super(appUser);
}
@Override
public AppUserOwnedObject getObservationSubject() {
return observationSubject;
}
@Override
public void setObservationSubject(final AppUserOwnedObject observationSubject) {
this.observationSubject = observationSubject;
}
@Override
public LocalDateTime getObservationTimestamp() {
return observationTimestamp;
}
@Override
public void setObservationTimestamp(final LocalDateTime observationDate) {
this.observationTimestamp = observationDate;
}
@Override
public boolean isSignificant() {
return significant;
}
@Override
public void setSignificant(final boolean significant) {
this.significant = significant;
}
@Override
public boolean isFollowUpNeeded() {
return followUpNeeded;
}
@Override
public void setFollowUpNeeded(final boolean followUpNeeded) {
this.followUpNeeded = followUpNeeded;
}
@Override
public LocalDate getFollowUpReminder() {
return followUpReminder;
}
@Override
public void setFollowUpReminder(final LocalDate followUpReminder) {
this.followUpReminder = followUpReminder;
}
@Override
public Observation getFollowUpObservation() {
return followUpObservation;
}
@Override
public void setFollowUpObservation(final Observation followUpObservation) {
this.followUpObservation = followUpObservation;
}
@Override
public Set<ObservationCategory> getCategories() {
return Collections.unmodifiableSet(categories);
}
@Override
public void setCategories(final Set<ObservationCategory> categories) {
this.categories.clear();
this.categories.addAll(categories);
}
@Override
public void addCategory(final ObservationCategory observationCategory) {
categories.add(observationCategory);
}
@Override
public void addCategories(final Collection<ObservationCategory> observationCategories) {
categories.addAll(observationCategories);
}
@Override
public void removeCategory(final ObservationCategory observationCategory) {
categories.remove(observationCategory);
}
@Override
public String getComment() {
return comment;
}
@Override
public void setComment(final String comment) {
this.comment = comment;
}
@Override
public String getSummaryDescription() {
- return (observationSubject != null ? observationSubject.getSummaryDescription() : "?"
+ return ((observationSubject != null ? observationSubject.getSummaryDescription() : "?")
+ " "
+ observationTimestamp.toString("MMM dd")).trim();
}
}
| true | true | public String getSummaryDescription() {
return (observationSubject != null ? observationSubject.getSummaryDescription() : "?"
+ " "
+ observationTimestamp.toString("MMM dd")).trim();
}
| public String getSummaryDescription() {
return ((observationSubject != null ? observationSubject.getSummaryDescription() : "?")
+ " "
+ observationTimestamp.toString("MMM dd")).trim();
}
|
diff --git a/datasource-csv/src/main/java/org/obiba/magma/datasource/csv/support/BufferedReaderEolSupport.java b/datasource-csv/src/main/java/org/obiba/magma/datasource/csv/support/BufferedReaderEolSupport.java
index 25d7d9bd..0361753a 100644
--- a/datasource-csv/src/main/java/org/obiba/magma/datasource/csv/support/BufferedReaderEolSupport.java
+++ b/datasource-csv/src/main/java/org/obiba/magma/datasource/csv/support/BufferedReaderEolSupport.java
@@ -1,467 +1,468 @@
/*
* Copyright (c) 2013 OBiBa. 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.magma.datasource.csv.support;
import java.io.IOException;
import java.io.Reader;
import javax.annotation.Nullable;
/**
* Copy of BufferedReader that expose nextChar.
* End of line are not returned by readLine() but we can get the cursor position in the file with getNextCharPosition().
*/
@SuppressWarnings({ "OverlyLongMethod", "FieldCanBeLocal", "SynchronizeOnNonFinalField", "UnusedLabel",
"UnnecessaryLabelOnBreakStatement", "ParameterHidesMemberVariable", "StaticNonFinalField", "FieldMayBeFinal",
"MagicNumber", "PMD.NcssMethodCount" })
public class BufferedReaderEolSupport extends Reader {
private Reader in;
private char cb[];
private int nChars;
private int nextChar;
private static final int INVALIDATED = -2;
private static final int UNMARKED = -1;
private int markedChar = UNMARKED;
private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
/**
* If the next character is a line feed, skip it
*/
private boolean skipLF = false;
/**
* The skipLF flag when the mark was set
*/
private boolean markedSkipLF = false;
private static int defaultCharBufferSize = 8192;
private static int defaultExpectedLineLength = 80;
private long bufferOffset;
/**
* Creates a buffering character-input stream that uses an input buffer of the specified size.
*
* @param in A Reader
* @param sz Input-buffer size
* @throws IllegalArgumentException If sz is <= 0
*/
public BufferedReaderEolSupport(Reader in, int sz) {
super(in);
if(sz <= 0) throw new IllegalArgumentException("Buffer size <= 0");
this.in = in;
cb = new char[sz];
nextChar = nChars = 0;
}
/**
* Creates a buffering character-input stream that uses a default-sized
* input buffer.
*
* @param in A Reader
*/
public BufferedReaderEolSupport(Reader in) {
this(in, defaultCharBufferSize);
}
/**
* Checks to make sure that the stream has not been closed
*/
private void ensureOpen() throws IOException {
if(in == null) throw new IOException("Stream closed");
}
/**
* Fills the input buffer, taking the mark into account if it is valid.
*/
private void fill() throws IOException {
int dst;
if(markedChar <= UNMARKED) {
/* No mark */
dst = 0;
} else {
/* Marked */
int delta = nextChar - markedChar;
if(delta >= readAheadLimit) {
/* Gone past read-ahead limit: Invalidate mark */
markedChar = INVALIDATED;
readAheadLimit = 0;
dst = 0;
} else {
if(readAheadLimit <= cb.length) {
/* Shuffle in the current buffer */
System.arraycopy(cb, markedChar, cb, 0, delta);
markedChar = 0;
dst = delta;
} else {
/* Reallocate buffer to accommodate read-ahead limit */
char ncb[] = new char[readAheadLimit];
System.arraycopy(cb, markedChar, ncb, 0, delta);
cb = ncb;
markedChar = 0;
dst = delta;
}
nextChar = nChars = delta;
}
}
int n;
do {
n = in.read(cb, dst, cb.length - dst);
} while(n == 0);
if(n > 0) {
nChars = dst + n;
bufferOffset += nextChar;
nextChar = dst;
}
}
/**
* Reads a single character.
*
* @return The character read, as an integer in the range
* 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
* end of the stream has been reached
* @throws IOException If an I/O error occurs
*/
@Override
public int read() throws IOException {
synchronized(lock) {
ensureOpen();
for(; ; ) {
if(nextChar >= nChars) {
fill();
if(nextChar >= nChars) return -1;
}
if(skipLF) {
skipLF = false;
if(cb[nextChar] == '\n') {
nextChar++;
continue;
}
}
return cb[nextChar++];
}
}
}
/**
* Reads characters into a portion of an array, reading from the underlying
* stream if necessary.
*/
private int read1(char[] cbuf, int off, int len) throws IOException {
if(nextChar >= nChars) {
// If the requested length is at least as large as the buffer, and if there is no mark/reset activity,
// and if line feeds are not being skipped, do not bother to copy the characters into the local buffer.
// In this way buffered streams will cascade harmlessly.
if(len >= cb.length && markedChar <= UNMARKED && !skipLF) {
return in.read(cbuf, off, len);
}
fill();
}
if(nextChar >= nChars) return -1;
if(skipLF) {
skipLF = false;
if(cb[nextChar] == '\n') {
nextChar++;
if(nextChar >= nChars) fill();
if(nextChar >= nChars) return -1;
}
}
int n = Math.min(len, nChars - nextChar);
System.arraycopy(cb, nextChar, cbuf, off, n);
nextChar += n;
return n;
}
/**
* Reads characters into a portion of an array.
* <p/>
* <p> This method implements the general contract of the corresponding
* <code>{@link Reader#read(char[], int, int) read}</code> method of the
* <code>{@link Reader}</code> class. As an additional convenience, it
* attempts to read as many characters as possible by repeatedly invoking
* the <code>read</code> method of the underlying stream. This iterated
* <code>read</code> continues until one of the following conditions becomes
* true: <ul>
* <p/>
* <li> The specified number of characters have been read,
* <p/>
* <li> The <code>read</code> method of the underlying stream returns
* <code>-1</code>, indicating end-of-file, or
* <p/>
* <li> The <code>ready</code> method of the underlying stream
* returns <code>false</code>, indicating that further input requests
* would block.
* <p/>
* </ul> If the first <code>read</code> on the underlying stream returns
* <code>-1</code> to indicate end-of-file then this method returns
* <code>-1</code>. Otherwise this method returns the number of characters
* actually read.
* <p/>
* <p> Subclasses of this class are encouraged, but not required, to
* attempt to read as many characters as possible in the same fashion.
* <p/>
* <p> Ordinarily this method takes characters from this stream's character
* buffer, filling it from the underlying stream as necessary. If,
* however, the buffer is empty, the mark is not valid, and the requested
* length is at least as large as the buffer, then this method will read
* characters directly from the underlying stream into the given array.
* Thus redundant <code>BufferedReader</code>s will not copy data
* unnecessarily.
*
* @param cbuf Destination buffer
* @param off Offset at which to start storing characters
* @param len Maximum number of characters to read
* @return The number of characters read, or -1 if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
*/
@Override
public int read(char cbuf[], int off, int len) throws IOException {
synchronized(lock) {
ensureOpen();
if(off < 0 || off > cbuf.length || len < 0 || off + len > cbuf.length || off + len < 0) {
throw new IndexOutOfBoundsException();
}
if(len == 0) {
return 0;
}
int n = read1(cbuf, off, len);
if(n <= 0) return n;
while(n < len && in.ready()) {
int n1 = read1(cbuf, off + n, len - n);
if(n1 <= 0) break;
n += n1;
}
return n;
}
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
* @throws IOException If an I/O error occurs
* @see java.io.LineNumberReader#readLine()
*/
@Nullable
public String readLine() throws IOException {
StringBuffer s = null;
int startChar;
synchronized(lock) {
ensureOpen();
bufferLoop:
for(; ; ) {
if(nextChar >= nChars) fill();
if(nextChar >= nChars) { /* EOF */
if(s != null && s.length() > 0) return s.toString();
return null;
}
boolean eol = false;
char c = 0;
int i;
skipLF = false;
charLoop:
for(i = nextChar; i < nChars; i++) {
c = cb[i];
if(c == '\n' || c == '\r') {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if(eol) {
String str;
if(s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if(c == '\r') {
skipLF = true;
}
// Skip leftover '\n' or '\r', if necessary
if(nextChar >= nChars) fill();
while(nextChar < cb.length && (cb[nextChar] == '\n' || cb[nextChar] == '\r')) {
nextChar++;
+ if(nextChar >= nChars) fill();
}
return str;
}
if(s == null) s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
/**
* Skips characters.
*
* @param n The number of characters to skip
* @return The number of characters actually skipped
* @throws IllegalArgumentException If <code>n</code> is negative.
* @throws IOException If an I/O error occurs
*/
@Override
public long skip(long n) throws IOException {
if(n < 0L) {
throw new IllegalArgumentException("skip value is negative");
}
synchronized(lock) {
ensureOpen();
long r = n;
while(r > 0) {
if(nextChar >= nChars) fill();
if(nextChar >= nChars) /* EOF */ break;
if(skipLF) {
skipLF = false;
if(cb[nextChar] == '\n') {
nextChar++;
}
}
long d = nChars - nextChar;
if(r <= d) {
nextChar += r;
r = 0;
break;
} else {
r -= d;
nextChar = nChars;
}
}
return n - r;
}
}
/**
* Tells whether this stream is ready to be read. A buffered character
* stream is ready if the buffer is not empty, or if the underlying
* character stream is ready.
*
* @throws IOException If an I/O error occurs
*/
@Override
public boolean ready() throws IOException {
synchronized(lock) {
ensureOpen();
/*
* If newline needs to be skipped and the next char to be read
* is a newline character, then just skip it right away.
*/
if(skipLF) {
/* Note that in.ready() will return true if and only if the next
* read on the stream will not block.
*/
if(nextChar >= nChars && in.ready()) {
fill();
}
if(nextChar < nChars) {
if(cb[nextChar] == '\n') nextChar++;
skipLF = false;
}
}
return nextChar < nChars || in.ready();
}
}
/**
* Tells whether this stream supports the mark() operation, which it does.
*/
@Override
public boolean markSupported() {
return true;
}
/**
* Marks the present position in the stream. Subsequent calls to reset()
* will attempt to reposition the stream to this point.
*
* @param readAheadLimit Limit on the number of characters that may be
* read while still preserving the mark. An attempt
* to reset the stream after reading characters
* up to this limit or beyond may fail.
* A limit value larger than the size of the input
* buffer will cause a new buffer to be allocated
* whose size is no smaller than limit.
* Therefore large values should be used with care.
* @throws IllegalArgumentException If readAheadLimit is < 0
* @throws IOException If an I/O error occurs
*/
@Override
public void mark(int readAheadLimit) throws IOException {
if(readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
synchronized(lock) {
ensureOpen();
this.readAheadLimit = readAheadLimit;
markedChar = nextChar;
markedSkipLF = skipLF;
}
}
/**
* Resets the stream to the most recent mark.
*
* @throws IOException If the stream has never been marked,
* or if the mark has been invalidated
*/
@Override
public void reset() throws IOException {
synchronized(lock) {
ensureOpen();
if(markedChar < 0) throw new IOException(markedChar == INVALIDATED ? "Mark invalid" : "Stream not marked");
nextChar = markedChar;
skipLF = markedSkipLF;
}
}
@Override
public void close() throws IOException {
synchronized(lock) {
if(in == null) return;
in.close();
in = null;
cb = null;
}
}
public long getCursorPosition() {
return bufferOffset + nextChar;
}
}
| true | true | public String readLine() throws IOException {
StringBuffer s = null;
int startChar;
synchronized(lock) {
ensureOpen();
bufferLoop:
for(; ; ) {
if(nextChar >= nChars) fill();
if(nextChar >= nChars) { /* EOF */
if(s != null && s.length() > 0) return s.toString();
return null;
}
boolean eol = false;
char c = 0;
int i;
skipLF = false;
charLoop:
for(i = nextChar; i < nChars; i++) {
c = cb[i];
if(c == '\n' || c == '\r') {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if(eol) {
String str;
if(s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if(c == '\r') {
skipLF = true;
}
// Skip leftover '\n' or '\r', if necessary
if(nextChar >= nChars) fill();
while(nextChar < cb.length && (cb[nextChar] == '\n' || cb[nextChar] == '\r')) {
nextChar++;
}
return str;
}
if(s == null) s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
| public String readLine() throws IOException {
StringBuffer s = null;
int startChar;
synchronized(lock) {
ensureOpen();
bufferLoop:
for(; ; ) {
if(nextChar >= nChars) fill();
if(nextChar >= nChars) { /* EOF */
if(s != null && s.length() > 0) return s.toString();
return null;
}
boolean eol = false;
char c = 0;
int i;
skipLF = false;
charLoop:
for(i = nextChar; i < nChars; i++) {
c = cb[i];
if(c == '\n' || c == '\r') {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if(eol) {
String str;
if(s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if(c == '\r') {
skipLF = true;
}
// Skip leftover '\n' or '\r', if necessary
if(nextChar >= nChars) fill();
while(nextChar < cb.length && (cb[nextChar] == '\n' || cb[nextChar] == '\r')) {
nextChar++;
if(nextChar >= nChars) fill();
}
return str;
}
if(s == null) s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
|
diff --git a/alitheia/web-services/src/eu/sqooss/impl/service/web/services/datatypes/WSStoredProject.java b/alitheia/web-services/src/eu/sqooss/impl/service/web/services/datatypes/WSStoredProject.java
index 3abea542..c32fc291 100644
--- a/alitheia/web-services/src/eu/sqooss/impl/service/web/services/datatypes/WSStoredProject.java
+++ b/alitheia/web-services/src/eu/sqooss/impl/service/web/services/datatypes/WSStoredProject.java
@@ -1,288 +1,288 @@
/*
* This file is part of the Alitheia system, developed by the SQO-OSS
* consortium as part of the IST FP6 SQO-OSS project, number 033331.
*
* Copyright 2007-2008 by the SQO-OSS consortium members <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 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 eu.sqooss.impl.service.web.services.datatypes;
import java.util.List;
import java.util.Set;
import eu.sqooss.service.db.Developer;
import eu.sqooss.service.db.MailingList;
import eu.sqooss.service.db.StoredProject;
/**
* This class wraps the <code>eu.sqooss.service.db.StoredProject</code>.
*/
public class WSStoredProject {
private long id;
private String bugs;
private String contact;
private String mail;
private String name;
private String repository;
private String website;
private String developers;
private String mailingLists;
/**
* @return the bugs
*/
public String getBugs() {
return bugs;
}
/**
* @param bugs the bugs to set
*/
public void setBugs(String bugs) {
this.bugs = bugs;
}
/**
* @return the contact
*/
public String getContact() {
return contact;
}
/**
* @param contact the contact to set
*/
public void setContact(String contact) {
this.contact = contact;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the mail
*/
public String getMail() {
return mail;
}
/**
* @param mail the mail to set
*/
public void setMail(String mail) {
this.mail = mail;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the repository
*/
public String getRepository() {
return repository;
}
/**
* @param repository the repository to set
*/
public void setRepository(String repository) {
this.repository = repository;
}
/**
* @return the website
*/
public String getWebsite() {
return website;
}
/**
* @param website the website to set
*/
public void setWebsite(String website) {
this.website = website;
}
/**
* Returns the Ids of the developers that work on this project.
* <br/><br/>
* <b>Note:</b> Using an array of <code>long</code> as a result, instead
* of the <code>String</code> based workaround is currently impossible,
* because of a limitation in the used Axis version i.e. it triggers an
* exception when passing a <code>null<code> or an empty array field.
*
* @return The list of developer Ids.
*/
public String getDevelopers() {
return developers;
}
/**
* Sets the list of Ids of the developers that work on this project.
*
* @param ids the list of developer Ids
*/
public void setDevelopers(long[] ids) {
if (ids != null) {
developers = "";
for (long id: ids)
developers += id + ";";
}
}
/**
* Returns the Ids of the mailing lists associated with this project.
* <br/><br/>
* <b>Note:</b> Using an array of <code>long</code> as a result, instead
* of the <code>String</code> based workaround is currently impossible,
* because of a limitation in the used Axis version i.e. it triggers an
* exception when passing a <code>null<code> or an empty array field.
*
* @return The list of mailing list Ids.
*/
public String getMailingLists() {
return mailingLists;
}
/**
* Sets the list of mailing list Ids, which are associated with this
* project.
*
* @param ids the list of mailing list Ids
*/
public void setMailingLists(long[] ids) {
if (ids != null) {
mailingLists = "";
for (long id: ids)
mailingLists += id + ";";
}
}
/**
* The method creates a new <code>WSStoredProject</code> object
* from the existent DAO object.
* The method doesn't care of the db session.
*
* @param storedProject - DAO stored project object
*
* @return The new <code>WSStoredProject</code> object
*/
public static WSStoredProject getInstance(StoredProject storedProject) {
if (storedProject == null) return null;
try {
WSStoredProject wsStoredProject = new WSStoredProject();
wsStoredProject.setId(storedProject.getId());
wsStoredProject.setBugs(storedProject.getBtsUrl());
wsStoredProject.setContact(storedProject.getContactUrl());
wsStoredProject.setMail(storedProject.getMailUrl());
wsStoredProject.setName(storedProject.getName());
wsStoredProject.setRepository(storedProject.getScmUrl());
wsStoredProject.setWebsite(storedProject.getWebsiteUrl());
- List<Developer> developers = storedProject.getDevelopers();
+ Set<Developer> developers = storedProject.getDevelopers();
if ((developers != null) && (developers.size() > 0)) {
int index = 0;
long[] developerIds = new long[developers.size()];
for (Developer developer : developers)
developerIds[index++] = developer.getId();
wsStoredProject.setDevelopers(developerIds);
}
Set<MailingList> mailingLists = storedProject.getMailingLists();
if ((mailingLists != null) && (mailingLists.size() > 0)) {
int index = 0;
long[] mailingListIds = new long[mailingLists.size()];
for (MailingList mailingList : mailingLists)
mailingListIds[index++] = mailingList.getId();
wsStoredProject.setMailingLists(mailingListIds);
}
return wsStoredProject;
} catch (Exception e) {
return null;
}
}
/**
* The method returns an array containing
* all of the elements in the stored projects list.
* The list argument should contain DAO
* <code>StoredProject</code> objects.
* The method doesn't care of the db session.
*
* @param storedProjects - the stored projects list;
* the elements should be <code>StoredProject</code> objects
*
* @return - an array with <code>WSStoredProject</code> objects;
* if the list is null, contains different object type
* or the DAO can't be wrapped then the array is null
*/
public static WSStoredProject[] asArray(List<?> storedProjects) {
WSStoredProject[] result = null;
if (storedProjects != null) {
result = new WSStoredProject[storedProjects.size()];
StoredProject currentStoredProject;
WSStoredProject currentWSStoredProject;
for (int i = 0; i < result.length; i++) {
try {
currentStoredProject = (StoredProject) storedProjects.get(i);
} catch (ClassCastException e) {
return null;
}
currentWSStoredProject = WSStoredProject.getInstance(currentStoredProject);
if (currentWSStoredProject == null) return null;
result[i] = currentWSStoredProject;
}
}
return result;
}
}
//vi: ai nosi sw=4 ts=4 expandtab
| true | true | public static WSStoredProject getInstance(StoredProject storedProject) {
if (storedProject == null) return null;
try {
WSStoredProject wsStoredProject = new WSStoredProject();
wsStoredProject.setId(storedProject.getId());
wsStoredProject.setBugs(storedProject.getBtsUrl());
wsStoredProject.setContact(storedProject.getContactUrl());
wsStoredProject.setMail(storedProject.getMailUrl());
wsStoredProject.setName(storedProject.getName());
wsStoredProject.setRepository(storedProject.getScmUrl());
wsStoredProject.setWebsite(storedProject.getWebsiteUrl());
List<Developer> developers = storedProject.getDevelopers();
if ((developers != null) && (developers.size() > 0)) {
int index = 0;
long[] developerIds = new long[developers.size()];
for (Developer developer : developers)
developerIds[index++] = developer.getId();
wsStoredProject.setDevelopers(developerIds);
}
Set<MailingList> mailingLists = storedProject.getMailingLists();
if ((mailingLists != null) && (mailingLists.size() > 0)) {
int index = 0;
long[] mailingListIds = new long[mailingLists.size()];
for (MailingList mailingList : mailingLists)
mailingListIds[index++] = mailingList.getId();
wsStoredProject.setMailingLists(mailingListIds);
}
return wsStoredProject;
} catch (Exception e) {
return null;
}
}
| public static WSStoredProject getInstance(StoredProject storedProject) {
if (storedProject == null) return null;
try {
WSStoredProject wsStoredProject = new WSStoredProject();
wsStoredProject.setId(storedProject.getId());
wsStoredProject.setBugs(storedProject.getBtsUrl());
wsStoredProject.setContact(storedProject.getContactUrl());
wsStoredProject.setMail(storedProject.getMailUrl());
wsStoredProject.setName(storedProject.getName());
wsStoredProject.setRepository(storedProject.getScmUrl());
wsStoredProject.setWebsite(storedProject.getWebsiteUrl());
Set<Developer> developers = storedProject.getDevelopers();
if ((developers != null) && (developers.size() > 0)) {
int index = 0;
long[] developerIds = new long[developers.size()];
for (Developer developer : developers)
developerIds[index++] = developer.getId();
wsStoredProject.setDevelopers(developerIds);
}
Set<MailingList> mailingLists = storedProject.getMailingLists();
if ((mailingLists != null) && (mailingLists.size() > 0)) {
int index = 0;
long[] mailingListIds = new long[mailingLists.size()];
for (MailingList mailingList : mailingLists)
mailingListIds[index++] = mailingList.getId();
wsStoredProject.setMailingLists(mailingListIds);
}
return wsStoredProject;
} catch (Exception e) {
return null;
}
}
|
diff --git a/src/org/openmrs/module/reporting/common/ObjectUtil.java b/src/org/openmrs/module/reporting/common/ObjectUtil.java
index 4ae3a425..ec9d917c 100644
--- a/src/org/openmrs/module/reporting/common/ObjectUtil.java
+++ b/src/org/openmrs/module/reporting/common/ObjectUtil.java
@@ -1,362 +1,365 @@
package org.openmrs.module.reporting.common;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.OpenmrsData;
import org.openmrs.OpenmrsMetadata;
import org.openmrs.PersonName;
import org.openmrs.ProgramWorkflow;
import org.openmrs.ProgramWorkflowState;
import org.openmrs.User;
import org.openmrs.api.context.Context;
import org.openmrs.util.OpenmrsUtil;
/**
* Generically useful utility class for working with Objects
*/
public class ObjectUtil {
protected static Log log = LogFactory.getLog(ObjectUtil.class);
/**
* Returns a String representation of the passed Map
*/
public static String toString(Map<?, ?> m, String keyValueSeparator, String entrySeparator) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<?, ?> e : m.entrySet()) {
if (sb.length() > 0) {
sb.append(entrySeparator);
}
sb.append(e.getKey() + keyValueSeparator + e.getValue());
}
return sb.toString();
}
/**
* Returns a String representation of the passed Map
*/
public static String toString(Map<?, ?> m, String sep) {
return toString(m, " -> ", sep);
}
/**
* Returns a String representation of the passed Object[]
*/
public static String toString(String separator, Object...elements) {
StringBuffer sb = new StringBuffer();
for (Object o : elements) {
if (notNull(o)) {
if (sb.length() > 0) {
sb.append(separator);
}
sb.append(o.toString());
}
}
return sb.toString();
}
/**
* Returns true if object is null or empty String
*/
public static boolean isNull(Object o) {
return o == null || o.equals("");
}
/**
* Returns true if object is not null and not empty string
*/
public static boolean notNull(Object o) {
return !isNull(o);
}
/**
* Returns the passed object, if not null, or replacement otherwise
*/
public static <T extends Object> T nvl(T o, T replacement) {
return (isNull(o) ? replacement : o);
}
/**
* Returns toString on the passed object if not null, or on replacement otherwise
*/
public static String nvlStr(Object o, Object replacement) {
return (isNull(o) ? nvl(replacement, "").toString() : o.toString());
}
/**
* Checks whether the testIfNull parameter is null, if so returns valueIfNull, otherwise returns valueIfNotNull
*/
public static <T extends Object> T decode(Object testIfNull, T valueIfNull, T valueIfNotNull) {
return (isNull(testIfNull) ? valueIfNull : valueIfNotNull);
}
/**
* Checks whether the testIfNull parameter is null, if so returns valueIfNull as String, otherwise returns valueIfNotNull as String
*/
public static String decodeStr(Object testIfNull, Object valueIfNull, Object valueIfNotNull) {
return (isNull(testIfNull) ? nvlStr(valueIfNull, "") : nvlStr(valueIfNotNull, ""));
}
/**
* Checks whether two objects are equal. This is null-safe and considers null and empty string to be equal
*/
public static boolean areEqual(Object o1, Object o2) {
Object obj1 = nvl(o1, "");
Object obj2 = nvl(o2, "");
return obj1.equals(obj2);
}
/**
* @return a null safe comparison between objects
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static int nullSafeCompare(Object o1, Object o2) {
if (o1 == null) {
return (o2 == null ? 0 : -1);
}
else if (o2 == null) {
return 1;
}
Comparable c1 = (o1 instanceof Comparable ? (Comparable) o1 : o1.toString());
Comparable c2 = (o2 instanceof Comparable ? (Comparable) o2 : o2.toString());
return c1.compareTo(c2);
}
/**
* Checks whether two objects have equal toString representations.
* This is null-safe and considers null and empty string to be equal
*/
public static boolean areEqualStr(Object o1, Object o2) {
String obj1 = nvlStr(o1, "");
String obj2 = nvlStr(o2, "");
return obj1.equals(obj2);
}
/**
* Checks whether o1 is equal to any of the objects in the passed array o2
*/
public static boolean equalToAny(Object o1, Object...o2) {
if (o1 != null && o2 != null) {
for (Object o : o2) {
if (o1.equals(o)) {
return true;
}
}
}
return false;
}
/**
* Returns the first non-null value in the passed array
*/
public static <T extends Object> T coalesce(T...tests) {
if (tests != null) {
for (int i=0; i<tests.length; i++) {
if (notNull(tests[i])) {
return tests[i];
}
}
}
return null;
}
/**
* Returns true if any value in the passed array is non-null
*/
public static boolean anyNotNull(Object...tests) {
return coalesce(tests) != null;
}
/**
* Returns the number of non-null objects in the passed array
*/
public static int numNotNull(Object...tests) {
int count=0;
if (tests != null) {
for (int i=0; i<tests.length; i++) {
if (notNull(tests[i])) {
count++;
}
}
}
return count;
}
/**
* Returns true if the passed collection contains any String in the passed String[]
*/
public static boolean containsAny(Collection<String> c, String...toCheck) {
if (c != null) {
for (String s : toCheck) {
if (c.contains(s)) {
return true;
}
}
}
return false;
}
/**
* Returns true if the passed collection contains all Strings in the passed String[]
*/
public static boolean containsAll(Collection<String> c, String...toCheck) {
if (c != null) {
for (String s : toCheck) {
if (!c.contains(s)) {
return false;
}
}
return true;
}
return false;
}
/**
* Returns a camelCase representation of the passed String
*/
public static String toCamelCase(String s) {
StringBuilder sb = new StringBuilder();
boolean nextUpper = false;
for (char c : s.toCharArray()) {
if (Character.isWhitespace(c)) {
nextUpper = true;
}
else {
if (Character.isLetterOrDigit(c)) {
sb.append((nextUpper ? Character.toUpperCase(c) : Character.toLowerCase(c)));
nextUpper = false;
}
}
}
return sb.toString();
}
/**
* Utility method to add an Object to a List if another passed Object is not null
*/
public static <T> void addIfNotNull(Collection<T> listToAddTo, T itemToAddToList, Object objectToCheckIfNull) {
if (objectToCheckIfNull != null) {
listToAddTo.add(itemToAddToList);
}
}
/**
* Utility method to trim a string without knowing whether it needs trimming beforehand
*/
public static String trimStringIfNeeded(String value, Integer maxLength) {
if (maxLength != null && value.length() > maxLength) {
return value.substring(0, maxLength);
} else {
return value;
}
}
/**
* Utility method to verify a string's length without knowing whether it is null or not
*/
public static String verifyStringLength(String value, Integer maxLength) {
if (maxLength != null && value.length() > maxLength) {
throw new RuntimeException(
"Maximum width for column with value '"+value+"' has been exceeded by "+ (value.length()-maxLength)+" characters.");
} else {
return value;
}
}
/**
* @return a formatted version of the object suitable for display
*/
public static String format(Object o) {
return format(o, null);
}
/**
* @return a formatted version of the object suitable for display
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String format(Object o, String format) {
if (o == null) { return ""; }
if (o instanceof Date) {
- DateFormat df = decode(format, Context.getDateFormat(), new SimpleDateFormat(format));
+ DateFormat df = Context.getDateFormat();
+ if (ObjectUtil.notNull(format)) {
+ df = new SimpleDateFormat(format);
+ }
return df.format((Date)o);
}
if (o instanceof Map) {
return toString((Map)o, nvl(format, ","));
}
if (o instanceof Collection) {
return OpenmrsUtil.join((Collection)o, nvl(format, ","));
}
if (o instanceof Object[]) {
return toString(nvl(format, ","), (Object[])o);
}
if (o instanceof Number) {
if (notNull(format)) {
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
return nf.format((Number)o);
}
}
if (o instanceof OpenmrsMetadata) {
String name = ((OpenmrsMetadata) o).getName();
if (name == null) {
if (o instanceof ProgramWorkflow) {
name = ((ProgramWorkflow)o).getConcept().getDisplayString();
}
else if (o instanceof ProgramWorkflowState) {
name = ((ProgramWorkflowState)o).getConcept().getDisplayString();
}
}
return name;
}
if (o instanceof OpenmrsData) {
if (ObjectUtil.notNull(format)) {
String[] formatSplit = format.split("\\|");
String ret = formatSplit[0];
try {
int startIndex = ret.indexOf("{");
int endIndex = ret.indexOf("}", startIndex+1);
while (startIndex != -1 && endIndex != -1) {
String propertyName = ret.substring(startIndex+1, endIndex);
Object replacement = ReflectionUtil.getPropertyValue(o, propertyName);
String newFormat = (replacement != null && formatSplit.length > 1 ? formatSplit[1] : null);
replacement = ObjectUtil.format(replacement, newFormat);
ret = ret.replace("{"+propertyName+"}", nvlStr(replacement, ""));
startIndex = ret.indexOf("{");
endIndex = ret.indexOf("}", startIndex+1);
}
return ret;
}
catch (Exception e) {
log.warn("Unable to get property using converter with format: " + format, e);
}
}
}
return o.toString();
}
public static String getNameOfCurrentUser() {
return getNameOfUser(Context.getAuthenticatedUser());
}
public static String getNameOfUser(User user) {
if (user != null) {
PersonName pn = user.getPersonName();
if (pn != null) {
return pn.getFullName();
}
else {
if (user.getUsername() != null) {
return user.getUsername();
}
}
}
return "Unknown User";
}
}
| true | true | public static String format(Object o, String format) {
if (o == null) { return ""; }
if (o instanceof Date) {
DateFormat df = decode(format, Context.getDateFormat(), new SimpleDateFormat(format));
return df.format((Date)o);
}
if (o instanceof Map) {
return toString((Map)o, nvl(format, ","));
}
if (o instanceof Collection) {
return OpenmrsUtil.join((Collection)o, nvl(format, ","));
}
if (o instanceof Object[]) {
return toString(nvl(format, ","), (Object[])o);
}
if (o instanceof Number) {
if (notNull(format)) {
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
return nf.format((Number)o);
}
}
if (o instanceof OpenmrsMetadata) {
String name = ((OpenmrsMetadata) o).getName();
if (name == null) {
if (o instanceof ProgramWorkflow) {
name = ((ProgramWorkflow)o).getConcept().getDisplayString();
}
else if (o instanceof ProgramWorkflowState) {
name = ((ProgramWorkflowState)o).getConcept().getDisplayString();
}
}
return name;
}
if (o instanceof OpenmrsData) {
if (ObjectUtil.notNull(format)) {
String[] formatSplit = format.split("\\|");
String ret = formatSplit[0];
try {
int startIndex = ret.indexOf("{");
int endIndex = ret.indexOf("}", startIndex+1);
while (startIndex != -1 && endIndex != -1) {
String propertyName = ret.substring(startIndex+1, endIndex);
Object replacement = ReflectionUtil.getPropertyValue(o, propertyName);
String newFormat = (replacement != null && formatSplit.length > 1 ? formatSplit[1] : null);
replacement = ObjectUtil.format(replacement, newFormat);
ret = ret.replace("{"+propertyName+"}", nvlStr(replacement, ""));
startIndex = ret.indexOf("{");
endIndex = ret.indexOf("}", startIndex+1);
}
return ret;
}
catch (Exception e) {
log.warn("Unable to get property using converter with format: " + format, e);
}
}
}
return o.toString();
}
| public static String format(Object o, String format) {
if (o == null) { return ""; }
if (o instanceof Date) {
DateFormat df = Context.getDateFormat();
if (ObjectUtil.notNull(format)) {
df = new SimpleDateFormat(format);
}
return df.format((Date)o);
}
if (o instanceof Map) {
return toString((Map)o, nvl(format, ","));
}
if (o instanceof Collection) {
return OpenmrsUtil.join((Collection)o, nvl(format, ","));
}
if (o instanceof Object[]) {
return toString(nvl(format, ","), (Object[])o);
}
if (o instanceof Number) {
if (notNull(format)) {
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
return nf.format((Number)o);
}
}
if (o instanceof OpenmrsMetadata) {
String name = ((OpenmrsMetadata) o).getName();
if (name == null) {
if (o instanceof ProgramWorkflow) {
name = ((ProgramWorkflow)o).getConcept().getDisplayString();
}
else if (o instanceof ProgramWorkflowState) {
name = ((ProgramWorkflowState)o).getConcept().getDisplayString();
}
}
return name;
}
if (o instanceof OpenmrsData) {
if (ObjectUtil.notNull(format)) {
String[] formatSplit = format.split("\\|");
String ret = formatSplit[0];
try {
int startIndex = ret.indexOf("{");
int endIndex = ret.indexOf("}", startIndex+1);
while (startIndex != -1 && endIndex != -1) {
String propertyName = ret.substring(startIndex+1, endIndex);
Object replacement = ReflectionUtil.getPropertyValue(o, propertyName);
String newFormat = (replacement != null && formatSplit.length > 1 ? formatSplit[1] : null);
replacement = ObjectUtil.format(replacement, newFormat);
ret = ret.replace("{"+propertyName+"}", nvlStr(replacement, ""));
startIndex = ret.indexOf("{");
endIndex = ret.indexOf("}", startIndex+1);
}
return ret;
}
catch (Exception e) {
log.warn("Unable to get property using converter with format: " + format, e);
}
}
}
return o.toString();
}
|
diff --git a/plugins/org.eclipse.viatra2.emf.incquery.base/src/org/eclipse/viatra2/emf/incquery/base/core/NavigationHelperImpl.java b/plugins/org.eclipse.viatra2.emf.incquery.base/src/org/eclipse/viatra2/emf/incquery/base/core/NavigationHelperImpl.java
index 7d1c3c44..65832e16 100644
--- a/plugins/org.eclipse.viatra2.emf.incquery.base/src/org/eclipse/viatra2/emf/incquery/base/core/NavigationHelperImpl.java
+++ b/plugins/org.eclipse.viatra2.emf.incquery.base/src/org/eclipse/viatra2/emf/incquery/base/core/NavigationHelperImpl.java
@@ -1,695 +1,696 @@
/*******************************************************************************
* Copyright (c) 2010-2012, Istvan Rath and Daniel Varro
* 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:
* Tamas Szabo, Gabor Bergmann - initial API and implementation
*******************************************************************************/
package org.eclipse.viatra2.emf.incquery.base.core;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EStructuralFeature.Setting;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.viatra2.emf.incquery.base.api.DataTypeListener;
import org.eclipse.viatra2.emf.incquery.base.api.FeatureListener;
import org.eclipse.viatra2.emf.incquery.base.api.InstanceListener;
import org.eclipse.viatra2.emf.incquery.base.api.NavigationHelper;
import org.eclipse.viatra2.emf.incquery.base.comprehension.EMFModelComprehension;
import org.eclipse.viatra2.emf.incquery.base.exception.IncQueryBaseException;
public class NavigationHelperImpl implements NavigationHelper {
protected boolean inWildcardMode;
protected HashSet<EClass> directlyObservedClasses;
protected HashSet<EClass> allObservedClasses = null; // including subclasses
protected HashSet<EDataType> observedDataTypes;
protected HashSet<EStructuralFeature> observedFeatures;
protected Notifier notifier;
protected Set<Notifier> modelRoots;
private boolean expansionAllowed;
// protected NavigationHelperVisitor visitor;
protected NavigationHelperContentAdapter contentAdapter;
private Logger logger;
/**
* These global listeners will be called after updates.
*/
protected Set<Runnable> afterUpdateCallbacks;
private Map<InstanceListener, Collection<EClass>> instanceListeners;
private Map<FeatureListener, Collection<EStructuralFeature>> featureListeners;
private Map<DataTypeListener, Collection<EDataType>> dataTypeListeners;
/**
* Feature registration and model traversal is delayed while true
*/
protected boolean delayTraversals = false;
/**
* Classes to be registered once the coalescing period is over
*/
protected Set<EClass> delayedClasses;
/**
* EStructuralFeatures to be registered once the coalescing period is over
*/
protected Set<EStructuralFeature> delayedFeatures;
/**
* EDataTypes to be registered once the coalescing period is over
*/
protected Set<EDataType> delayedDataTypes;
private Set<EClass> noClass() { return Collections.emptySet(); };
private Set<EDataType> noDataType() { return Collections.emptySet(); };
private Set<EStructuralFeature> noFeature() { return Collections.emptySet(); };
<T> Set<T> setMinus(Set<T> a, Set<T> b) {
Set<T> result = new HashSet<T>(a);
result.removeAll(b);
return result;
}
<T extends EObject> Set<T> resolveAll(Set<T> a) {
Set<T> result = new HashSet<T>(a);
for (T t : a) {
if (t.eIsProxy())
result.add((T) EcoreUtil.resolve(t, (ResourceSet)null));
else
result.add(t);
}
return result;
}
/* (non-Javadoc)
* @see org.eclipse.viatra2.emf.incquery.base.api.NavigationHelper#isInWildcardMode()
*/
@Override
public boolean isInWildcardMode() {
return inWildcardMode;
}
// @Override
// public void setInWildcardMode(boolean newWildcardMode) {
// if (inWildcardMode && !newWildcardMode)
// throw new UnsupportedOperationException();
// if (!inWildcardMode && newWildcardMode) {
// this.inWildcardMode = true;
//
// this.allObservedClasses = null;
// this.directlyObservedClasses = null;
// this.observedDataTypes = null;
// this.observedFeatures = null;
//
// this.contentAdapter. // TODO lot of work because need to send proper notifications
// }
//
// }
public NavigationHelperImpl(Notifier emfRoot, boolean wildcardMode, Logger logger) throws IncQueryBaseException {
this.logger = logger;
assert(logger!=null);
if (!((emfRoot instanceof EObject) || (emfRoot instanceof Resource) || (emfRoot instanceof ResourceSet))) {
throw new IncQueryBaseException(IncQueryBaseException.INVALID_EMFROOT);
}
this.instanceListeners = new HashMap<InstanceListener, Collection<EClass>>();
this.featureListeners = new HashMap<FeatureListener, Collection<EStructuralFeature>>();
this.dataTypeListeners = new HashMap<DataTypeListener, Collection<EDataType>>();
this.directlyObservedClasses = new HashSet<EClass>();
this.observedFeatures = new HashSet<EStructuralFeature>();
this.observedDataTypes = new HashSet<EDataType>();
this.contentAdapter = new NavigationHelperContentAdapter(this);
// this.visitor = new NavigationHelperVisitor(this);
this.afterUpdateCallbacks = new HashSet<Runnable>();
this.notifier = emfRoot;
this.modelRoots = new HashSet<Notifier>();
this.expansionAllowed = notifier instanceof ResourceSet;
this.inWildcardMode = wildcardMode;
// if (this.navigationHelperType == NavigationHelperType.ALL) {
// visitor.visitModel(notifier, observedFeatures, observedClasses, observedDataTypes);
// }
expandToAdditionalRoot(emfRoot);
}
public NavigationHelperContentAdapter getContentAdapter() {
return contentAdapter;
}
public HashSet<EStructuralFeature> getObservedFeatures() {
return observedFeatures;
}
// public NavigationHelperVisitor getVisitor() {
// return visitor;
// }
@Override
public void dispose() {
for (Notifier root : modelRoots) {
root.eAdapters().remove(contentAdapter);
}
}
@Override
public Collection<Object> getDataTypeInstances(EDataType type) {
Map<Object, Integer> valMap = contentAdapter.dataTypeMap.get(type);
if (valMap != null) {
return Collections.unmodifiableSet(valMap.keySet());
}
else {
return Collections.emptySet();
}
}
@Override
public Collection<Setting> findByAttributeValue(Object value) {
Set<Setting> retSet = new HashSet<Setting>();
Map<EStructuralFeature, Set<EObject>> valMap = contentAdapter.featureMap.get(value);
if (valMap != null) {
for (Entry<EStructuralFeature, Set<EObject>> entry : valMap.entrySet()) {
for (EObject holder : entry.getValue()) {
retSet.add(new NavigationHelperSetting(entry.getKey(), holder, value));
}
}
}
return retSet;
}
@Override
public Collection<Setting> findByAttributeValue(Object value, Collection<EAttribute> attributes) {
Set<Setting> retSet = new HashSet<Setting>();
Map<EStructuralFeature, Set<EObject>> valMap = contentAdapter.featureMap.get(value);
if (valMap != null) {
for (EAttribute attr : attributes) {
if (valMap.get(attr) != null) {
for (EObject holder : valMap.get(attr)) {
retSet.add(new NavigationHelperSetting(attr, holder, value));
}
}
}
}
return retSet;
}
@Override
public Collection<EObject> findByAttributeValue(Object value, EAttribute attribute) {
Map<EStructuralFeature, Set<EObject>> valMap = contentAdapter.featureMap.get(value);
if (valMap == null || valMap.get(attribute) == null) {
return Collections.emptySet();
}
else {
return Collections.unmodifiableSet(valMap.get(attribute));
}
}
// @Override
// public Collection<Setting> findAllAttributeValuesByType(Class<?> clazz) {
// Set<Setting> retSet = new HashSet<Setting>();
//
// for (Object value : contentAdapter.featureMap.keySet()) {
// if (value.getClass().equals(clazz)) {
// for (EStructuralFeature attr : contentAdapter.featureMap.get(value).keySet()) {
// for (EObject holder : contentAdapter.featureMap.get(value).get(attr)) {
// retSet.add(new NavigationHelperSetting(attr, holder, value));
// }
// }
// }
// }
//
// return retSet;
// }
@Override
public Collection<Setting> getInverseReferences(EObject target) {
Set<Setting> retSet = new HashSet<Setting>();
Map<EStructuralFeature, Set<EObject>> valMap = contentAdapter.featureMap.get(target);
if (valMap != null) {
for (Entry<EStructuralFeature, Set<EObject>> entry : valMap.entrySet()) {
for (EObject source : entry.getValue()) {
retSet.add(new NavigationHelperSetting(entry.getKey(), target, source));
}
}
}
return retSet;
}
@Override
public Collection<Setting> getInverseReferences(EObject target, Collection<EReference> references) {
Set<Setting> retSet = new HashSet<Setting>();
Map<EStructuralFeature, Set<EObject>> valMap = contentAdapter.featureMap.get(target);
if (valMap != null) {
for (EReference ref : references) {
if (valMap.get(ref) != null) {
for (EObject source : valMap.get(ref)) {
retSet.add(new NavigationHelperSetting(ref, target, source));
}
}
}
}
return retSet;
}
@Override
public Collection<EObject> getInverseReferences(EObject target, EReference reference) {
Map<EStructuralFeature, Set<EObject>> valMap = contentAdapter.featureMap.get(target);
if (valMap == null || valMap.get(reference) == null) {
return Collections.emptySet();
}
else {
return Collections.unmodifiableSet(valMap.get(reference));
}
}
@Override
public Collection<EObject> getDirectInstances(EClass type) {
Set<EObject> valSet = contentAdapter.instanceMap.get(type);
if (valSet == null) {
return Collections.emptySet();
}
else {
return Collections.unmodifiableSet(valSet);
}
}
@Override
public Collection<EObject> getAllInstances(EClass type) {
Set<EObject> retSet = new HashSet<EObject>();
Set<EClass> valSet = contentAdapter.subTypeMap.get(type);
if (valSet != null) {
for (EClass c : valSet) {
final Set<EObject> instances = contentAdapter.instanceMap.get(c);
if (instances != null) retSet.addAll(instances);
}
}
final Set<EObject> instances = contentAdapter.instanceMap.get(type);
if (instances != null) retSet.addAll(instances);
return retSet;
}
@Override
public Collection<EObject> findByFeatureValue(Object value, EStructuralFeature feature) {
Set<EObject> retSet = new HashSet<EObject>();
Map<EStructuralFeature, Set<EObject>> valMap = contentAdapter.featureMap.get(value);
if (valMap != null && valMap.get(feature) != null) {
retSet.addAll(valMap.get(feature));
}
return retSet;
}
@Override
public Collection<EObject> getHoldersOfFeature(EStructuralFeature feature) {
if (contentAdapter.getReversedFeatureMap().get(feature) == null) {
return Collections.emptySet();
}
else {
return Collections.unmodifiableSet(contentAdapter.getReversedFeatureMap().get(feature));
}
}
@Override
public void registerInstanceListener(Collection<EClass> classes, InstanceListener listener) {
Collection<EClass> registered = this.instanceListeners.get(listener);
if (registered == null) {
registered = new HashSet<EClass>();
this.instanceListeners.put(listener, registered);
}
registered.addAll(classes);
}
@Override
public void unregisterInstanceListener(Collection<EClass> classes, InstanceListener listener) {
Collection<EClass> restriction = this.instanceListeners.get(listener);
if (restriction != null) {
restriction.removeAll(classes);
if (restriction.size() == 0) {
this.instanceListeners.remove(listener);
}
}
}
@Override
public void registerFeatureListener(Collection<EStructuralFeature> features, FeatureListener listener) {
Collection<EStructuralFeature> registered = this.featureListeners.get(listener);
if (registered == null) {
registered = new HashSet<EStructuralFeature>();
this.featureListeners.put(listener, registered);
}
registered.addAll(features);
}
@Override
public void unregisterFeatureListener(Collection<EStructuralFeature> features, FeatureListener listener) {
Collection<EStructuralFeature> restriction = this.featureListeners.get(listener);
if (restriction != null) {
restriction.removeAll(features);
if (restriction.size() == 0) {
this.featureListeners.remove(listener);
}
}
}
@Override
public void registerDataTypeListener(Collection<EDataType> types, DataTypeListener listener) {
Collection<EDataType> registered = this.dataTypeListeners.get(listener);
if (registered == null) {
registered = new HashSet<EDataType>();
this.dataTypeListeners.put(listener, registered);
}
registered.addAll(types);
}
@Override
public void unregisterDataTypeListener(Collection<EDataType> types, DataTypeListener listener) {
Collection<EDataType> restriction = this.dataTypeListeners.get(listener);
if (restriction != null) {
restriction.removeAll(types);
if (restriction.size() == 0) {
this.dataTypeListeners.remove(listener);
}
}
}
public Map<InstanceListener, Collection<EClass>> getInstanceListeners() {
return instanceListeners;
}
public Map<FeatureListener, Collection<EStructuralFeature>> getFeatureListeners() {
return featureListeners;
}
public Map<DataTypeListener, Collection<EDataType>> getDataTypeListeners() {
return dataTypeListeners;
}
/**
* @return the observedDataTypes
*/
public HashSet<EDataType> getObservedDataTypes() {
return observedDataTypes;
}
/**
* These runnables will be called after updates by the manipulationListener at its own discretion.
* Can be used e.g. to check delta monitors.
*/
@Override
public Set<Runnable> getAfterUpdateCallbacks() {
return afterUpdateCallbacks;
}
/**
* This will run after updates.
*/
// * If there are any such, updates are settled before they are run.
public void runAfterUpdateCallbacks() {
try {
if (!afterUpdateCallbacks.isEmpty()) {
//settle();
for (Runnable runnable : new ArrayList<Runnable>(afterUpdateCallbacks)) {
runnable.run();
}
}
} catch (Exception ex) {
logger.fatal(
"EMF-IncQuery Base encountered an error in delivering notifications about changes. " , ex);
//throw new IncQueryRuntimeException(IncQueryRuntimeException.EMF_MODEL_PROCESSING_ERROR, ex);
}
}
protected void considerForExpansion(EObject obj) {
if (expansionAllowed) {
Resource eResource = obj.eResource();
if (eResource != null && eResource.getResourceSet() == null) {
expandToAdditionalRoot(eResource);
}
}
}
protected void expandToAdditionalRoot(Notifier root) {
if (modelRoots.add(root)) {
root.eAdapters().add(contentAdapter);
}
}
/**
* @return the expansionAllowed
*/
public boolean isExpansionAllowed() {
return expansionAllowed;
}
/**
* @return the directlyObservedClasses
*/
public HashSet<EClass> getDirectlyObservedClasses() {
return directlyObservedClasses;
}
public boolean isObserved(EClass clazz) {
return inWildcardMode || getAllObservedClasses().contains(clazz);
}
/**
* not just the directly observed classes, but also their known subtypes
*/
public HashSet<EClass> getAllObservedClasses() {
if (allObservedClasses == null) {
allObservedClasses = new HashSet<EClass>();
for (EClass eClass : directlyObservedClasses) {
allObservedClasses.add(eClass);
final Set<EClass> subTypes = NavigationHelperContentAdapter.subTypeMap.get(eClass);
if (subTypes != null) {
allObservedClasses.addAll(subTypes);
}
}
}
return allObservedClasses;
}
@Override
public void registerEStructuralFeatures(Set<EStructuralFeature> features) {
if (inWildcardMode) throw new IllegalStateException();
if (features != null) {
features = resolveAll(features);
if (delayTraversals) {
delayedFeatures.addAll(features);
} else {
features = setMinus(features, observedFeatures);
observedFeatures.addAll(features);
final NavigationHelperVisitor visitor =
new NavigationHelperVisitor.TraversingVisitor(this, features, noClass(), noClass(), noDataType());
traverse(visitor);
}
}
}
@Override
public void unregisterEStructuralFeatures(Set<EStructuralFeature> features) {
if (inWildcardMode) throw new IllegalStateException();
if (features != null) {
features = resolveAll(features);
observedFeatures.removeAll(features);
delayedFeatures.removeAll(features);
for (EStructuralFeature f : features) {
for (Object key : contentAdapter.featureMap.keySet()) {
contentAdapter.featureMap.get(key).remove(f);
// TODO proper notification
}
}
}
}
@Override
public void registerEClasses(Set<EClass> classes) {
if (inWildcardMode) throw new IllegalStateException();
if (classes != null) {
classes = resolveAll(classes);
if (delayTraversals) {
delayedClasses.addAll(classes);
} else {
classes = setMinus(classes, directlyObservedClasses);
final HashSet<EClass> oldClasses = new HashSet<EClass>(directlyObservedClasses);
startObservingClasses(classes);
final NavigationHelperVisitor visitor =
new NavigationHelperVisitor.TraversingVisitor(this, noFeature(), classes, oldClasses, noDataType());
traverse(visitor);
}
}
}
/**
* @param classes
*/
protected void startObservingClasses(Set<EClass> classes) {
directlyObservedClasses.addAll(classes);
getAllObservedClasses().addAll(classes);
for (EClass eClass : classes) {
final Set<EClass> subTypes = NavigationHelperContentAdapter.subTypeMap.get(eClass);
if (subTypes != null) {
allObservedClasses.addAll(subTypes);
}
}
}
@Override
public void unregisterEClasses(Set<EClass> classes) {
if (inWildcardMode) throw new IllegalStateException();
if (classes != null) {
classes = resolveAll(classes);
directlyObservedClasses.removeAll(classes);
allObservedClasses = null;
delayedClasses.removeAll(classes);
for (EClass c : classes) {
contentAdapter.instanceMap.remove(c);
}
}
}
@Override
public void registerEDataTypes(Set<EDataType> dataTypes) {
if (inWildcardMode) throw new IllegalStateException();
if (dataTypes != null) {
dataTypes = resolveAll(dataTypes);
if (delayTraversals) {
delayedDataTypes.addAll(dataTypes);
} else {
dataTypes = setMinus(dataTypes, observedDataTypes);
observedDataTypes.addAll(dataTypes);
final NavigationHelperVisitor visitor =
new NavigationHelperVisitor.TraversingVisitor(this, noFeature(), noClass(), noClass(), dataTypes);
traverse(visitor);
}
}
}
@Override
public void unregisterEDataTypes(Set<EDataType> dataTypes) {
if (inWildcardMode) throw new IllegalStateException();
if (dataTypes != null) {
dataTypes = resolveAll(dataTypes);
observedDataTypes.removeAll(dataTypes);
delayedDataTypes.removeAll(dataTypes);
for (EDataType dt : dataTypes) {
contentAdapter.dataTypeMap.remove(dt);
}
}
}
@Override
public <V> V coalesceTraversals(Callable<V> callable) throws InvocationTargetException {
if(delayTraversals) { // reentrant case, no special action needed
V result = null;
try {
result = callable.call();
} catch (Exception e) {
throw new InvocationTargetException(e);
}
return result;
}
delayedClasses = new HashSet<EClass>();
delayedFeatures = new HashSet<EStructuralFeature>();
delayedDataTypes = new HashSet<EDataType>();
V result = null;
try {
try {
delayTraversals = true;
result = callable.call();
} finally {
delayTraversals = false;
delayedFeatures = setMinus(delayedFeatures, observedFeatures);
delayedClasses = setMinus(delayedClasses, directlyObservedClasses);
delayedDataTypes = setMinus(delayedDataTypes, observedDataTypes);
boolean classesWarrantTraversal = !setMinus(delayedClasses, getAllObservedClasses()).isEmpty();
if (!delayedClasses.isEmpty() || !delayedFeatures.isEmpty() || !delayedDataTypes.isEmpty()) {
final HashSet<EClass> oldClasses = new HashSet<EClass>(directlyObservedClasses);
startObservingClasses(delayedClasses);
observedFeatures.addAll(delayedFeatures);
observedDataTypes.addAll(delayedDataTypes);
// make copies and clean original accumulators, for the rare case that a coalesced
// traversal is invoked during visitation, e.g. by a derived feature implementation
final HashSet<EClass> toGatherClasses = new HashSet<EClass>(delayedClasses);
final HashSet<EStructuralFeature> toGatherFeatures = new HashSet<EStructuralFeature>(delayedFeatures);
final HashSet<EDataType> toGatherDataTypes = new HashSet<EDataType>(delayedDataTypes);
delayedFeatures.clear();
delayedClasses.clear();
delayedDataTypes.clear();
if (classesWarrantTraversal || !toGatherFeatures.isEmpty() || !toGatherDataTypes.isEmpty()) {
final NavigationHelperVisitor visitor =
new NavigationHelperVisitor.TraversingVisitor(this, toGatherFeatures, toGatherClasses, oldClasses, toGatherDataTypes);
traverse(visitor);
}
}
}
} catch (Exception e) {
+ getLogger().fatal("EMF-IncQuery Base encountered an error while traversing the EMF model to gather new information. " , e);
throw new InvocationTargetException(e);
}
return result;
}
private void traverse(final NavigationHelperVisitor visitor) {
for (Notifier root : modelRoots) {
EMFModelComprehension.visitModel(visitor, root);
}
runAfterUpdateCallbacks();
}
/**
* @return the logger
*/
public Logger getLogger() {
return logger;
}
}
| true | true | public <V> V coalesceTraversals(Callable<V> callable) throws InvocationTargetException {
if(delayTraversals) { // reentrant case, no special action needed
V result = null;
try {
result = callable.call();
} catch (Exception e) {
throw new InvocationTargetException(e);
}
return result;
}
delayedClasses = new HashSet<EClass>();
delayedFeatures = new HashSet<EStructuralFeature>();
delayedDataTypes = new HashSet<EDataType>();
V result = null;
try {
try {
delayTraversals = true;
result = callable.call();
} finally {
delayTraversals = false;
delayedFeatures = setMinus(delayedFeatures, observedFeatures);
delayedClasses = setMinus(delayedClasses, directlyObservedClasses);
delayedDataTypes = setMinus(delayedDataTypes, observedDataTypes);
boolean classesWarrantTraversal = !setMinus(delayedClasses, getAllObservedClasses()).isEmpty();
if (!delayedClasses.isEmpty() || !delayedFeatures.isEmpty() || !delayedDataTypes.isEmpty()) {
final HashSet<EClass> oldClasses = new HashSet<EClass>(directlyObservedClasses);
startObservingClasses(delayedClasses);
observedFeatures.addAll(delayedFeatures);
observedDataTypes.addAll(delayedDataTypes);
// make copies and clean original accumulators, for the rare case that a coalesced
// traversal is invoked during visitation, e.g. by a derived feature implementation
final HashSet<EClass> toGatherClasses = new HashSet<EClass>(delayedClasses);
final HashSet<EStructuralFeature> toGatherFeatures = new HashSet<EStructuralFeature>(delayedFeatures);
final HashSet<EDataType> toGatherDataTypes = new HashSet<EDataType>(delayedDataTypes);
delayedFeatures.clear();
delayedClasses.clear();
delayedDataTypes.clear();
if (classesWarrantTraversal || !toGatherFeatures.isEmpty() || !toGatherDataTypes.isEmpty()) {
final NavigationHelperVisitor visitor =
new NavigationHelperVisitor.TraversingVisitor(this, toGatherFeatures, toGatherClasses, oldClasses, toGatherDataTypes);
traverse(visitor);
}
}
}
} catch (Exception e) {
throw new InvocationTargetException(e);
}
return result;
}
| public <V> V coalesceTraversals(Callable<V> callable) throws InvocationTargetException {
if(delayTraversals) { // reentrant case, no special action needed
V result = null;
try {
result = callable.call();
} catch (Exception e) {
throw new InvocationTargetException(e);
}
return result;
}
delayedClasses = new HashSet<EClass>();
delayedFeatures = new HashSet<EStructuralFeature>();
delayedDataTypes = new HashSet<EDataType>();
V result = null;
try {
try {
delayTraversals = true;
result = callable.call();
} finally {
delayTraversals = false;
delayedFeatures = setMinus(delayedFeatures, observedFeatures);
delayedClasses = setMinus(delayedClasses, directlyObservedClasses);
delayedDataTypes = setMinus(delayedDataTypes, observedDataTypes);
boolean classesWarrantTraversal = !setMinus(delayedClasses, getAllObservedClasses()).isEmpty();
if (!delayedClasses.isEmpty() || !delayedFeatures.isEmpty() || !delayedDataTypes.isEmpty()) {
final HashSet<EClass> oldClasses = new HashSet<EClass>(directlyObservedClasses);
startObservingClasses(delayedClasses);
observedFeatures.addAll(delayedFeatures);
observedDataTypes.addAll(delayedDataTypes);
// make copies and clean original accumulators, for the rare case that a coalesced
// traversal is invoked during visitation, e.g. by a derived feature implementation
final HashSet<EClass> toGatherClasses = new HashSet<EClass>(delayedClasses);
final HashSet<EStructuralFeature> toGatherFeatures = new HashSet<EStructuralFeature>(delayedFeatures);
final HashSet<EDataType> toGatherDataTypes = new HashSet<EDataType>(delayedDataTypes);
delayedFeatures.clear();
delayedClasses.clear();
delayedDataTypes.clear();
if (classesWarrantTraversal || !toGatherFeatures.isEmpty() || !toGatherDataTypes.isEmpty()) {
final NavigationHelperVisitor visitor =
new NavigationHelperVisitor.TraversingVisitor(this, toGatherFeatures, toGatherClasses, oldClasses, toGatherDataTypes);
traverse(visitor);
}
}
}
} catch (Exception e) {
getLogger().fatal("EMF-IncQuery Base encountered an error while traversing the EMF model to gather new information. " , e);
throw new InvocationTargetException(e);
}
return result;
}
|
diff --git a/src/sai_cas/services/UserServices.java b/src/sai_cas/services/UserServices.java
index 1c14979..e13e42b 100644
--- a/src/sai_cas/services/UserServices.java
+++ b/src/sai_cas/services/UserServices.java
@@ -1,25 +1,25 @@
package sai_cas.services;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import sai_cas.db.DBConnection;
import sai_cas.db.DBInterface;
;
public class UserServices
{
static Logger logger = Logger.getLogger("sai_cas.MainAxisServices");
public static void createNewUser(String adminLogin,
String adminPassword, String newLogin, String newPassword,
String email, String fullName) throws SQLException
{
- Connection conn = DBConnection.getSimpleConnection(adminLogin, adminPassword);
+ Connection conn = DBConnection.getPooledPerUserConnection(adminLogin, adminPassword);
//(login, password);
DBInterface dbi = new DBInterface(conn);
dbi.executeSimpleQuery("select cas_create_ordinary_user('"+newLogin+"','"+newPassword+"','"+fullName+"','"+email+"');");
dbi.close();
}
}
| true | true | public static void createNewUser(String adminLogin,
String adminPassword, String newLogin, String newPassword,
String email, String fullName) throws SQLException
{
Connection conn = DBConnection.getSimpleConnection(adminLogin, adminPassword);
//(login, password);
DBInterface dbi = new DBInterface(conn);
dbi.executeSimpleQuery("select cas_create_ordinary_user('"+newLogin+"','"+newPassword+"','"+fullName+"','"+email+"');");
dbi.close();
}
| public static void createNewUser(String adminLogin,
String adminPassword, String newLogin, String newPassword,
String email, String fullName) throws SQLException
{
Connection conn = DBConnection.getPooledPerUserConnection(adminLogin, adminPassword);
//(login, password);
DBInterface dbi = new DBInterface(conn);
dbi.executeSimpleQuery("select cas_create_ordinary_user('"+newLogin+"','"+newPassword+"','"+fullName+"','"+email+"');");
dbi.close();
}
|
diff --git a/src/uk/org/ownage/dmdirc/parser/ChannelListModeItem.java b/src/uk/org/ownage/dmdirc/parser/ChannelListModeItem.java
index 2a1a727c4..505a5bd7b 100644
--- a/src/uk/org/ownage/dmdirc/parser/ChannelListModeItem.java
+++ b/src/uk/org/ownage/dmdirc/parser/ChannelListModeItem.java
@@ -1,98 +1,98 @@
/*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack
*
* 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.
*
* SVN: $Id$
*/
package uk.org.ownage.dmdirc.parser;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* Contains Channel List Mode information.
*
* @author Shane Mc Cormack
* @author Chris Smith
* @version $Id$
* @see IRCParser
*/
public class ChannelListModeItem {
/**
* The Item itself.
*/
protected String myItem = "";
/**
* The Time the item was created.
*/
protected long myTime = 0;
/**
* The Person who created the item
*/
protected String myOwner = "";
/**
* Get The Item itself.
*
* @return The Item itself.
*/
public String getItem() { return myItem; }
/**
* Get The Person who created the item.
*
* @return The Person who created the item.
*/
public String getOwner() { return myOwner; }
/**
* Get The Time the item was created.
*
* @return The Time the item was created.
*/
public long getTime() { return myTime; }
/**
* Create a new Item.
*
* @param item The item (ie: [email protected])
* @param owner The owner (ie: Dataforce)
* @param time The Time (ie: 1173389295)
*/
public ChannelListModeItem(final String item, final String owner, final long time) {
myItem = item;
myTime = time;
myOwner = owner;
- if (owner.charAt(0) == ':') { myOwner = owner.substring(1); }
+ if (!owner.equals("") && owner.charAt(0) == ':') { myOwner = owner.substring(1); }
}
/**
* Get SVN Version information.
*
* @return SVN Version String
*/
public static String getSvnInfo () { return "$Id$"; }
}
| true | true | public ChannelListModeItem(final String item, final String owner, final long time) {
myItem = item;
myTime = time;
myOwner = owner;
if (owner.charAt(0) == ':') { myOwner = owner.substring(1); }
}
| public ChannelListModeItem(final String item, final String owner, final long time) {
myItem = item;
myTime = time;
myOwner = owner;
if (!owner.equals("") && owner.charAt(0) == ':') { myOwner = owner.substring(1); }
}
|
diff --git a/openFaces/source/org/openfaces/renderkit/util/ForEachRenderer.java b/openFaces/source/org/openfaces/renderkit/util/ForEachRenderer.java
index c15c76bc7..48e6cb06e 100644
--- a/openFaces/source/org/openfaces/renderkit/util/ForEachRenderer.java
+++ b/openFaces/source/org/openfaces/renderkit/util/ForEachRenderer.java
@@ -1,77 +1,78 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2009, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.openfaces.renderkit.util;
import org.openfaces.component.util.ForEach;
import org.openfaces.renderkit.RendererBase;
import org.openfaces.util.StyleUtil;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;
/**
* @author Alexey Tarasyuk
*/
public class ForEachRenderer extends RendererBase {
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) return;
super.encodeBegin(context, component);
ForEach forEach = (ForEach) component;
+ forEach.setObjectId(null);
String wrapperTagName = forEach.getWrapperTagName();
if (wrapperTagName == null || wrapperTagName.length() == 0)
return;
ResponseWriter writer = context.getResponseWriter();
String clientId = forEach.getClientId(context);
writer.startElement(wrapperTagName, forEach);
writer.writeAttribute("id", clientId, null);
String classStr = StyleUtil.getCSSClass(context, forEach, forEach.getStyle(), forEach.getStyleClass());
if (classStr != null) {
writer.writeAttribute("class", classStr, null);
}
StyleUtil.renderStyleClasses(context, forEach);
}
@Override
public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered())
return;
ForEach forEach = (ForEach) component;
forEach.setObjectId(null);
while (forEach.hasNext()) {
forEach.next();
super.encodeChildren(context, component);
}
forEach.setObjectId(null);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) return;
super.encodeEnd(context, component);
ForEach forEach = (ForEach) component;
String wrapperTagName = forEach.getWrapperTagName();
if (wrapperTagName == null || wrapperTagName.length() == 0)
return;
ResponseWriter writer = context.getResponseWriter();
writer.endElement(wrapperTagName);
}
@Override
public boolean getRendersChildren() {
return true;
}
}
| true | true | public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) return;
super.encodeBegin(context, component);
ForEach forEach = (ForEach) component;
String wrapperTagName = forEach.getWrapperTagName();
if (wrapperTagName == null || wrapperTagName.length() == 0)
return;
ResponseWriter writer = context.getResponseWriter();
String clientId = forEach.getClientId(context);
writer.startElement(wrapperTagName, forEach);
writer.writeAttribute("id", clientId, null);
String classStr = StyleUtil.getCSSClass(context, forEach, forEach.getStyle(), forEach.getStyleClass());
if (classStr != null) {
writer.writeAttribute("class", classStr, null);
}
StyleUtil.renderStyleClasses(context, forEach);
}
| public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) return;
super.encodeBegin(context, component);
ForEach forEach = (ForEach) component;
forEach.setObjectId(null);
String wrapperTagName = forEach.getWrapperTagName();
if (wrapperTagName == null || wrapperTagName.length() == 0)
return;
ResponseWriter writer = context.getResponseWriter();
String clientId = forEach.getClientId(context);
writer.startElement(wrapperTagName, forEach);
writer.writeAttribute("id", clientId, null);
String classStr = StyleUtil.getCSSClass(context, forEach, forEach.getStyle(), forEach.getStyleClass());
if (classStr != null) {
writer.writeAttribute("class", classStr, null);
}
StyleUtil.renderStyleClasses(context, forEach);
}
|
diff --git a/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java b/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java
index d6224ffaf0..2c6cb79d47 100644
--- a/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java
+++ b/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java
@@ -1,455 +1,455 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== 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 St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.kernel.csw.services;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import jeeves.server.context.ServiceContext;
import jeeves.utils.Log;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DocumentStoredFieldVisitor;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.CachingWrapperFilter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.csw.common.Csw;
import org.fao.geonet.csw.common.exceptions.CatalogException;
import org.fao.geonet.csw.common.exceptions.NoApplicableCodeEx;
import org.fao.geonet.csw.common.exceptions.OperationNotSupportedEx;
import org.fao.geonet.kernel.csw.CatalogConfiguration;
import org.fao.geonet.kernel.csw.CatalogDispatcher;
import org.fao.geonet.kernel.csw.CatalogService;
import org.fao.geonet.kernel.csw.services.getrecords.CatalogSearcher;
import org.fao.geonet.kernel.search.IndexAndTaxonomy;
import org.fao.geonet.kernel.search.LuceneConfig;
import org.fao.geonet.kernel.search.LuceneSearcher;
import org.fao.geonet.kernel.search.LuceneUtils;
import org.fao.geonet.kernel.search.SearchManager;
import org.fao.geonet.kernel.search.SummaryComparator;
import org.fao.geonet.kernel.search.SummaryComparator.SortOption;
import org.fao.geonet.kernel.search.SummaryComparator.Type;
import org.fao.geonet.kernel.search.index.GeonetworkMultiReader;
import org.fao.geonet.kernel.search.spatial.Pair;
import org.jdom.Element;
import bak.pcj.map.ObjectKeyIntMapIterator;
import bak.pcj.map.ObjectKeyIntOpenHashMap;
//=============================================================================
public class GetDomain extends AbstractOperation implements CatalogService
{
//---------------------------------------------------------------------------
//---
//--- Constructor
//---
//---------------------------------------------------------------------------
private LuceneConfig _luceneConfig;
public GetDomain(LuceneConfig luceneConfig) {
this._luceneConfig = luceneConfig;
}
//---------------------------------------------------------------------------
//---
//--- API methods
//---
//---------------------------------------------------------------------------
public String getName() { return "GetDomain"; }
//---------------------------------------------------------------------------
public Element execute(Element request, ServiceContext context) throws CatalogException
{
checkService(request);
checkVersion(request);
Element response = new Element(getName() +"Response", Csw.NAMESPACE_CSW);
String[] propertyNames = getParameters(request, "PropertyName");
String[] parameterNames = getParameters(request, "ParameterName");
String cswServiceSpecificConstraint = request.getChildText(Geonet.Elem.FILTER);
// PropertyName handled first.
if (propertyNames != null) {
List<Element> domainValues;
try {
domainValues = handlePropertyName(propertyNames, context, false, CatalogConfiguration.getMaxNumberOfRecordsForPropertyNames(), cswServiceSpecificConstraint, _luceneConfig);
} catch (Exception e) {
Log.error(Geonet.CSW, "Error getting domain value for specified PropertyName : " + e);
throw new NoApplicableCodeEx(
"Raised exception while getting domain value for specified PropertyName : " + e);
}
response.addContent(domainValues);
return response;
}
if (parameterNames != null) {
List<Element> domainValues = handleParameterName(parameterNames);
response.addContent(domainValues);
}
return response;
}
//---------------------------------------------------------------------------
public Element adaptGetRequest(Map<String, String> params)
{
String service = params.get("service");
String version = params.get("version");
String parameterName = params.get("parametername");
String propertyName = params.get("propertyname");
Element request = new Element(getName(), Csw.NAMESPACE_CSW);
setAttrib(request, "service", service);
setAttrib(request, "version", version);
//--- these 2 are in mutual exclusion.
Element propName = new Element("PropertyName", Csw.NAMESPACE_CSW).setText(propertyName);
Element paramName = new Element("ParameterName", Csw.NAMESPACE_CSW).setText(parameterName);
// Property is handled first.
if (propertyName != null && !propertyName.equals(""))
request.addContent(propName);
else if (parameterName != null && !parameterName.equals(""))
request.addContent(paramName);
return request;
}
//---------------------------------------------------------------------------
public Element retrieveValues(String parameterName) throws CatalogException {
return null;
}
//---------------------------------------------------------------------------
public static List<Element> handlePropertyName(String[] propertyNames,
ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception {
List<Element> domainValuesList = null;
if(Log.isDebugEnabled(Geonet.CSW))
Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords);
for (int i=0; i < propertyNames.length; i++) {
if (i==0) domainValuesList = new ArrayList<Element>();
// Initialize list of values element.
Element listOfValues = null;
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String property = propertyNames[i].trim();
// Set propertyName in any case.
Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(property));
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
SearchManager sm = gc.getSearchmanager();
IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null);
try {
GeonetworkMultiReader reader = indexAndTaxonomy.indexReader;
BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context);
BooleanQuery query = null;
// Apply CSW service specific constraint
if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) {
Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig);
query = new BooleanQuery();
BooleanClause.Occur occur = LuceneUtils
.convertRequiredAndProhibitedToOccur(true, false);
query.add(groupsQuery, occur);
query.add(constraintQuery, occur);
} else {
query = groupsQuery;
}
List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true));
Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false);
CachingWrapperFilter filter = null;
Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary(
maxRecords, 0, maxRecords, context.getLanguage(),
null, reader,
query, filter, sort, null, false, false,
false, false // Scoring is useless for GetDomain operation
);
TopDocs hits = searchResults.one();
try {
// Get mapped lucene field in CSW configuration
String indexField = CatalogConfiguration.getFieldMapping().get(
property.toLowerCase());
if (indexField != null)
property = indexField;
// check if params asked is in the index using getFieldNames ?
@SuppressWarnings("resource")
FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos();
if (fi.fieldInfo(property) == null)
continue;
boolean isRange = false;
if (CatalogConfiguration.getGetRecordsRangeFields().contains(
property))
isRange = true;
if (isRange)
listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW);
else
listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW);
Set<String> fields = new HashSet<String>();
fields.add(property);
fields.add("_isTemplate");
// parse each document in the index
String[] fieldValues;
SortedSet<String> sortedValues = new TreeSet<String>();
ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap();
for (int j = 0; j < hits.scoreDocs.length; j++) {
DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields);
reader.document(hits.scoreDocs[j].doc, selector);
Document doc = selector.getDocument();
// Skip templates and subTemplates
String[] isTemplate = doc.getValues("_isTemplate");
if (isTemplate[0] != null && !isTemplate[0].equals("n"))
continue;
// Get doc values for specified property
fieldValues = doc.getValues(property);
if (fieldValues == null)
continue;
addtoSortedSet(sortedValues, fieldValues, duplicateValues);
}
SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null);
TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator);
ObjectKeyIntMapIterator entries = duplicateValues.entries();
while(entries.hasNext()) {
+ entries.next();
sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries));
- entries.next();
}
if (freq)
return createValuesByFrequency(sortedValuesFrequency);
else
listOfValues.addContent(createValuesElement(sortedValues, isRange));
} finally {
// any children means that the catalog was unable to determine
// anything about the specified parameter
if (listOfValues!= null && listOfValues.getChildren().size() != 0)
domainValues.addContent(listOfValues);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
} finally {
sm.releaseIndexReader(indexAndTaxonomy);
}
}
return domainValuesList;
}
//---------------------------------------------------------------------------
//---
//--- Private methods
//---
//---------------------------------------------------------------------------
private List<Element> handleParameterName(String[] parameterNames) throws CatalogException {
Element values;
List<Element> domainValuesList = null;
for (int i=0; i < parameterNames.length; i++) {
if (i==0) domainValuesList = new ArrayList<Element>();
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String paramName = parameterNames[i];
// Set parameterName in any case.
Element pn = new Element("ParameterName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(paramName));
String operationName = paramName.substring(0, paramName.indexOf('.'));
String parameterName = paramName.substring(paramName.indexOf('.')+1);
CatalogService cs = checkOperation(operationName);
values = cs.retrieveValues(parameterName);
// values null mean that the catalog was unable to determine
// anything about the specified parameter
if (values != null)
domainValues.addContent(values);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
return domainValuesList;
}
//---------------------------------------------------------------------------
private CatalogService checkOperation(String operationName)
throws CatalogException {
CatalogService cs = CatalogDispatcher.hmServices.get(operationName);
if (cs == null)
throw new OperationNotSupportedEx(operationName);
return cs;
}
//---------------------------------------------------------------------------
private String[] getParameters(Element request, String parameter) {
if (request == null)
return null;
Element paramElt = request.getChild(parameter,Csw.NAMESPACE_CSW);
if (paramElt == null)
return null;
String parameterName = paramElt.getText();
return parameterName.split(",");
}
//---------------------------------------------------------------------------
/**
* @param sortedValues
* @param fieldValues
* @param duplicateValues
*/
private static void addtoSortedSet(SortedSet<String> sortedValues,
String[] fieldValues, ObjectKeyIntOpenHashMap duplicateValues) {
for (String value : fieldValues) {
sortedValues.add(value);
if (duplicateValues.containsKey(value)) {
int nb = duplicateValues.get(value);
duplicateValues.remove(value);
duplicateValues.put(value, nb+1);
} else
duplicateValues.put(value, 1);
}
}
//---------------------------------------------------------------------------
/**
* Create value element for each item of the string array
* @param sortedValues
* @param isRange
* @return
*/
private static List<Element> createValuesElement(SortedSet<String> sortedValues, boolean isRange) {
List<Element> valuesList = new ArrayList<Element>();
if (!isRange) {
for (String value : sortedValues) {
valuesList.add(new Element("Value", Csw.NAMESPACE_CSW).setText(value));
}
} else {
valuesList.add(new Element("MinValue",Csw.NAMESPACE_CSW).setText(sortedValues.first()));
valuesList.add(new Element("MaxValue",Csw.NAMESPACE_CSW).setText(sortedValues.last()));
}
return valuesList;
}
//---------------------------------------------------------------------------
/**
* @param sortedValuesFrequency
* @return
*/
private static List<Element> createValuesByFrequency(TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency) {
List<Element> values = new ArrayList<Element>();
Element value;
for (SummaryComparator.SummaryElement element : sortedValuesFrequency) {
value = new Element("Value", Csw.NAMESPACE_CSW);
value.setAttribute("count", Integer.toString(element.count));
value.setText(element.name);
values.add(value);
}
return values;
}
}
//=============================================================================
| false | true | public static List<Element> handlePropertyName(String[] propertyNames,
ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception {
List<Element> domainValuesList = null;
if(Log.isDebugEnabled(Geonet.CSW))
Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords);
for (int i=0; i < propertyNames.length; i++) {
if (i==0) domainValuesList = new ArrayList<Element>();
// Initialize list of values element.
Element listOfValues = null;
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String property = propertyNames[i].trim();
// Set propertyName in any case.
Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(property));
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
SearchManager sm = gc.getSearchmanager();
IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null);
try {
GeonetworkMultiReader reader = indexAndTaxonomy.indexReader;
BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context);
BooleanQuery query = null;
// Apply CSW service specific constraint
if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) {
Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig);
query = new BooleanQuery();
BooleanClause.Occur occur = LuceneUtils
.convertRequiredAndProhibitedToOccur(true, false);
query.add(groupsQuery, occur);
query.add(constraintQuery, occur);
} else {
query = groupsQuery;
}
List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true));
Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false);
CachingWrapperFilter filter = null;
Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary(
maxRecords, 0, maxRecords, context.getLanguage(),
null, reader,
query, filter, sort, null, false, false,
false, false // Scoring is useless for GetDomain operation
);
TopDocs hits = searchResults.one();
try {
// Get mapped lucene field in CSW configuration
String indexField = CatalogConfiguration.getFieldMapping().get(
property.toLowerCase());
if (indexField != null)
property = indexField;
// check if params asked is in the index using getFieldNames ?
@SuppressWarnings("resource")
FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos();
if (fi.fieldInfo(property) == null)
continue;
boolean isRange = false;
if (CatalogConfiguration.getGetRecordsRangeFields().contains(
property))
isRange = true;
if (isRange)
listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW);
else
listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW);
Set<String> fields = new HashSet<String>();
fields.add(property);
fields.add("_isTemplate");
// parse each document in the index
String[] fieldValues;
SortedSet<String> sortedValues = new TreeSet<String>();
ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap();
for (int j = 0; j < hits.scoreDocs.length; j++) {
DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields);
reader.document(hits.scoreDocs[j].doc, selector);
Document doc = selector.getDocument();
// Skip templates and subTemplates
String[] isTemplate = doc.getValues("_isTemplate");
if (isTemplate[0] != null && !isTemplate[0].equals("n"))
continue;
// Get doc values for specified property
fieldValues = doc.getValues(property);
if (fieldValues == null)
continue;
addtoSortedSet(sortedValues, fieldValues, duplicateValues);
}
SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null);
TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator);
ObjectKeyIntMapIterator entries = duplicateValues.entries();
while(entries.hasNext()) {
sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries));
entries.next();
}
if (freq)
return createValuesByFrequency(sortedValuesFrequency);
else
listOfValues.addContent(createValuesElement(sortedValues, isRange));
} finally {
// any children means that the catalog was unable to determine
// anything about the specified parameter
if (listOfValues!= null && listOfValues.getChildren().size() != 0)
domainValues.addContent(listOfValues);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
} finally {
sm.releaseIndexReader(indexAndTaxonomy);
}
}
return domainValuesList;
}
| public static List<Element> handlePropertyName(String[] propertyNames,
ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception {
List<Element> domainValuesList = null;
if(Log.isDebugEnabled(Geonet.CSW))
Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords);
for (int i=0; i < propertyNames.length; i++) {
if (i==0) domainValuesList = new ArrayList<Element>();
// Initialize list of values element.
Element listOfValues = null;
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String property = propertyNames[i].trim();
// Set propertyName in any case.
Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(property));
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
SearchManager sm = gc.getSearchmanager();
IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null);
try {
GeonetworkMultiReader reader = indexAndTaxonomy.indexReader;
BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context);
BooleanQuery query = null;
// Apply CSW service specific constraint
if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) {
Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig);
query = new BooleanQuery();
BooleanClause.Occur occur = LuceneUtils
.convertRequiredAndProhibitedToOccur(true, false);
query.add(groupsQuery, occur);
query.add(constraintQuery, occur);
} else {
query = groupsQuery;
}
List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true));
Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false);
CachingWrapperFilter filter = null;
Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary(
maxRecords, 0, maxRecords, context.getLanguage(),
null, reader,
query, filter, sort, null, false, false,
false, false // Scoring is useless for GetDomain operation
);
TopDocs hits = searchResults.one();
try {
// Get mapped lucene field in CSW configuration
String indexField = CatalogConfiguration.getFieldMapping().get(
property.toLowerCase());
if (indexField != null)
property = indexField;
// check if params asked is in the index using getFieldNames ?
@SuppressWarnings("resource")
FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos();
if (fi.fieldInfo(property) == null)
continue;
boolean isRange = false;
if (CatalogConfiguration.getGetRecordsRangeFields().contains(
property))
isRange = true;
if (isRange)
listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW);
else
listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW);
Set<String> fields = new HashSet<String>();
fields.add(property);
fields.add("_isTemplate");
// parse each document in the index
String[] fieldValues;
SortedSet<String> sortedValues = new TreeSet<String>();
ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap();
for (int j = 0; j < hits.scoreDocs.length; j++) {
DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields);
reader.document(hits.scoreDocs[j].doc, selector);
Document doc = selector.getDocument();
// Skip templates and subTemplates
String[] isTemplate = doc.getValues("_isTemplate");
if (isTemplate[0] != null && !isTemplate[0].equals("n"))
continue;
// Get doc values for specified property
fieldValues = doc.getValues(property);
if (fieldValues == null)
continue;
addtoSortedSet(sortedValues, fieldValues, duplicateValues);
}
SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null);
TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator);
ObjectKeyIntMapIterator entries = duplicateValues.entries();
while(entries.hasNext()) {
entries.next();
sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries));
}
if (freq)
return createValuesByFrequency(sortedValuesFrequency);
else
listOfValues.addContent(createValuesElement(sortedValues, isRange));
} finally {
// any children means that the catalog was unable to determine
// anything about the specified parameter
if (listOfValues!= null && listOfValues.getChildren().size() != 0)
domainValues.addContent(listOfValues);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
} finally {
sm.releaseIndexReader(indexAndTaxonomy);
}
}
return domainValuesList;
}
|
diff --git a/ij/Menus.java b/ij/Menus.java
index e2e60b15..94f4820e 100644
--- a/ij/Menus.java
+++ b/ij/Menus.java
@@ -1,1348 +1,1348 @@
package ij;
import ij.process.*;
import ij.util.*;
import ij.gui.ImageWindow;
import ij.plugin.MacroInstaller;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.awt.event.*;
import java.util.zip.*;
/**
This class installs and updates ImageJ's menus. Note that menu labels,
even in submenus, must be unique. This is because ImageJ uses a single
hash table for all menu labels. If you look closely, you will see that
File->Import->Text Image... and File->Save As->Text Image... do not use
the same label. One of the labels has an extra space.
@see ImageJ
*/
public class Menus {
public static final char PLUGINS_MENU = 'p';
public static final char IMPORT_MENU = 'i';
public static final char SAVE_AS_MENU = 's';
public static final char SHORTCUTS_MENU = 'h'; // 'h'=hotkey
public static final char ABOUT_MENU = 'a';
public static final char FILTERS_MENU = 'f';
public static final char TOOLS_MENU = 't';
public static final char UTILITIES_MENU = 'u';
public static final int WINDOW_MENU_ITEMS = 5; // fixed items at top of Window menu
public static final int NORMAL_RETURN = 0;
public static final int COMMAND_IN_USE = -1;
public static final int INVALID_SHORTCUT = -2;
public static final int SHORTCUT_IN_USE = -3;
public static final int NOT_INSTALLED = -4;
public static final int COMMAND_NOT_FOUND = -5;
public static final int MAX_OPEN_RECENT_ITEMS = 15;
private static MenuBar mbar;
private static CheckboxMenuItem gray8Item,gray16Item,gray32Item,
color256Item,colorRGBItem,RGBStackItem,HSBStackItem;
private static PopupMenu popup;
private static ImageJ ij;
private static ImageJApplet applet;
private static Hashtable demoImagesTable = new Hashtable();
private static String pluginsPath, macrosPath;
private static Menu pluginsMenu, importMenu, saveAsMenu, shortcutsMenu,
aboutMenu, filtersMenu, toolsMenu, utilitiesMenu, macrosMenu, optionsMenu;
private static Hashtable pluginsTable;
static Menu window, openRecentMenu;
static int nPlugins, nMacros;
private static Hashtable shortcuts = new Hashtable();
private static Hashtable macroShortcuts;
private static Vector pluginsPrefs = new Vector(); // commands saved in IJ_Prefs
static int windowMenuItems2; // non-image windows listed in Window menu + separator
private static String error;
private String jarError;
private String pluginError;
private boolean isJarErrorHeading;
private boolean installingJars, duplicateCommand;
private static Vector jarFiles; // JAR files in plugins folder with "_" in their name
private static Vector macroFiles; // Macro files in plugins folder with "_" in their name
private int importCount, saveAsCount, toolsCount, optionsCount;
private static Hashtable menusTable; // Submenus of Plugins menu
private int userPluginsIndex; // First user plugin or submenu in Plugins menu
private boolean addSorted;
private static int fontSize = Prefs.getInt(Prefs.MENU_SIZE, 14);
private static Font menuFont;
static boolean jnlp; // true when using Java WebStart
Menus(ImageJ ijInstance, ImageJApplet appletInstance) {
ij = ijInstance;
applet = appletInstance;
}
String addMenuBar() {
error = null;
pluginsTable = new Hashtable();
Menu file = new PopupMenu("File");
addSubMenu(file, "New");
addPlugInItem(file, "Open...", "ij.plugin.Commands(\"open\")", KeyEvent.VK_O, false);
addPlugInItem(file, "Open Next", "ij.plugin.NextImageOpener", KeyEvent.VK_O, true);
if (applet == null)
addSubMenu(file, "Open Samples");
addOpenRecentSubMenu(file);
importMenu = addSubMenu(file, "Import");
file.addSeparator();
addPlugInItem(file, "Close", "ij.plugin.Commands(\"close\")", KeyEvent.VK_W, false);
addPlugInItem(file, "Save", "ij.plugin.Commands(\"save\")", KeyEvent.VK_S, false);
saveAsMenu = addSubMenu(file, "Save As");
addPlugInItem(file, "Revert", "ij.plugin.Commands(\"revert\")", KeyEvent.VK_R, false);
file.addSeparator();
addPlugInItem(file, "Page Setup...", "ij.plugin.filter.Printer(\"setup\")", 0, false);
addPlugInItem(file, "Print...", "ij.plugin.filter.Printer(\"print\")", KeyEvent.VK_P, false);
file.addSeparator();
addPlugInItem(file, "Quit", "ij.plugin.Commands(\"quit\")", 0, false);
Menu edit = new PopupMenu("Edit");
addPlugInItem(edit, "Undo", "ij.plugin.Commands(\"undo\")", KeyEvent.VK_Z, false);
edit.addSeparator();
addPlugInItem(edit, "Cut", "ij.plugin.Clipboard(\"cut\")", KeyEvent.VK_X, false);
addPlugInItem(edit, "Copy", "ij.plugin.Clipboard(\"copy\")", KeyEvent.VK_C, false);
addPlugInItem(edit, "Copy to System", "ij.plugin.Clipboard(\"scopy\")", 0, false);
addPlugInItem(edit, "Paste", "ij.plugin.Clipboard(\"paste\")", KeyEvent.VK_V, false);
addPlugInItem(edit, "Paste Control...", "ij.plugin.frame.PasteController", 0, false);
edit.addSeparator();
addPlugInItem(edit, "Clear", "ij.plugin.filter.Filler(\"clear\")", 0, false);
addPlugInItem(edit, "Clear Outside", "ij.plugin.filter.Filler(\"outside\")", 0, false);
addPlugInItem(edit, "Fill", "ij.plugin.filter.Filler(\"fill\")", KeyEvent.VK_F, false);
addPlugInItem(edit, "Draw", "ij.plugin.filter.Filler(\"draw\")", KeyEvent.VK_D, false);
addPlugInItem(edit, "Invert", "ij.plugin.filter.Filters(\"invert\")", KeyEvent.VK_I, true);
edit.addSeparator();
addSubMenu(edit, "Selection");
optionsMenu = addSubMenu(edit, "Options");
Menu image = new PopupMenu("Image");
Menu imageType = new Menu("Type");
gray8Item = addCheckboxItem(imageType, "8-bit", "ij.plugin.Converter(\"8-bit\")");
gray16Item = addCheckboxItem(imageType, "16-bit", "ij.plugin.Converter(\"16-bit\")");
gray32Item = addCheckboxItem(imageType, "32-bit", "ij.plugin.Converter(\"32-bit\")");
color256Item = addCheckboxItem(imageType, "8-bit Color", "ij.plugin.Converter(\"8-bit Color\")");
colorRGBItem = addCheckboxItem(imageType, "RGB Color", "ij.plugin.Converter(\"RGB Color\")");
imageType.add(new MenuItem("-"));
RGBStackItem = addCheckboxItem(imageType, "RGB Stack", "ij.plugin.Converter(\"RGB Stack\")");
HSBStackItem = addCheckboxItem(imageType, "HSB Stack", "ij.plugin.Converter(\"HSB Stack\")");
image.add(imageType);
image.addSeparator();
addSubMenu(image, "Adjust");
addPlugInItem(image, "Show Info...", "ij.plugin.filter.Info", KeyEvent.VK_I, false);
addPlugInItem(image, "Properties...", "ij.plugin.filter.ImageProperties", KeyEvent.VK_P, true);
addSubMenu(image, "Color");
addSubMenu(image, "Stacks");
image.addSeparator();
addPlugInItem(image, "Crop", "ij.plugin.filter.Resizer(\"crop\")", KeyEvent.VK_X, true);
addPlugInItem(image, "Duplicate...", "ij.plugin.filter.Duplicater", KeyEvent.VK_D, true);
addPlugInItem(image, "Rename...", "ij.plugin.SimpleCommands(\"rename\")", 0, false);
addPlugInItem(image, "Scale...", "ij.plugin.Scaler", KeyEvent.VK_E, false);
addSubMenu(image, "Rotate");
addSubMenu(image, "Zoom");
image.addSeparator();
addSubMenu(image, "Lookup Tables");
Menu process = new PopupMenu("Process");
addPlugInItem(process, "Smooth", "ij.plugin.filter.Filters(\"smooth\")", KeyEvent.VK_S, true);
addPlugInItem(process, "Sharpen", "ij.plugin.filter.Filters(\"sharpen\")", 0, false);
addPlugInItem(process, "Find Edges", "ij.plugin.filter.Filters(\"edge\")", 0, false);
addPlugInItem(process, "Enhance Contrast", "ij.plugin.ContrastEnhancer", 0, false);
addSubMenu(process, "Noise");
addSubMenu(process, "Shadows");
addSubMenu(process, "Binary");
addSubMenu(process, "Math");
addSubMenu(process, "FFT");
filtersMenu = addSubMenu(process, "Filters");
process.addSeparator();
addPlugInItem(process, "Image Calculator...", "ij.plugin.ImageCalculator", 0, false);
addPlugInItem(process, "Subtract Background...", "ij.plugin.filter.BackgroundSubtracter", 0, false);
addItem(process, "Repeat Command", KeyEvent.VK_R, true);
Menu analyze = new PopupMenu("Analyze");
addPlugInItem(analyze, "Measure", "ij.plugin.filter.Analyzer", KeyEvent.VK_M, false);
addPlugInItem(analyze, "Analyze Particles...", "ij.plugin.filter.ParticleAnalyzer", 0, false);
addPlugInItem(analyze, "Summarize", "ij.plugin.filter.Analyzer(\"sum\")", 0, false);
addPlugInItem(analyze, "Distribution...", "ij.plugin.Distribution", 0, false);
addPlugInItem(analyze, "Label", "ij.plugin.filter.Filler(\"label\")", 0, false);
addPlugInItem(analyze, "Clear Results", "ij.plugin.filter.Analyzer(\"clear\")", 0, false);
addPlugInItem(analyze, "Set Measurements...", "ij.plugin.filter.Analyzer(\"set\")", 0, false);
analyze.addSeparator();
addPlugInItem(analyze, "Set Scale...", "ij.plugin.filter.ScaleDialog", 0, false);
addPlugInItem(analyze, "Calibrate...", "ij.plugin.filter.Calibrator", 0, false);
addPlugInItem(analyze, "Histogram", "ij.plugin.Histogram", KeyEvent.VK_H, false);
addPlugInItem(analyze, "Plot Profile", "ij.plugin.filter.Profiler(\"plot\")", KeyEvent.VK_K, false);
addPlugInItem(analyze, "Surface Plot...", "ij.plugin.SurfacePlotter", 0, false);
addSubMenu(analyze, "Gels");
toolsMenu = addSubMenu(analyze, "Tools");
- window = new Menu("Window");
+ window = new PopupMenu("Window");
addPlugInItem(window, "Show All", "ij.plugin.WindowOrganizer(\"show\")", KeyEvent.VK_F, true);
addPlugInItem(window, "Put Behind [tab]", "ij.plugin.Commands(\"tab\")", 0, false);
addPlugInItem(window, "Cascade", "ij.plugin.WindowOrganizer(\"cascade\")", 0, false);
addPlugInItem(window, "Tile", "ij.plugin.WindowOrganizer(\"tile\")", 0, false);
window.addSeparator();
Menu help = new PopupMenu("Help");
aboutMenu = addSubMenu(help, "About Plugins");
help.addSeparator();
addPlugInItem(help, "ImageJA Web Site...", "ij.plugin.BrowserLauncher", 0, false);
addPlugInItem(help, "Online Docs...", "ij.plugin.BrowserLauncher(\"online\")", 0, false);
addPlugInItem(help, "About ImageJA...", "ij.plugin.AboutBoxJA", 0, false);
addPluginsMenu();
if (applet==null) {
installPlugins();
mbar = new MenuBar();
if (fontSize!=0)
mbar.setFont(getFont());
} else
mbar = applet.menu.getMenuBar();
mbar.add(file);
mbar.add(edit);
mbar.add(image);
mbar.add(process);
mbar.add(analyze);
mbar.add(pluginsMenu);
mbar.add(window);
mbar.setHelpMenu(help);
if (ij!=null && applet == null)
ij.setMenuBar(mbar);
if (pluginError!=null)
error = error!=null?error+="\n"+pluginError:pluginError;
if (jarError!=null)
error = error!=null?error+="\n"+jarError:jarError;
return error;
}
void addOpenRecentSubMenu(Menu menu) {
openRecentMenu = new Menu("Open Recent");
for (int i=0; i<MAX_OPEN_RECENT_ITEMS; i++) {
String path = Prefs.getString("recent" + (i/10)%10 + i%10);
if (path==null) break;
MenuItem item = new MenuItem(path);
openRecentMenu.add(item);
item.addActionListener(ij);
}
menu.add(openRecentMenu);
}
void addItem(Menu menu, String label, int shortcut, boolean shift) {
if (menu==null)
return;
MenuItem item;
if (shortcut==0)
item = new MenuItem(label);
else {
if (shift) {
item = new MenuItem(label, new MenuShortcut(shortcut, true));
shortcuts.put(new Integer(shortcut+200),label);
} else {
item = new MenuItem(label, new MenuShortcut(shortcut));
shortcuts.put(new Integer(shortcut),label);
}
}
if (addSorted) {
if (menu==pluginsMenu)
addItemSorted(menu, item, userPluginsIndex);
else
addOrdered(menu, item);
} else
menu.add(item);
item.addActionListener(ij);
}
void addPlugInItem(Menu menu, String label, String className, int shortcut, boolean shift) {
pluginsTable.put(label, className);
nPlugins++;
addItem(menu, label, shortcut, shift);
}
CheckboxMenuItem addCheckboxItem(Menu menu, String label, String className) {
pluginsTable.put(label, className);
nPlugins++;
CheckboxMenuItem item = new CheckboxMenuItem(label);
menu.add(item);
item.addItemListener(ij);
item.setState(false);
return item;
}
Menu addSubMenu(Menu menu, String name) {
String value;
String key = name.toLowerCase(Locale.US);
int index;
Menu submenu=new Menu(name.replace('_', ' '));
index = key.indexOf(' ');
if (index>0)
key = key.substring(0, index);
for (int count=1; count<100; count++) {
value = Prefs.getString(key + (count/10)%10 + count%10);
if (value==null)
break;
if (count==1)
menu.add(submenu);
if (value.equals("-"))
submenu.addSeparator();
else
addPluginItem(submenu, value);
}
if (name.equals("Lookup Tables") && applet==null)
addLuts(submenu);
return submenu;
}
void addLuts(Menu submenu) {
String path = Prefs.getHomeDir()+File.separator;
File f = new File(path+"luts");
String[] list = null;
if (applet==null && f.exists() && f.isDirectory())
list = f.list();
if (list==null) return;
if (IJ.isLinux()) StringSorter.sort(list);
submenu.addSeparator();
for (int i=0; i<list.length; i++) {
String name = list[i];
if (name.endsWith(".lut")) {
name = name.substring(0,name.length()-4);
MenuItem item = new MenuItem(name);
submenu.add(item);
item.addActionListener(ij);
nPlugins++;
}
}
}
void addPluginItem(Menu submenu, String s) {
if (s.startsWith("\"-\"")) {
// add menu separator if command="-"
addSeparator(submenu);
return;
}
int lastComma = s.lastIndexOf(',');
if (lastComma<=0)
return;
String command = s.substring(1,lastComma-1);
int keyCode = 0;
boolean shift = false;
if (command.endsWith("]")) {
int openBracket = command.lastIndexOf('[');
if (openBracket>0) {
String shortcut = command.substring(openBracket+1,command.length()-1);
keyCode = convertShortcutToCode(shortcut);
boolean functionKey = keyCode>=KeyEvent.VK_F1 && keyCode<=KeyEvent.VK_F12;
if (keyCode>0 && !functionKey)
command = command.substring(0,openBracket);
//IJ.write(command+": "+shortcut);
}
}
if (keyCode>=KeyEvent.VK_F1 && keyCode<=KeyEvent.VK_F12) {
shortcuts.put(new Integer(keyCode),command);
keyCode = 0;
} else if (keyCode>=265 && keyCode<=290) {
keyCode -= 200;
shift = true;
}
addItem(submenu,command,keyCode,shift);
while(s.charAt(lastComma+1)==' ' && lastComma+2<s.length())
lastComma++; // remove leading spaces
String className = s.substring(lastComma+1,s.length());
//IJ.log(command+" "+className);
if (installingJars)
duplicateCommand = pluginsTable.get(command)!=null;
pluginsTable.put(command, className);
nPlugins++;
}
void checkForDuplicate(String command) {
if (pluginsTable.get(command)!=null) {
}
}
void addPluginsMenu() {
String value,label,className;
int index;
pluginsMenu = new PopupMenu("Plugins");
for (int count=1; count<100; count++) {
value = Prefs.getString("plug-in" + (count/10)%10 + count%10);
if (value==null)
break;
char firstChar = value.charAt(0);
if (firstChar=='-')
pluginsMenu.addSeparator();
else if (firstChar=='>') {
String submenu = value.substring(2,value.length()-1);
Menu menu = addSubMenu(pluginsMenu, submenu);
if (submenu.equals("Shortcuts"))
shortcutsMenu = menu;
else if (submenu.equals("Utilities"))
utilitiesMenu = menu;
else if (submenu.equals("Macros"))
macrosMenu = menu;
} else
addPluginItem(pluginsMenu, value);
}
userPluginsIndex = pluginsMenu.getItemCount();
if (userPluginsIndex<0) userPluginsIndex = 0;
}
/** Install plugins using "pluginxx=" keys in IJ_Prefs.txt.
Plugins not listed in IJ_Prefs are added to the end
of the Plugins menu. */
void installPlugins() {
String value, className;
char menuCode;
Menu menu;
String[] plugins = getPlugins();
String[] plugins2 = null;
Hashtable skipList = new Hashtable();
for (int index=0; index<100; index++) {
value = Prefs.getString("plugin" + (index/10)%10 + index%10);
if (value==null)
break;
menuCode = value.charAt(0);
switch (menuCode) {
case PLUGINS_MENU: default: menu = pluginsMenu; break;
case IMPORT_MENU: menu = importMenu; break;
case SAVE_AS_MENU: menu = saveAsMenu; break;
case SHORTCUTS_MENU: menu = shortcutsMenu; break;
case ABOUT_MENU: menu = aboutMenu; break;
case FILTERS_MENU: menu = filtersMenu; break;
case TOOLS_MENU: menu = toolsMenu; break;
case UTILITIES_MENU: menu = utilitiesMenu; break;
}
String prefsValue = value;
value = value.substring(2,value.length()); //remove menu code and coma
className = value.substring(value.lastIndexOf(',')+1,value.length());
boolean found = className.startsWith("ij.");
if (!found && plugins!=null) { // does this plugin exist?
if (plugins2==null)
plugins2 = getStrippedPlugins(plugins);
for (int i=0; i<plugins2.length; i++) {
if (className.startsWith(plugins2[i])) {
found = true;
break;
}
}
}
if (found) {
addPluginItem(menu, value);
pluginsPrefs.addElement(prefsValue);
if (className.endsWith("\")")) { // remove any argument
int argStart = className.lastIndexOf("(\"");
if (argStart>0)
className = className.substring(0, argStart);
}
skipList.put(className, "");
}
}
if (plugins!=null) {
for (int i=0; i<plugins.length; i++) {
if (!skipList.containsKey(plugins[i]))
installUserPlugin(plugins[i]);
}
}
installJarPlugins();
installMacros();
}
/** Installs macro files that are located in the plugins folder and have a "_" in their name. */
void installMacros() {
if (macroFiles==null)
return;
for (int i=0; i<macroFiles.size(); i++) {
String name = (String)macroFiles.elementAt(i);
installMacro(name);
}
}
/** Installs a macro in the Plugins menu, or submenu, with
with underscores in the file name replaced by spaces. */
void installMacro(String name) {
Menu menu = pluginsMenu;
String dir = null;
int slashIndex = name.indexOf('/');
if (slashIndex>0) {
dir = name.substring(0, slashIndex);
name = name.substring(slashIndex+1, name.length());
menu = getPluginsSubmenu(dir);
}
String command = name.replace('_',' ');
command = command.substring(0, command.length()-4); //remove ".txt" or ".ijm"
command.trim();
if (pluginsTable.get(command)!=null) // duplicate command?
command = command + " Macro";
MenuItem item = new MenuItem(command);
addOrdered(menu, item);
item.addActionListener(ij);
String path = (dir!=null?dir+File.separator:"") + name;
pluginsTable.put(command, "ij.plugin.Macro_Runner(\""+path+"\")");
nMacros++;
}
/** Inserts 'item' into 'menu' in alphanumeric order. */
void addOrdered(Menu menu, MenuItem item) {
if (menu==pluginsMenu)
{menu.add(item); return;}
String label = item.getLabel();
for (int i=0; i<menu.getItemCount(); i++) {
if (label.compareTo(menu.getItem(i).getLabel())<0) {
menu.insert(item, i);
return;
}
}
menu.add(item);
}
/** Install plugins located in JAR files. */
void installJarPlugins() {
if (jarFiles==null)
return;
installingJars = true;
for (int i=0; i<jarFiles.size(); i++) {
isJarErrorHeading = false;
String jar = (String)jarFiles.elementAt(i);
InputStream is = getConfigurationFile(jar);
if (is==null) continue;
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
try {
while(true) {
String s = lnr.readLine();
if (s==null) break;
installJarPlugin(jar, s);
}
}
catch (IOException e) {}
finally {
try {if (lnr!=null) lnr.close();}
catch (IOException e) {}
}
}
}
/** Install a plugin located in a JAR file. */
void installJarPlugin(String jar, String s) {
//IJ.log(s);
if (s.length()<3) return;
char firstChar = s.charAt(0);
if (firstChar=='#') return;
addSorted = false;
Menu menu;
if (s.startsWith("Plugins>")) {
int firstComma = s.indexOf(',');
if (firstComma==-1 || firstComma<=8)
menu = null;
else {
String name = s.substring(8, firstComma);
menu = getPluginsSubmenu(name);
}
} else if (firstChar=='"' || s.startsWith("Plugins")) {
String name = getSubmenuName(jar);
if (name!=null)
menu = getPluginsSubmenu(name);
else
menu = pluginsMenu;
addSorted = true;
} else if (s.startsWith("File>Import")) {
menu = importMenu;
if (importCount==0) addSeparator(menu);
importCount++;
} else if (s.startsWith("File>Save")) {
menu = saveAsMenu;
if (saveAsCount==0) addSeparator(menu);
saveAsCount++;
} else if (s.startsWith("Analyze>Tools")) {
menu = toolsMenu;
if (toolsCount==0) addSeparator(menu);
toolsCount++;
} else if (s.startsWith("Help>About")) {
menu = aboutMenu;
} else if (s.startsWith("Edit>Options")) {
menu = optionsMenu;
if (optionsCount==0) addSeparator(menu);
optionsCount++;
} else {
if (jarError==null) jarError = "";
addJarErrorHeading(jar);
jarError += " Invalid menu: " + s + "\n";
return;
}
int firstQuote = s.indexOf('"');
if (firstQuote==-1)
return;
s = s.substring(firstQuote, s.length()); // remove menu
if (menu!=null) {
addPluginItem(menu, s);
addSorted = false;
}
if (duplicateCommand) {
if (jarError==null) jarError = "";
addJarErrorHeading(jar);
jarError += " Duplicate command: " + s + "\n";
}
duplicateCommand = false;
}
void addJarErrorHeading(String jar) {
if (!isJarErrorHeading) {
if (!jarError.equals(""))
jarError += " \n";
jarError += "Plugin configuration error: " + jar + "\n";
isJarErrorHeading = true;
}
}
Menu getPluginsSubmenu(String submenuName) {
if (menusTable!=null) {
Menu menu = (Menu)menusTable.get(submenuName);
if (menu!=null)
return menu;
}
Menu menu = new Menu(submenuName);
//pluginsMenu.add(menu);
addItemSorted(pluginsMenu, menu, userPluginsIndex);
if (menusTable==null) menusTable = new Hashtable();
menusTable.put(submenuName, menu);
//IJ.log("getPluginsSubmenu: "+submenuName);
return menu;
}
String getSubmenuName(String jarPath) {
//IJ.log("getSubmenuName: \n"+jarPath+"\n"+pluginsPath);
if (jarPath.startsWith(pluginsPath))
jarPath = jarPath.substring(pluginsPath.length() - 1);
int index = jarPath.lastIndexOf(File.separatorChar);
if (index<0) return null;
String name = jarPath.substring(0, index);
index = name.lastIndexOf(File.separatorChar);
if (index<0) return null;
name = name.substring(index+1);
if (name.equals("plugins")) return null;
return name;
}
static void addItemSorted(Menu menu, MenuItem item, int startingIndex) {
String itemLabel = item.getLabel();
int count = menu.getItemCount();
boolean inserted = false;
for (int i=startingIndex; i<count; i++) {
MenuItem mi = menu.getItem(i);
String label = mi.getLabel();
//IJ.log(i+ " "+itemLabel+" "+label + " "+(itemLabel.compareTo(label)));
if (itemLabel.compareTo(label)<0) {
menu.insert(item, i);
inserted = true;
break;
}
}
if (!inserted) menu.add(item);
}
void addSeparator(Menu menu) {
menu.addSeparator();
}
/** Opens the configuration file ("plugins.txt") from a JAR file and returns it as an InputStream. */
InputStream getConfigurationFile(String jar) {
try {
ZipFile jarFile = new ZipFile(jar);
Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.getName().endsWith("plugins.config"))
return jarFile.getInputStream(entry);
}
}
catch (Exception e) {}
return autoGenerateConfigFile(jar);
}
/** Creates a configuration file for JAR/ZIP files that do not have one. */
InputStream autoGenerateConfigFile(String jar) {
StringBuffer sb = null;
try {
ZipFile jarFile = new ZipFile(jar);
Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String name = entry.getName();
if (name.endsWith(".class") && name.indexOf("_")>0 && name.indexOf("$")==-1
&& name.indexOf("/_")==-1 && !name.startsWith("_")) {
if (sb==null) sb = new StringBuffer();
String className = name.substring(0, name.length()-6);
int slashIndex = className.lastIndexOf('/');
String plugins = "Plugins";
if (slashIndex >= 0) {
plugins += ">" + className.substring(0, slashIndex).replace('/', '>').replace('_', ' ');
name = className.substring(slashIndex + 1);
} else
name = className;
name = name.replace('_', ' ');
className = className.replace('/', '.');
sb.append(plugins + ", \""+name+"\", "+className+"\n");
}
}
}
catch (Exception e) {}
//IJ.log(""+(sb!=null?sb.toString():"null"));
if (sb==null)
return null;
else
return new ByteArrayInputStream(sb.toString().getBytes());
}
/** Returns a list of the plugins with directory names removed. */
String[] getStrippedPlugins(String[] plugins) {
String[] plugins2 = new String[plugins.length];
int slashPos;
for (int i=0; i<plugins2.length; i++) {
plugins2[i] = plugins[i];
slashPos = plugins2[i].lastIndexOf('/');
if (slashPos>=0)
plugins2[i] = plugins[i].substring(slashPos+1,plugins2[i].length());
}
return plugins2;
}
/** Returns a list of the plugins in the plugins menu. */
public static synchronized String[] getPlugins() {
String homeDir = Prefs.getHomeDir();
if (homeDir==null)
return null;
if (homeDir.endsWith("plugins"))
pluginsPath = homeDir+Prefs.separator;
else {
String property = System.getProperty("plugins.dir");
if (property!=null && (property.endsWith("/")||property.endsWith("\\")))
property = property.substring(0, property.length()-1);
String pluginsDir = property;
if (pluginsDir==null)
pluginsDir = homeDir;
else if (pluginsDir.equals("user.home")) {
pluginsDir = System.getProperty("user.home");
if (!(new File(pluginsDir+Prefs.separator+"plugins")).isDirectory())
pluginsDir = pluginsDir + Prefs.separator + "ImageJ";
property = null;
// needed to run plugins when ImageJ launched using Java WebStart
if (applet==null) System.setSecurityManager(null);
jnlp = true;
}
pluginsPath = pluginsDir+Prefs.separator+"plugins"+Prefs.separator;
if (property!=null&&!(new File(pluginsPath)).isDirectory())
pluginsPath = pluginsDir + Prefs.separator;
macrosPath = pluginsDir+Prefs.separator+"macros"+Prefs.separator;
}
File f = macrosPath!=null?new File(macrosPath):null;
if (f!=null && !f.isDirectory())
macrosPath = null;
f = pluginsPath!=null?new File(pluginsPath):null;
if (f==null || (f!=null && !f.isDirectory())) {
//error = "Plugins folder not found at "+pluginsPath;
pluginsPath = null;
return null;
}
String[] list = f.list();
if (list==null)
return null;
Vector v = new Vector();
jarFiles = null;
macroFiles = null;
for (int i=0; i<list.length; i++) {
String name = list[i];
boolean isClassFile = name.endsWith(".class");
boolean hasUnderscore = name.indexOf('_')>=0;
if (hasUnderscore && isClassFile && name.indexOf('$')<0 ) {
name = name.substring(0, name.length()-6); // remove ".class"
v.addElement(name);
} else if (hasUnderscore && (name.endsWith(".jar") || name.endsWith(".zip"))) {
if (jarFiles==null) jarFiles = new Vector();
jarFiles.addElement(pluginsPath + name);
} else if (hasUnderscore && (name.endsWith(".txt")||name.endsWith(".ijm"))) {
if (macroFiles==null) macroFiles = new Vector();
macroFiles.addElement(name);
} else {
if (!isClassFile)
checkSubdirectory(pluginsPath, name, v);
}
}
list = new String[v.size()];
v.copyInto((String[])list);
StringSorter.sort(list);
return list;
}
/** Looks for plugins and jar files in a subdirectory of the plugins directory. */
static void checkSubdirectory(String path, String dir, Vector v) {
if (dir.endsWith(".java"))
return;
File f = new File(path, dir);
if (!f.isDirectory())
return;
String[] list = f.list();
if (list==null)
return;
dir += "/";
for (int i=0; i<list.length; i++) {
String name = list[i];
boolean hasUnderscore = name.indexOf('_')>=0;
if (hasUnderscore && name.endsWith(".class") && name.indexOf('$')<0) {
name = name.substring(0, name.length()-6); // remove ".class"
v.addElement(dir+name);
//IJ.write("File: "+f+"/"+name);
} else if (hasUnderscore && (name.endsWith(".jar") || name.endsWith(".zip"))) {
if (jarFiles==null) jarFiles = new Vector();
jarFiles.addElement(f.getPath() + File.separator + name);
} else if (hasUnderscore && (name.endsWith(".txt")||name.endsWith(".ijm"))) {
if (macroFiles==null) macroFiles = new Vector();
macroFiles.addElement(dir + name);
}
}
}
static String submenuName;
static Menu submenu;
/** Installs a plugin in the Plugins menu using the class name,
with underscores replaced by spaces, as the command. */
void installUserPlugin(String className) {
installUserPlugin(className, false);
}
public static void installUserPlugin(String className, boolean force) {
Menu menu = pluginsMenu;
int slashIndex = className.indexOf('/');
String command = className;
if (slashIndex>0) {
String dir = className.substring(0, slashIndex);
command = className.substring(slashIndex+1, className.length());
//className = className.replace('/', '.');
if (submenu==null || !submenuName.equals(dir)) {
submenuName = dir;
submenu = new Menu(submenuName);
pluginsMenu.add(submenu);
if (menusTable==null) menusTable = new Hashtable();
menusTable.put(submenuName, submenu);
}
menu = submenu;
//IJ.write(dir + " " + className);
}
command = command.replace('_',' ');
command.trim();
boolean itemExists = (pluginsTable.get(command)!=null);
if(force && itemExists)
return;
if (!force && itemExists) // duplicate command?
command = command + " Plugin";
MenuItem item = new MenuItem(command);
if(force)
addItemSorted(menu,item,0);
else
menu.add(item);
item.addActionListener(ij);
pluginsTable.put(command, className.replace('/', '.'));
nPlugins++;
}
void installPopupMenu(ImageJ ij) {
String s;
int count = 0;
MenuItem mi;
popup = new PopupMenu("");
if (fontSize!=0)
popup.setFont(getFont());
while (true) {
count++;
s = Prefs.getString("popup" + (count/10)%10 + count%10);
if (s==null)
break;
if (s.equals("-"))
popup.addSeparator();
else if (!s.equals("")) {
mi = new MenuItem(s);
mi.addActionListener(ij);
popup.add(mi);
}
}
}
public static MenuBar getMenuBar() {
return mbar;
}
public static Menu getMacrosMenu() {
return macrosMenu;
}
static final int RGB_STACK=10, HSB_STACK=11;
/** Updates the Image/Type and Window menus. */
public static void updateMenus() {
if (ij==null) return;
gray8Item.setState(false);
gray16Item.setState(false);
gray32Item.setState(false);
color256Item.setState(false);
colorRGBItem.setState(false);
RGBStackItem.setState(false);
HSBStackItem.setState(false);
ImagePlus imp = WindowManager.getCurrentImage();
if (imp==null)
return;
int type = imp.getType();
if (imp.getStackSize()>1) {
ImageStack stack = imp.getStack();
if (stack.isRGB()) type = RGB_STACK;
else if (stack.isHSB()) type = HSB_STACK;
}
if (type==ImagePlus.GRAY8) {
ImageProcessor ip = imp.getProcessor();
if (ip!=null && ip.getMinThreshold()==ImageProcessor.NO_THRESHOLD && ip.isColorLut()) {
type = ImagePlus.COLOR_256;
if (!ip.isPseudoColorLut())
imp.setType(ImagePlus.COLOR_256);
}
}
switch (type) {
case ImagePlus.GRAY8:
gray8Item.setState(true);
break;
case ImagePlus.GRAY16:
gray16Item.setState(true);
break;
case ImagePlus.GRAY32:
gray32Item.setState(true);
break;
case ImagePlus.COLOR_256:
color256Item.setState(true);
break;
case ImagePlus.COLOR_RGB:
colorRGBItem.setState(true);
break;
case RGB_STACK:
RGBStackItem.setState(true);
break;
case HSB_STACK:
HSBStackItem.setState(true);
break;
}
//update Window menu
int nItems = window.getItemCount();
int start = WINDOW_MENU_ITEMS + windowMenuItems2;
int index = start + WindowManager.getCurrentIndex();
try { // workaround for Linux/Java 5.0/bug
for (int i=start; i<nItems; i++) {
CheckboxMenuItem item = (CheckboxMenuItem)window.getItem(i);
item.setState(i==index);
}
} catch (NullPointerException e) {}
}
static boolean isColorLut(ImagePlus imp) {
ImageProcessor ip = imp.getProcessor();
IndexColorModel cm = (IndexColorModel)ip.getColorModel();
if (cm==null) return false;
int mapSize = cm.getMapSize();
byte[] reds = new byte[mapSize];
byte[] greens = new byte[mapSize];
byte[] blues = new byte[mapSize];
cm.getReds(reds);
cm.getGreens(greens);
cm.getBlues(blues);
boolean isColor = false;
for (int i=0; i<mapSize; i++) {
if ((reds[i] != greens[i]) || (greens[i] != blues[i])) {
isColor = true;
break;
}
}
return isColor;
}
/** Returns the path to the user plugins directory or
null if the plugins directory was not found. */
public static String getPlugInsPath() {
return pluginsPath;
}
/** Returns the path to the macros directory or
null if the macros directory was not found. */
public static String getMacrosPath() {
return macrosPath;
}
/** Returns the hashtable that associates commands with plugins. */
public static Hashtable getCommands() {
return pluginsTable;
}
/** Returns the hashtable that associates shortcuts with commands. The keys
in the hashtable are Integer keycodes, or keycode+200 for uppercase. */
public static Hashtable getShortcuts() {
return shortcuts;
}
/** Returns the hashtable that associates keyboard shortcuts with macros. The keys
in the hashtable are Integer keycodes, or keycode+200 for uppercase. */
public static Hashtable getMacroShortcuts() {
if (macroShortcuts==null) macroShortcuts = new Hashtable();
return macroShortcuts;
}
/** Returns the hashtable that associates menu names with menus. */
//public static Hashtable getMenus() {
// return menusTable;
//}
/** Inserts one item (a non-image window) into the Window menu. */
static synchronized void insertWindowMenuItem(Frame win) {
if (ij==null || win==null)
return;
CheckboxMenuItem item = new CheckboxMenuItem(win.getTitle());
item.addItemListener(ij);
int index = WINDOW_MENU_ITEMS+windowMenuItems2;
if (windowMenuItems2>=2)
index--;
window.insert(item, index);
windowMenuItems2++;
if (windowMenuItems2==1) {
window.insertSeparator(WINDOW_MENU_ITEMS+windowMenuItems2);
windowMenuItems2++;
}
//IJ.write("insertWindowMenuItem: "+windowMenuItems2);
}
/** Adds one image to the end of the Window menu. */
static synchronized void addWindowMenuItem(ImagePlus imp) {
//IJ.log("addWindowMenuItem: "+imp);
if (ij==null) return;
String name = imp.getTitle();
int size = (imp.getWidth()*imp.getHeight()*imp.getStackSize())/1024;
switch (imp.getType()) {
case ImagePlus.GRAY32: case ImagePlus.COLOR_RGB: // 32-bit
size *=4;
break;
case ImagePlus.GRAY16: // 16-bit
size *= 2;
break;
default: // 8-bit
;
}
CheckboxMenuItem item = new CheckboxMenuItem(name + " " + size + "K");
window.add(item);
item.addItemListener(ij);
}
/** Removes the specified item from the Window menu. */
static synchronized void removeWindowMenuItem(int index) {
//IJ.log("removeWindowMenuItem: "+index+" "+windowMenuItems2+" "+window.getItemCount());
if (ij==null)
return;
if (index>=0 && index<window.getItemCount()) {
window.remove(WINDOW_MENU_ITEMS+index);
if (index<windowMenuItems2) {
windowMenuItems2--;
if (windowMenuItems2==1) {
window.remove(WINDOW_MENU_ITEMS);
windowMenuItems2 = 0;
}
}
}
}
/** Changes the name of an item in the Window menu. */
public static synchronized void updateWindowMenuItem(String oldLabel, String newLabel) {
if (oldLabel.equals(newLabel))
return;
int first = WINDOW_MENU_ITEMS;
int last = window.getItemCount()-1;
//IJ.write("updateWindowMenuItem: "+" "+first+" "+last+" "+oldLabel+" "+newLabel);
try { // workaround for Linux/Java 5.0/bug
for (int i=first; i<=last; i++) {
MenuItem item = window.getItem(i);
//IJ.write(i+" "+item.getLabel()+" "+newLabel);
String label = item.getLabel();
if (item!=null && label.startsWith(oldLabel)) {
if (label.endsWith("K")) {
int index = label.lastIndexOf(' ');
if (index>-1)
newLabel += label.substring(index, label.length());
}
item.setLabel(newLabel);
return;
}
}
} catch (NullPointerException e) {}
}
/** Adds a file path to the beginning of the File/Open Recent submenu. */
public static synchronized void addOpenRecentItem(String path) {
if (ij==null) return;
int count = openRecentMenu.getItemCount();
if (count>0 && openRecentMenu.getItem(0).getLabel().equals(path))
return;
if (count==MAX_OPEN_RECENT_ITEMS)
openRecentMenu.remove(MAX_OPEN_RECENT_ITEMS-1);
MenuItem item = new MenuItem(path);
openRecentMenu.insert(item, 0);
item.addActionListener(ij);
}
public static PopupMenu getPopupMenu() {
return popup;
}
public static Menu getSaveAsMenu() {
return saveAsMenu;
}
/** Adds a plugin based command to the end of a specified menu.
* @param plugin the plugin (e.g. "Inverter_", "Inverter_("arg")")
* @param menuCode PLUGINS_MENU, IMPORT_MENU, SAVE_AS_MENU or HOT_KEYS
* @param command the menu item label (set to "" to uninstall)
* @param shortcut the keyboard shortcut (e.g. "y", "Y", "F1")
* @param ij ImageJ (the action listener)
*
* @return returns an error code(NORMAL_RETURN,COMMAND_IN_USE_ERROR, etc.)
*/
public static int installPlugin(String plugin, char menuCode, String command, String shortcut, ImageJ ij) {
if (command.equals("")) { //uninstall
//Object o = pluginsPrefs.remove(plugin);
//if (o==null)
// return NOT_INSTALLED;
//else
return NORMAL_RETURN;
}
if (commandInUse(command))
return COMMAND_IN_USE;
if (!validShortcut(shortcut))
return INVALID_SHORTCUT;
if (shortcutInUse(shortcut))
return SHORTCUT_IN_USE;
Menu menu;
switch (menuCode) {
case PLUGINS_MENU: menu = pluginsMenu; break;
case IMPORT_MENU: menu = importMenu; break;
case SAVE_AS_MENU: menu = saveAsMenu; break;
case SHORTCUTS_MENU: menu = shortcutsMenu; break;
case ABOUT_MENU: menu = aboutMenu; break;
case FILTERS_MENU: menu = filtersMenu; break;
case TOOLS_MENU: menu = toolsMenu; break;
case UTILITIES_MENU: menu = utilitiesMenu; break;
default: return 0;
}
int code = convertShortcutToCode(shortcut);
MenuItem item;
boolean functionKey = code>=KeyEvent.VK_F1 && code<=KeyEvent.VK_F12;
if (code==0)
item = new MenuItem(command);
else if (functionKey) {
command += " [F"+(code-KeyEvent.VK_F1+1)+"]";
shortcuts.put(new Integer(code),command);
item = new MenuItem(command);
}else {
shortcuts.put(new Integer(code),command);
int keyCode = code;
boolean shift = false;
if (keyCode>=265 && keyCode<=290) {
keyCode -= 200;
shift = true;
}
item = new MenuItem(command, new MenuShortcut(keyCode, shift));
}
menu.add(item);
item.addActionListener(ij);
pluginsTable.put(command, plugin);
shortcut = code>0 && !functionKey?"["+shortcut+"]":"";
//IJ.write("installPlugin: "+menuCode+",\""+command+shortcut+"\","+plugin);
pluginsPrefs.addElement(menuCode+",\""+command+shortcut+"\","+plugin);
return NORMAL_RETURN;
}
/** Deletes a command installed by installPlugin. */
public static int uninstallPlugin(String command) {
boolean found = false;
for (Enumeration en=pluginsPrefs.elements(); en.hasMoreElements();) {
String cmd = (String)en.nextElement();
if (cmd.indexOf(command)>0) {
pluginsPrefs.removeElement((Object)cmd);
found = true;
break;
}
}
if (found)
return NORMAL_RETURN;
else
return COMMAND_NOT_FOUND;
}
public static boolean commandInUse(String command) {
if (pluginsTable.get(command)!=null)
return true;
else
return false;
}
public static int convertShortcutToCode(String shortcut) {
int code = 0;
int len = shortcut.length();
if (len==2 && shortcut.charAt(0)=='F') {
code = KeyEvent.VK_F1+(int)shortcut.charAt(1)-49;
if (code>=KeyEvent.VK_F1 && code<=KeyEvent.VK_F9)
return code;
else
return 0;
}
if (len==3 && shortcut.charAt(0)=='F') {
code = KeyEvent.VK_F10+(int)shortcut.charAt(2)-48;
if (code>=KeyEvent.VK_F10 && code<=KeyEvent.VK_F12)
return code;
else
return 0;
}
if (len==2 && shortcut.charAt(0)=='N') { // numeric keypad
code = KeyEvent.VK_NUMPAD0+(int)shortcut.charAt(1)-48;
if (code>=KeyEvent.VK_NUMPAD0 && code<=KeyEvent.VK_NUMPAD9)
return code;
switch (shortcut.charAt(1)) {
case '/': return KeyEvent.VK_DIVIDE;
case '*': return KeyEvent.VK_MULTIPLY;
case '-': return KeyEvent.VK_SUBTRACT;
case '+': return KeyEvent.VK_ADD;
case '.': return KeyEvent.VK_DECIMAL;
default: return 0;
}
}
if (len!=1)
return 0;
int c = (int)shortcut.charAt(0);
if (c>=65&&c<=90) //A-Z
code = KeyEvent.VK_A+c-65 + 200;
else if (c>=97&&c<=122) //a-z
code = KeyEvent.VK_A+c-97;
else if (c>=48&&c<=57) //0-9
code = KeyEvent.VK_0+c-48;
else {
switch (c) {
case 43: code = KeyEvent.VK_PLUS; break;
case 45: code = KeyEvent.VK_MINUS; break;
//case 92: code = KeyEvent.VK_BACK_SLASH; break;
default: return 0;
}
}
return code;
}
void installStartupMacroSet() {
if (applet!=null) {
String docBase = ""+applet.getDocumentBase();
if (!docBase.endsWith("/")) {
int index = docBase.lastIndexOf("/");
if (index!=-1)
docBase = docBase.substring(0, index+1);
}
IJ.runPlugIn("ij.plugin.URLOpener", docBase+"StartupMacros.txt");
return;
}
if (macrosPath==null) {
(new MacroInstaller()).installFromIJJar("/macros/StartupMacros.txt");
return;
}
String path = macrosPath + "StartupMacros.txt";
File f = new File(path);
if (!f.exists()) {
path = macrosPath + "StartupMacros.ijm";
f = new File(path);
if (!f.exists()) {
(new MacroInstaller()).installFromIJJar("/macros/StartupMacros.txt");
return;
}
}
String libraryPath = macrosPath + "Library.txt";
f = new File(libraryPath);
boolean isLibrary = f.exists();
try {
MacroInstaller mi = new MacroInstaller();
if (isLibrary) mi.installLibrary(libraryPath);
mi.installFile(path);
nMacros += mi.getMacroCount();
} catch (Exception e) {}
}
static boolean validShortcut(String shortcut) {
int len = shortcut.length();
if (shortcut.equals(""))
return true;
else if (len==1)
return true;
else if (shortcut.startsWith("F") && (len==2 || len==3))
return true;
else
return false;
}
public static boolean shortcutInUse(String shortcut) {
int code = convertShortcutToCode(shortcut);
if (shortcuts.get(new Integer(code))!=null)
return true;
else
return false;
}
/** Set the size (in points) used for the fonts in ImageJ menus.
Set the size to 0 to use the Java default size. */
public static void setFontSize(int size) {
if (size<9 && size!=0) size = 9;
if (size>24) size = 24;
fontSize = size;
}
/** Returns the size (in points) used for the fonts in ImageJ menus. Returns
0 if the default font size is being used or if this is a Macintosh. */
public static int getFontSize() {
return IJ.isMacintosh()?0:fontSize;
}
public static Font getFont() {
if (menuFont==null)
menuFont = new Font("SanSerif", Font.PLAIN, fontSize==0?12:fontSize);
return menuFont;
}
/** Called once when ImageJ quits. */
public static void savePreferences(Properties prefs) {
int index = 0;
for (Enumeration en=pluginsPrefs.elements(); en.hasMoreElements();) {
String key = "plugin" + (index/10)%10 + index%10;
String value = (String)en.nextElement();
prefs.put(key, Prefs.escapeBackSlashes(value));
index++;
}
int n = openRecentMenu.getItemCount();
for (int i=0; i<n; i++) {
String key = ""+i;
if (key.length()==1) key = "0"+key;
key = "recent"+key;
prefs.put(key, Prefs.escapeBackSlashes(openRecentMenu.getItem(i).getLabel()));
}
prefs.put(Prefs.MENU_SIZE, Integer.toString(fontSize));
}
}
| true | true | String addMenuBar() {
error = null;
pluginsTable = new Hashtable();
Menu file = new PopupMenu("File");
addSubMenu(file, "New");
addPlugInItem(file, "Open...", "ij.plugin.Commands(\"open\")", KeyEvent.VK_O, false);
addPlugInItem(file, "Open Next", "ij.plugin.NextImageOpener", KeyEvent.VK_O, true);
if (applet == null)
addSubMenu(file, "Open Samples");
addOpenRecentSubMenu(file);
importMenu = addSubMenu(file, "Import");
file.addSeparator();
addPlugInItem(file, "Close", "ij.plugin.Commands(\"close\")", KeyEvent.VK_W, false);
addPlugInItem(file, "Save", "ij.plugin.Commands(\"save\")", KeyEvent.VK_S, false);
saveAsMenu = addSubMenu(file, "Save As");
addPlugInItem(file, "Revert", "ij.plugin.Commands(\"revert\")", KeyEvent.VK_R, false);
file.addSeparator();
addPlugInItem(file, "Page Setup...", "ij.plugin.filter.Printer(\"setup\")", 0, false);
addPlugInItem(file, "Print...", "ij.plugin.filter.Printer(\"print\")", KeyEvent.VK_P, false);
file.addSeparator();
addPlugInItem(file, "Quit", "ij.plugin.Commands(\"quit\")", 0, false);
Menu edit = new PopupMenu("Edit");
addPlugInItem(edit, "Undo", "ij.plugin.Commands(\"undo\")", KeyEvent.VK_Z, false);
edit.addSeparator();
addPlugInItem(edit, "Cut", "ij.plugin.Clipboard(\"cut\")", KeyEvent.VK_X, false);
addPlugInItem(edit, "Copy", "ij.plugin.Clipboard(\"copy\")", KeyEvent.VK_C, false);
addPlugInItem(edit, "Copy to System", "ij.plugin.Clipboard(\"scopy\")", 0, false);
addPlugInItem(edit, "Paste", "ij.plugin.Clipboard(\"paste\")", KeyEvent.VK_V, false);
addPlugInItem(edit, "Paste Control...", "ij.plugin.frame.PasteController", 0, false);
edit.addSeparator();
addPlugInItem(edit, "Clear", "ij.plugin.filter.Filler(\"clear\")", 0, false);
addPlugInItem(edit, "Clear Outside", "ij.plugin.filter.Filler(\"outside\")", 0, false);
addPlugInItem(edit, "Fill", "ij.plugin.filter.Filler(\"fill\")", KeyEvent.VK_F, false);
addPlugInItem(edit, "Draw", "ij.plugin.filter.Filler(\"draw\")", KeyEvent.VK_D, false);
addPlugInItem(edit, "Invert", "ij.plugin.filter.Filters(\"invert\")", KeyEvent.VK_I, true);
edit.addSeparator();
addSubMenu(edit, "Selection");
optionsMenu = addSubMenu(edit, "Options");
Menu image = new PopupMenu("Image");
Menu imageType = new Menu("Type");
gray8Item = addCheckboxItem(imageType, "8-bit", "ij.plugin.Converter(\"8-bit\")");
gray16Item = addCheckboxItem(imageType, "16-bit", "ij.plugin.Converter(\"16-bit\")");
gray32Item = addCheckboxItem(imageType, "32-bit", "ij.plugin.Converter(\"32-bit\")");
color256Item = addCheckboxItem(imageType, "8-bit Color", "ij.plugin.Converter(\"8-bit Color\")");
colorRGBItem = addCheckboxItem(imageType, "RGB Color", "ij.plugin.Converter(\"RGB Color\")");
imageType.add(new MenuItem("-"));
RGBStackItem = addCheckboxItem(imageType, "RGB Stack", "ij.plugin.Converter(\"RGB Stack\")");
HSBStackItem = addCheckboxItem(imageType, "HSB Stack", "ij.plugin.Converter(\"HSB Stack\")");
image.add(imageType);
image.addSeparator();
addSubMenu(image, "Adjust");
addPlugInItem(image, "Show Info...", "ij.plugin.filter.Info", KeyEvent.VK_I, false);
addPlugInItem(image, "Properties...", "ij.plugin.filter.ImageProperties", KeyEvent.VK_P, true);
addSubMenu(image, "Color");
addSubMenu(image, "Stacks");
image.addSeparator();
addPlugInItem(image, "Crop", "ij.plugin.filter.Resizer(\"crop\")", KeyEvent.VK_X, true);
addPlugInItem(image, "Duplicate...", "ij.plugin.filter.Duplicater", KeyEvent.VK_D, true);
addPlugInItem(image, "Rename...", "ij.plugin.SimpleCommands(\"rename\")", 0, false);
addPlugInItem(image, "Scale...", "ij.plugin.Scaler", KeyEvent.VK_E, false);
addSubMenu(image, "Rotate");
addSubMenu(image, "Zoom");
image.addSeparator();
addSubMenu(image, "Lookup Tables");
Menu process = new PopupMenu("Process");
addPlugInItem(process, "Smooth", "ij.plugin.filter.Filters(\"smooth\")", KeyEvent.VK_S, true);
addPlugInItem(process, "Sharpen", "ij.plugin.filter.Filters(\"sharpen\")", 0, false);
addPlugInItem(process, "Find Edges", "ij.plugin.filter.Filters(\"edge\")", 0, false);
addPlugInItem(process, "Enhance Contrast", "ij.plugin.ContrastEnhancer", 0, false);
addSubMenu(process, "Noise");
addSubMenu(process, "Shadows");
addSubMenu(process, "Binary");
addSubMenu(process, "Math");
addSubMenu(process, "FFT");
filtersMenu = addSubMenu(process, "Filters");
process.addSeparator();
addPlugInItem(process, "Image Calculator...", "ij.plugin.ImageCalculator", 0, false);
addPlugInItem(process, "Subtract Background...", "ij.plugin.filter.BackgroundSubtracter", 0, false);
addItem(process, "Repeat Command", KeyEvent.VK_R, true);
Menu analyze = new PopupMenu("Analyze");
addPlugInItem(analyze, "Measure", "ij.plugin.filter.Analyzer", KeyEvent.VK_M, false);
addPlugInItem(analyze, "Analyze Particles...", "ij.plugin.filter.ParticleAnalyzer", 0, false);
addPlugInItem(analyze, "Summarize", "ij.plugin.filter.Analyzer(\"sum\")", 0, false);
addPlugInItem(analyze, "Distribution...", "ij.plugin.Distribution", 0, false);
addPlugInItem(analyze, "Label", "ij.plugin.filter.Filler(\"label\")", 0, false);
addPlugInItem(analyze, "Clear Results", "ij.plugin.filter.Analyzer(\"clear\")", 0, false);
addPlugInItem(analyze, "Set Measurements...", "ij.plugin.filter.Analyzer(\"set\")", 0, false);
analyze.addSeparator();
addPlugInItem(analyze, "Set Scale...", "ij.plugin.filter.ScaleDialog", 0, false);
addPlugInItem(analyze, "Calibrate...", "ij.plugin.filter.Calibrator", 0, false);
addPlugInItem(analyze, "Histogram", "ij.plugin.Histogram", KeyEvent.VK_H, false);
addPlugInItem(analyze, "Plot Profile", "ij.plugin.filter.Profiler(\"plot\")", KeyEvent.VK_K, false);
addPlugInItem(analyze, "Surface Plot...", "ij.plugin.SurfacePlotter", 0, false);
addSubMenu(analyze, "Gels");
toolsMenu = addSubMenu(analyze, "Tools");
window = new Menu("Window");
addPlugInItem(window, "Show All", "ij.plugin.WindowOrganizer(\"show\")", KeyEvent.VK_F, true);
addPlugInItem(window, "Put Behind [tab]", "ij.plugin.Commands(\"tab\")", 0, false);
addPlugInItem(window, "Cascade", "ij.plugin.WindowOrganizer(\"cascade\")", 0, false);
addPlugInItem(window, "Tile", "ij.plugin.WindowOrganizer(\"tile\")", 0, false);
window.addSeparator();
Menu help = new PopupMenu("Help");
aboutMenu = addSubMenu(help, "About Plugins");
help.addSeparator();
addPlugInItem(help, "ImageJA Web Site...", "ij.plugin.BrowserLauncher", 0, false);
addPlugInItem(help, "Online Docs...", "ij.plugin.BrowserLauncher(\"online\")", 0, false);
addPlugInItem(help, "About ImageJA...", "ij.plugin.AboutBoxJA", 0, false);
addPluginsMenu();
if (applet==null) {
installPlugins();
mbar = new MenuBar();
if (fontSize!=0)
mbar.setFont(getFont());
} else
mbar = applet.menu.getMenuBar();
mbar.add(file);
mbar.add(edit);
mbar.add(image);
mbar.add(process);
mbar.add(analyze);
mbar.add(pluginsMenu);
mbar.add(window);
mbar.setHelpMenu(help);
if (ij!=null && applet == null)
ij.setMenuBar(mbar);
if (pluginError!=null)
error = error!=null?error+="\n"+pluginError:pluginError;
if (jarError!=null)
error = error!=null?error+="\n"+jarError:jarError;
return error;
}
| String addMenuBar() {
error = null;
pluginsTable = new Hashtable();
Menu file = new PopupMenu("File");
addSubMenu(file, "New");
addPlugInItem(file, "Open...", "ij.plugin.Commands(\"open\")", KeyEvent.VK_O, false);
addPlugInItem(file, "Open Next", "ij.plugin.NextImageOpener", KeyEvent.VK_O, true);
if (applet == null)
addSubMenu(file, "Open Samples");
addOpenRecentSubMenu(file);
importMenu = addSubMenu(file, "Import");
file.addSeparator();
addPlugInItem(file, "Close", "ij.plugin.Commands(\"close\")", KeyEvent.VK_W, false);
addPlugInItem(file, "Save", "ij.plugin.Commands(\"save\")", KeyEvent.VK_S, false);
saveAsMenu = addSubMenu(file, "Save As");
addPlugInItem(file, "Revert", "ij.plugin.Commands(\"revert\")", KeyEvent.VK_R, false);
file.addSeparator();
addPlugInItem(file, "Page Setup...", "ij.plugin.filter.Printer(\"setup\")", 0, false);
addPlugInItem(file, "Print...", "ij.plugin.filter.Printer(\"print\")", KeyEvent.VK_P, false);
file.addSeparator();
addPlugInItem(file, "Quit", "ij.plugin.Commands(\"quit\")", 0, false);
Menu edit = new PopupMenu("Edit");
addPlugInItem(edit, "Undo", "ij.plugin.Commands(\"undo\")", KeyEvent.VK_Z, false);
edit.addSeparator();
addPlugInItem(edit, "Cut", "ij.plugin.Clipboard(\"cut\")", KeyEvent.VK_X, false);
addPlugInItem(edit, "Copy", "ij.plugin.Clipboard(\"copy\")", KeyEvent.VK_C, false);
addPlugInItem(edit, "Copy to System", "ij.plugin.Clipboard(\"scopy\")", 0, false);
addPlugInItem(edit, "Paste", "ij.plugin.Clipboard(\"paste\")", KeyEvent.VK_V, false);
addPlugInItem(edit, "Paste Control...", "ij.plugin.frame.PasteController", 0, false);
edit.addSeparator();
addPlugInItem(edit, "Clear", "ij.plugin.filter.Filler(\"clear\")", 0, false);
addPlugInItem(edit, "Clear Outside", "ij.plugin.filter.Filler(\"outside\")", 0, false);
addPlugInItem(edit, "Fill", "ij.plugin.filter.Filler(\"fill\")", KeyEvent.VK_F, false);
addPlugInItem(edit, "Draw", "ij.plugin.filter.Filler(\"draw\")", KeyEvent.VK_D, false);
addPlugInItem(edit, "Invert", "ij.plugin.filter.Filters(\"invert\")", KeyEvent.VK_I, true);
edit.addSeparator();
addSubMenu(edit, "Selection");
optionsMenu = addSubMenu(edit, "Options");
Menu image = new PopupMenu("Image");
Menu imageType = new Menu("Type");
gray8Item = addCheckboxItem(imageType, "8-bit", "ij.plugin.Converter(\"8-bit\")");
gray16Item = addCheckboxItem(imageType, "16-bit", "ij.plugin.Converter(\"16-bit\")");
gray32Item = addCheckboxItem(imageType, "32-bit", "ij.plugin.Converter(\"32-bit\")");
color256Item = addCheckboxItem(imageType, "8-bit Color", "ij.plugin.Converter(\"8-bit Color\")");
colorRGBItem = addCheckboxItem(imageType, "RGB Color", "ij.plugin.Converter(\"RGB Color\")");
imageType.add(new MenuItem("-"));
RGBStackItem = addCheckboxItem(imageType, "RGB Stack", "ij.plugin.Converter(\"RGB Stack\")");
HSBStackItem = addCheckboxItem(imageType, "HSB Stack", "ij.plugin.Converter(\"HSB Stack\")");
image.add(imageType);
image.addSeparator();
addSubMenu(image, "Adjust");
addPlugInItem(image, "Show Info...", "ij.plugin.filter.Info", KeyEvent.VK_I, false);
addPlugInItem(image, "Properties...", "ij.plugin.filter.ImageProperties", KeyEvent.VK_P, true);
addSubMenu(image, "Color");
addSubMenu(image, "Stacks");
image.addSeparator();
addPlugInItem(image, "Crop", "ij.plugin.filter.Resizer(\"crop\")", KeyEvent.VK_X, true);
addPlugInItem(image, "Duplicate...", "ij.plugin.filter.Duplicater", KeyEvent.VK_D, true);
addPlugInItem(image, "Rename...", "ij.plugin.SimpleCommands(\"rename\")", 0, false);
addPlugInItem(image, "Scale...", "ij.plugin.Scaler", KeyEvent.VK_E, false);
addSubMenu(image, "Rotate");
addSubMenu(image, "Zoom");
image.addSeparator();
addSubMenu(image, "Lookup Tables");
Menu process = new PopupMenu("Process");
addPlugInItem(process, "Smooth", "ij.plugin.filter.Filters(\"smooth\")", KeyEvent.VK_S, true);
addPlugInItem(process, "Sharpen", "ij.plugin.filter.Filters(\"sharpen\")", 0, false);
addPlugInItem(process, "Find Edges", "ij.plugin.filter.Filters(\"edge\")", 0, false);
addPlugInItem(process, "Enhance Contrast", "ij.plugin.ContrastEnhancer", 0, false);
addSubMenu(process, "Noise");
addSubMenu(process, "Shadows");
addSubMenu(process, "Binary");
addSubMenu(process, "Math");
addSubMenu(process, "FFT");
filtersMenu = addSubMenu(process, "Filters");
process.addSeparator();
addPlugInItem(process, "Image Calculator...", "ij.plugin.ImageCalculator", 0, false);
addPlugInItem(process, "Subtract Background...", "ij.plugin.filter.BackgroundSubtracter", 0, false);
addItem(process, "Repeat Command", KeyEvent.VK_R, true);
Menu analyze = new PopupMenu("Analyze");
addPlugInItem(analyze, "Measure", "ij.plugin.filter.Analyzer", KeyEvent.VK_M, false);
addPlugInItem(analyze, "Analyze Particles...", "ij.plugin.filter.ParticleAnalyzer", 0, false);
addPlugInItem(analyze, "Summarize", "ij.plugin.filter.Analyzer(\"sum\")", 0, false);
addPlugInItem(analyze, "Distribution...", "ij.plugin.Distribution", 0, false);
addPlugInItem(analyze, "Label", "ij.plugin.filter.Filler(\"label\")", 0, false);
addPlugInItem(analyze, "Clear Results", "ij.plugin.filter.Analyzer(\"clear\")", 0, false);
addPlugInItem(analyze, "Set Measurements...", "ij.plugin.filter.Analyzer(\"set\")", 0, false);
analyze.addSeparator();
addPlugInItem(analyze, "Set Scale...", "ij.plugin.filter.ScaleDialog", 0, false);
addPlugInItem(analyze, "Calibrate...", "ij.plugin.filter.Calibrator", 0, false);
addPlugInItem(analyze, "Histogram", "ij.plugin.Histogram", KeyEvent.VK_H, false);
addPlugInItem(analyze, "Plot Profile", "ij.plugin.filter.Profiler(\"plot\")", KeyEvent.VK_K, false);
addPlugInItem(analyze, "Surface Plot...", "ij.plugin.SurfacePlotter", 0, false);
addSubMenu(analyze, "Gels");
toolsMenu = addSubMenu(analyze, "Tools");
window = new PopupMenu("Window");
addPlugInItem(window, "Show All", "ij.plugin.WindowOrganizer(\"show\")", KeyEvent.VK_F, true);
addPlugInItem(window, "Put Behind [tab]", "ij.plugin.Commands(\"tab\")", 0, false);
addPlugInItem(window, "Cascade", "ij.plugin.WindowOrganizer(\"cascade\")", 0, false);
addPlugInItem(window, "Tile", "ij.plugin.WindowOrganizer(\"tile\")", 0, false);
window.addSeparator();
Menu help = new PopupMenu("Help");
aboutMenu = addSubMenu(help, "About Plugins");
help.addSeparator();
addPlugInItem(help, "ImageJA Web Site...", "ij.plugin.BrowserLauncher", 0, false);
addPlugInItem(help, "Online Docs...", "ij.plugin.BrowserLauncher(\"online\")", 0, false);
addPlugInItem(help, "About ImageJA...", "ij.plugin.AboutBoxJA", 0, false);
addPluginsMenu();
if (applet==null) {
installPlugins();
mbar = new MenuBar();
if (fontSize!=0)
mbar.setFont(getFont());
} else
mbar = applet.menu.getMenuBar();
mbar.add(file);
mbar.add(edit);
mbar.add(image);
mbar.add(process);
mbar.add(analyze);
mbar.add(pluginsMenu);
mbar.add(window);
mbar.setHelpMenu(help);
if (ij!=null && applet == null)
ij.setMenuBar(mbar);
if (pluginError!=null)
error = error!=null?error+="\n"+pluginError:pluginError;
if (jarError!=null)
error = error!=null?error+="\n"+jarError:jarError;
return error;
}
|
diff --git a/araqne-krsyslog-parser/src/main/java/org/araqne/logparser/krsyslog/samsung/ExshieldCsvParser.java b/araqne-krsyslog-parser/src/main/java/org/araqne/logparser/krsyslog/samsung/ExshieldCsvParser.java
index 665c5fab..c29634cd 100644
--- a/araqne-krsyslog-parser/src/main/java/org/araqne/logparser/krsyslog/samsung/ExshieldCsvParser.java
+++ b/araqne-krsyslog-parser/src/main/java/org/araqne/logparser/krsyslog/samsung/ExshieldCsvParser.java
@@ -1,121 +1,121 @@
package org.araqne.logparser.krsyslog.samsung;
import java.util.HashMap;
import java.util.Map;
import org.araqne.log.api.V1LogParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExshieldCsvParser extends V1LogParser {
private final Logger slog = LoggerFactory.getLogger(ExshieldCsvParser.class);
private final String[] ADMITTED_FIELDS = new String[] { "priority", "e_time", "rule_id", "src_ip", "src_port", "dst_ip",
"dst_port", "protocol", "recv_byte", "send_byte", "duration", "s_time", "direction" };
// 0 string, 1 int, 2 long
private final int[] ADMITTED_TYPES = new int[] { 0, 0, 0, 0, 1, 0, 1, 0, 2, 2, 1, 0, 0 };
private final String[] DENIED_FIELDS = new String[] { "priority", "timestamp", "rule_id", "src_ip", "src_port", "dst_ip",
"dst_port", "protocol", "action", "sig_no", "deny_cnt", "direction" };
private final int[] DENIED_TYPES = new int[] { 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0 };
@Override
public Map<String, Object> parse(Map<String, Object> params) {
String line = null;
try {
line = (String) params.get("line");
if (line == null)
return params;
Map<String, Object> m = new HashMap<String, Object>();
int b = line.indexOf('[');
int e = line.indexOf(']', b);
if (b < 0 || e < 0)
return params;
String t = line.substring(b + 1, e);
if (t.equals("LOG_ADMITTED")) {
m.put("type", "admitted");
e++;
for (int i = 0; i < ADMITTED_FIELDS.length; i++) {
b = e + 1;
if (i == ADMITTED_FIELDS.length - 1)
e = line.indexOf('\n', b);
else
e = line.indexOf(',', b);
if (e < 0)
e = line.length();
String field = ADMITTED_FIELDS[i];
String value = line.substring(b, e);
switch (ADMITTED_TYPES[i]) {
case 0:
m.put(field, value);
break;
case 1:
- if (value.isEmpty())
+ if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Integer.valueOf(value));
break;
case 2:
- if (value.isEmpty())
+ if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Long.valueOf(value));
break;
}
}
} else if (t.equals("LOG_DENIED")) {
m.put("type", "denied");
e++;
for (int i = 0; i < DENIED_FIELDS.length; i++) {
b = e + 1;
if (i == DENIED_FIELDS.length - 1)
e = line.indexOf('\n', b);
else
e = line.indexOf(',', b);
if (e < 0)
e = line.length();
String field = DENIED_FIELDS[i];
String value = line.substring(b, e);
switch (DENIED_TYPES[i]) {
case 0:
m.put(field, value);
break;
case 1:
- if (value.isEmpty())
+ if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Integer.valueOf(value));
break;
case 2:
- if (value.isEmpty())
+ if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Long.valueOf(value));
break;
}
}
} else {
return params;
}
return m;
} catch (Throwable t) {
if (slog.isDebugEnabled())
slog.debug("araqne krsyslog parser: cannot parse exshield csv log - " + line, t);
return params;
}
}
}
| false | true | public Map<String, Object> parse(Map<String, Object> params) {
String line = null;
try {
line = (String) params.get("line");
if (line == null)
return params;
Map<String, Object> m = new HashMap<String, Object>();
int b = line.indexOf('[');
int e = line.indexOf(']', b);
if (b < 0 || e < 0)
return params;
String t = line.substring(b + 1, e);
if (t.equals("LOG_ADMITTED")) {
m.put("type", "admitted");
e++;
for (int i = 0; i < ADMITTED_FIELDS.length; i++) {
b = e + 1;
if (i == ADMITTED_FIELDS.length - 1)
e = line.indexOf('\n', b);
else
e = line.indexOf(',', b);
if (e < 0)
e = line.length();
String field = ADMITTED_FIELDS[i];
String value = line.substring(b, e);
switch (ADMITTED_TYPES[i]) {
case 0:
m.put(field, value);
break;
case 1:
if (value.isEmpty())
m.put(field, null);
else
m.put(field, Integer.valueOf(value));
break;
case 2:
if (value.isEmpty())
m.put(field, null);
else
m.put(field, Long.valueOf(value));
break;
}
}
} else if (t.equals("LOG_DENIED")) {
m.put("type", "denied");
e++;
for (int i = 0; i < DENIED_FIELDS.length; i++) {
b = e + 1;
if (i == DENIED_FIELDS.length - 1)
e = line.indexOf('\n', b);
else
e = line.indexOf(',', b);
if (e < 0)
e = line.length();
String field = DENIED_FIELDS[i];
String value = line.substring(b, e);
switch (DENIED_TYPES[i]) {
case 0:
m.put(field, value);
break;
case 1:
if (value.isEmpty())
m.put(field, null);
else
m.put(field, Integer.valueOf(value));
break;
case 2:
if (value.isEmpty())
m.put(field, null);
else
m.put(field, Long.valueOf(value));
break;
}
}
} else {
return params;
}
return m;
} catch (Throwable t) {
if (slog.isDebugEnabled())
slog.debug("araqne krsyslog parser: cannot parse exshield csv log - " + line, t);
return params;
}
}
| public Map<String, Object> parse(Map<String, Object> params) {
String line = null;
try {
line = (String) params.get("line");
if (line == null)
return params;
Map<String, Object> m = new HashMap<String, Object>();
int b = line.indexOf('[');
int e = line.indexOf(']', b);
if (b < 0 || e < 0)
return params;
String t = line.substring(b + 1, e);
if (t.equals("LOG_ADMITTED")) {
m.put("type", "admitted");
e++;
for (int i = 0; i < ADMITTED_FIELDS.length; i++) {
b = e + 1;
if (i == ADMITTED_FIELDS.length - 1)
e = line.indexOf('\n', b);
else
e = line.indexOf(',', b);
if (e < 0)
e = line.length();
String field = ADMITTED_FIELDS[i];
String value = line.substring(b, e);
switch (ADMITTED_TYPES[i]) {
case 0:
m.put(field, value);
break;
case 1:
if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Integer.valueOf(value));
break;
case 2:
if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Long.valueOf(value));
break;
}
}
} else if (t.equals("LOG_DENIED")) {
m.put("type", "denied");
e++;
for (int i = 0; i < DENIED_FIELDS.length; i++) {
b = e + 1;
if (i == DENIED_FIELDS.length - 1)
e = line.indexOf('\n', b);
else
e = line.indexOf(',', b);
if (e < 0)
e = line.length();
String field = DENIED_FIELDS[i];
String value = line.substring(b, e);
switch (DENIED_TYPES[i]) {
case 0:
m.put(field, value);
break;
case 1:
if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Integer.valueOf(value));
break;
case 2:
if (value.isEmpty() || value.equals("-"))
m.put(field, null);
else
m.put(field, Long.valueOf(value));
break;
}
}
} else {
return params;
}
return m;
} catch (Throwable t) {
if (slog.isDebugEnabled())
slog.debug("araqne krsyslog parser: cannot parse exshield csv log - " + line, t);
return params;
}
}
|
diff --git a/test/regression/src/org/jacorb/test/orb/rmi/AllTest.java b/test/regression/src/org/jacorb/test/orb/rmi/AllTest.java
index 33d5f1de6..3f2b05dee 100644
--- a/test/regression/src/org/jacorb/test/orb/rmi/AllTest.java
+++ b/test/regression/src/org/jacorb/test/orb/rmi/AllTest.java
@@ -1,40 +1,40 @@
package org.jacorb.test.orb.rmi;
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2003 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import junit.framework.*;
public class AllTest extends TestCase
{
public AllTest (String name)
{
super (name);
}
public static Test suite ()
{
- TestSuite suite = new TestSuite ("All ORB Tests");
+ TestSuite suite = new TestSuite ("RMI Tests");
suite.addTest (org.jacorb.test.orb.rmi.RMITest.suite());
return suite;
}
}
| true | true | public static Test suite ()
{
TestSuite suite = new TestSuite ("All ORB Tests");
suite.addTest (org.jacorb.test.orb.rmi.RMITest.suite());
return suite;
}
| public static Test suite ()
{
TestSuite suite = new TestSuite ("RMI Tests");
suite.addTest (org.jacorb.test.orb.rmi.RMITest.suite());
return suite;
}
|
diff --git a/org.eclipse.recommenders.rcp.utils/src/org/eclipse/recommenders/rcp/utils/ScaleOneDimensionLayout.java b/org.eclipse.recommenders.rcp.utils/src/org/eclipse/recommenders/rcp/utils/ScaleOneDimensionLayout.java
index c64594d20..f87782423 100644
--- a/org.eclipse.recommenders.rcp.utils/src/org/eclipse/recommenders/rcp/utils/ScaleOneDimensionLayout.java
+++ b/org.eclipse.recommenders.rcp.utils/src/org/eclipse/recommenders/rcp/utils/ScaleOneDimensionLayout.java
@@ -1,57 +1,61 @@
/**
* Copyright (c) 2010 Darmstadt University of Technology.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Johannes Lerch - initial API and implementation.
*/
package org.eclipse.recommenders.rcp.utils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;
/**
* Layouts all children to have the same width and height as the parent
* composite. For computing size of the component only the dimension given as
* parameter to the constructor will be used. <br>
*/
public class ScaleOneDimensionLayout extends Layout {
private final int dimension;
/**
* @param dimension
* Dimension which should be scaled, either SWT.VERTICAL or
* SWT.HORIZONTAL
*/
public ScaleOneDimensionLayout(final int dimension) {
this.dimension = dimension;
}
@Override
protected Point computeSize(final Composite composite, final int wHint, final int hHint, final boolean flushCache) {
final Control[] children = composite.getChildren();
int max = 0;
for (final Control child : children) {
final Point childSize = child.computeSize(wHint, hHint);
max = Math.max(max, dimension == SWT.HORIZONTAL ? childSize.x : childSize.y);
}
- return new Point(max, 0);
+ if (dimension == SWT.HORIZONTAL) {
+ return new Point(max, 0);
+ } else {
+ return new Point(0, max);
+ }
}
@Override
protected void layout(final Composite composite, final boolean flushCache) {
final Control[] children = composite.getChildren();
final Rectangle bounds = composite.getClientArea();
for (final Control child : children) {
child.setBounds(bounds);
}
}
}
| true | true | protected Point computeSize(final Composite composite, final int wHint, final int hHint, final boolean flushCache) {
final Control[] children = composite.getChildren();
int max = 0;
for (final Control child : children) {
final Point childSize = child.computeSize(wHint, hHint);
max = Math.max(max, dimension == SWT.HORIZONTAL ? childSize.x : childSize.y);
}
return new Point(max, 0);
}
| protected Point computeSize(final Composite composite, final int wHint, final int hHint, final boolean flushCache) {
final Control[] children = composite.getChildren();
int max = 0;
for (final Control child : children) {
final Point childSize = child.computeSize(wHint, hHint);
max = Math.max(max, dimension == SWT.HORIZONTAL ? childSize.x : childSize.y);
}
if (dimension == SWT.HORIZONTAL) {
return new Point(max, 0);
} else {
return new Point(0, max);
}
}
|
diff --git a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java
index 5b7307cb5..8f1d6dc49 100644
--- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java
+++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java
@@ -1,397 +1,397 @@
/*
* Copyright (c) 2002-2008 Gargoyle Software 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:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by Gargoyle Software Inc.
* (http://www.GargoyleSoftware.com/)."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
* 4. The name "Gargoyle Software" must not be used to endorse or promote
* products derived from this software without prior written permission.
* For written permission, please contact [email protected].
* 5. Products derived from this software may not be called "HtmlUnit", nor may
* "HtmlUnit" appear in their name, without prior written permission of
* Gargoyle Software Inc.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE
* SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.gargoylesoftware.htmlunit.javascript;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang.ClassUtils;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CollectingAlertHandler;
import com.gargoylesoftware.htmlunit.MockWebConnection;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebTestCase;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration;
/**
* Tests for {@link SimpleScriptable}.
*
* @version $Revision$
* @author <a href="mailto:[email protected]">Mike Bowler</a>
* @author <a href="mailto:[email protected]">Barnaby Court</a>
* @author David K. Taylor
* @author <a href="mailto:[email protected]">Ben Curren</a>
* @author Marc Guillemot
* @author Chris Erskine
* @author Ahmed Ashour
*/
public class SimpleScriptableTest extends WebTestCase {
/**
* Create an instance
* @param name The name of the test
*/
public SimpleScriptableTest(final String name) {
super(name);
}
/**
* @throws Exception if the test fails
*/
public void testCallInheritedFunction() throws Exception {
final WebClient client = new WebClient();
final MockWebConnection webConnection = new MockWebConnection(client);
final String content
= "<html><head><title>foo</title><script>\n"
+ "function doTest() {\n"
+ " document.form1.textfield1.focus();\n"
+ " alert('past focus');\n"
+ "}\n"
+ "</script></head><body onload='doTest()'>\n"
+ "<p>hello world</p>\n"
+ "<form name='form1'>\n"
+ " <input type='text' name='textfield1' id='textfield1' value='foo'/>\n"
+ "</form>\n"
+ "</body></html>";
webConnection.setDefaultResponse(content);
client.setWebConnection(webConnection);
final List<String> expectedAlerts = Collections.singletonList("past focus");
createTestPageForRealBrowserIfNeeded(content, expectedAlerts);
final List<String> collectedAlerts = new ArrayList<String>();
client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
final HtmlPage page = (HtmlPage) client.getPage(URL_GARGOYLE);
assertEquals("foo", page.getTitleText());
assertEquals("focus not changed to textfield1",
page.getFormByName("form1").getInputByName("textfield1"),
page.getElementWithFocus());
assertEquals(expectedAlerts, collectedAlerts);
}
/**
*/
public void testHtmlJavaScriptMapping_AllJavaScriptClassesArePresent() {
final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map =
JavaScriptConfiguration.getHtmlJavaScriptMapping();
final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host";
final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar));
// Now pull out those names that we know don't have html equivalents
names.remove("ActiveXObject");
names.remove("BoxObject");
+ names.remove("CSSStyleDeclaration");
names.remove("Document");
names.remove("DOMImplementation");
names.remove("DOMParser");
names.remove("Event");
names.remove("EventHandler");
names.remove("EventListenersContainer");
names.remove("FormField");
names.remove("History");
names.remove("HTMLCollection");
names.remove("HTMLCollectionTags");
names.remove("HTMLOptionsCollection");
names.remove("JavaScriptBackgroundJob");
names.remove("Location");
names.remove("MimeType");
names.remove("MimeTypeArray");
names.remove("MouseEvent");
names.remove("Navigator");
names.remove("Node");
names.remove("Plugin");
names.remove("PluginArray");
names.remove("Popup");
names.remove("Range");
names.remove("RowContainer");
names.remove("Screen");
names.remove("ScoperFunctionObject");
names.remove("Selection");
names.remove("SimpleArray");
- names.remove("Style");
names.remove("Stylesheet");
names.remove("StyleSheetList");
names.remove("TextRange");
names.remove("TextRectangle");
names.remove("UIEvent");
names.remove("Window");
names.remove("XMLDocument");
names.remove("XMLDOMParseError");
names.remove("XMLHttpRequest");
names.remove("XMLSerializer");
names.remove("XPathNSResolver");
names.remove("XPathResult");
names.remove("XSLTProcessor");
names.remove("XSLTemplate");
final Collection<String> hostClassNames = new ArrayList<String>();
for (final Class< ? extends SimpleScriptable> clazz : map.values()) {
hostClassNames.add(ClassUtils.getShortClassName(clazz));
}
assertEquals(new TreeSet<String>(names), new TreeSet<String>(hostClassNames));
}
private Set<String> getFileNames(final String directoryName) {
File directory = new File("." + File.separatorChar + directoryName);
if (!directory.exists()) {
directory = new File("./src/main/java/".replace('/', File.separatorChar) + directoryName);
}
assertTrue("directory exists", directory.exists());
assertTrue("is a directory", directory.isDirectory());
final String fileNames[] = directory.list();
final Set<String> collection = new HashSet<String>();
for (int i = 0; i < fileNames.length; i++) {
final String name = fileNames[i];
if (name.endsWith(".java")) {
collection.add(name.substring(0, name.length() - 5));
}
}
return collection;
}
/**
* This test fails on IE and FF but not by HtmlUnit because according to Ecma standard,
* attempts to set read only properties should be silently ignored.
* Furthermore document.body = document.body will work on FF but not on IE
* @throws Exception if the test fails
*/
public void testSetNonWritableProperty() throws Exception {
if (notYetImplemented()) {
return;
}
final String content
= "<html><head><title>foo</title></head><body onload='document.body=123456'>"
+ "</body></html>";
try {
loadPage(content);
fail("Exception should have been thrown");
}
catch (final ScriptException e) {
// it's ok
}
}
/**
* @throws Exception if the test fails
*/
public void testArguments_toString() throws Exception {
if (notYetImplemented()) {
return;
}
final String content = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " alert(arguments);\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {"[object Object]"};
final List<String> collectedAlerts = new ArrayList<String>();
loadPage(content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
/**
* @throws Exception if the test fails
*/
public void testStringWithExclamationMark() throws Exception {
final String content = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " var x = '<!>';\n"
+ " alert(x.length);\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {"3"};
final List<String> collectedAlerts = new ArrayList<String>();
loadPage(content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
/**
* Test the host class names match the Firefox (w3c names).
* @see <a
* href="http://java.sun.com/j2se/1.5.0/docs/guide/plugin/dom/org/w3c/dom/html/package-summary.html">DOM API</a>
* @throws Exception if the test fails.
*/
public void testHostClassNames() throws Exception {
if (notYetImplemented()) {
return;
}
testHostClassNames("HTMLAnchorElement");
}
private void testHostClassNames(final String className) throws Exception {
final String content = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " alert(" + className + ");\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {'[' + className + ']'};
final List<String> collectedAlerts = new ArrayList<String>();
loadPage(BrowserVersion.FIREFOX_2, content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
/**
* @throws Exception if the test fails
*/
public void testArrayedMap() throws Exception {
if (notYetImplemented()) {
return;
}
final String content = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " var map = {};\n"
+ " map['x1'] = 'y1';\n"
+ " map['x2'] = 'y2';\n"
+ " map['x3'] = 'y3';\n"
+ " map['x4'] = 'y4';\n"
+ " map['x5'] = 'y5';\n"
+ " for (var i in map) {\n"
+ " alert(i);\n"
+ " }"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {"x1", "x2", "x3", "x4", "x5"};
final List<String> collectedAlerts = new ArrayList<String>();
loadPage(content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
/**
* @throws Exception if the test fails
*/
public void testIsParentOf() throws Exception {
if (notYetImplemented()) {
return;
}
testIsParentOf("Node", "Element", true);
testIsParentOf("Document", "XMLDocument", true);
testIsParentOf("Node", "XPathResult", false);
testIsParentOf("Element", "HTMLElement", true);
testIsParentOf("HTMLElement", "HTMLHtmlElement", true);
//although Image != HTMLImageElement, they seem to be synonyms!!!
testIsParentOf("Image", "HTMLImageElement", true);
testIsParentOf("HTMLImageElement", "Image", true);
}
private void testIsParentOf(final String object1, final String object2, final boolean status) throws Exception {
final String content = "<html><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " alert(isParentOf(" + object1 + ", " + object2 + "));\n"
+ " }\n"
+ " /**\n"
+ " * Returns true if o1 prototype is parent/grandparent of o2 prototype\n"
+ " */\n"
+ " function isParentOf(o1, o2) {\n"
+ " o1.prototype.myCustomFunction = function() {};\n"
+ " return o1 != o2 && o2.prototype.myCustomFunction != undefined;\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {Boolean.toString(status)};
final List<String> collectedAlerts = new ArrayList<String>();
loadPage(BrowserVersion.FIREFOX_2, content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
/**
* @throws Exception if the test fails
*/
public void testWindowPropertyToString() throws Exception {
final String content = "<html id='myId'><head><title>foo</title><script>\n"
+ " function test() {\n"
+ " alert(document.getElementById('myId'));\n"
+ " alert(HTMLHtmlElement);\n"
+ " }\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final String[] expectedAlerts = {"[object HTMLHtmlElement]", "[HTMLHtmlElement]"};
createTestPageForRealBrowserIfNeeded(content, expectedAlerts);
final List<String> collectedAlerts = new ArrayList<String>();
loadPage(BrowserVersion.FIREFOX_2, content, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
/**
* This is related to HtmlUnitContextFactory.hasFeature(Context.FEATURE_PARENT_PROTO_PROPERTIES).
* @throws Exception if the test fails
*/
public void testParentProtoFeature() throws Exception {
testParentProtoFeature(BrowserVersion.INTERNET_EXPLORER_7_0, new String[] {"false"});
testParentProtoFeature(BrowserVersion.FIREFOX_2, new String[] {"true"});
}
private void testParentProtoFeature(final BrowserVersion browserVersion, final String[] expectedAlerts)
throws Exception {
final String html
= "<html><head><title>First</title><script>\n"
+ "function test() {\n"
+ " alert(document.createElement('div').__proto__ != undefined);\n"
+ "}\n"
+ "</script></head><body onload='test()'>\n"
+ "</body></html>";
final List<String> collectedAlerts = new ArrayList<String>();
loadPage(browserVersion, html, collectedAlerts);
assertEquals(expectedAlerts, collectedAlerts);
}
}
| false | true | public void testHtmlJavaScriptMapping_AllJavaScriptClassesArePresent() {
final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map =
JavaScriptConfiguration.getHtmlJavaScriptMapping();
final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host";
final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar));
// Now pull out those names that we know don't have html equivalents
names.remove("ActiveXObject");
names.remove("BoxObject");
names.remove("Document");
names.remove("DOMImplementation");
names.remove("DOMParser");
names.remove("Event");
names.remove("EventHandler");
names.remove("EventListenersContainer");
names.remove("FormField");
names.remove("History");
names.remove("HTMLCollection");
names.remove("HTMLCollectionTags");
names.remove("HTMLOptionsCollection");
names.remove("JavaScriptBackgroundJob");
names.remove("Location");
names.remove("MimeType");
names.remove("MimeTypeArray");
names.remove("MouseEvent");
names.remove("Navigator");
names.remove("Node");
names.remove("Plugin");
names.remove("PluginArray");
names.remove("Popup");
names.remove("Range");
names.remove("RowContainer");
names.remove("Screen");
names.remove("ScoperFunctionObject");
names.remove("Selection");
names.remove("SimpleArray");
names.remove("Style");
names.remove("Stylesheet");
names.remove("StyleSheetList");
names.remove("TextRange");
names.remove("TextRectangle");
names.remove("UIEvent");
names.remove("Window");
names.remove("XMLDocument");
names.remove("XMLDOMParseError");
names.remove("XMLHttpRequest");
names.remove("XMLSerializer");
names.remove("XPathNSResolver");
names.remove("XPathResult");
names.remove("XSLTProcessor");
names.remove("XSLTemplate");
final Collection<String> hostClassNames = new ArrayList<String>();
for (final Class< ? extends SimpleScriptable> clazz : map.values()) {
hostClassNames.add(ClassUtils.getShortClassName(clazz));
}
assertEquals(new TreeSet<String>(names), new TreeSet<String>(hostClassNames));
}
| public void testHtmlJavaScriptMapping_AllJavaScriptClassesArePresent() {
final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map =
JavaScriptConfiguration.getHtmlJavaScriptMapping();
final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host";
final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar));
// Now pull out those names that we know don't have html equivalents
names.remove("ActiveXObject");
names.remove("BoxObject");
names.remove("CSSStyleDeclaration");
names.remove("Document");
names.remove("DOMImplementation");
names.remove("DOMParser");
names.remove("Event");
names.remove("EventHandler");
names.remove("EventListenersContainer");
names.remove("FormField");
names.remove("History");
names.remove("HTMLCollection");
names.remove("HTMLCollectionTags");
names.remove("HTMLOptionsCollection");
names.remove("JavaScriptBackgroundJob");
names.remove("Location");
names.remove("MimeType");
names.remove("MimeTypeArray");
names.remove("MouseEvent");
names.remove("Navigator");
names.remove("Node");
names.remove("Plugin");
names.remove("PluginArray");
names.remove("Popup");
names.remove("Range");
names.remove("RowContainer");
names.remove("Screen");
names.remove("ScoperFunctionObject");
names.remove("Selection");
names.remove("SimpleArray");
names.remove("Stylesheet");
names.remove("StyleSheetList");
names.remove("TextRange");
names.remove("TextRectangle");
names.remove("UIEvent");
names.remove("Window");
names.remove("XMLDocument");
names.remove("XMLDOMParseError");
names.remove("XMLHttpRequest");
names.remove("XMLSerializer");
names.remove("XPathNSResolver");
names.remove("XPathResult");
names.remove("XSLTProcessor");
names.remove("XSLTemplate");
final Collection<String> hostClassNames = new ArrayList<String>();
for (final Class< ? extends SimpleScriptable> clazz : map.values()) {
hostClassNames.add(ClassUtils.getShortClassName(clazz));
}
assertEquals(new TreeSet<String>(names), new TreeSet<String>(hostClassNames));
}
|
diff --git a/regression/jvm/ExceptionsTest.java b/regression/jvm/ExceptionsTest.java
index c526e835..71c4d2f9 100644
--- a/regression/jvm/ExceptionsTest.java
+++ b/regression/jvm/ExceptionsTest.java
@@ -1,493 +1,493 @@
/*
* Copyright (C) 2009 Tomasz Grabiec
*
* This file is released under the GPL version 2 with the following
* clarification and special exception:
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under terms
* of your choice, provided that you also meet, for each linked independent
* module, the terms and conditions of the license of that module. An
* independent module is a module which is not derived from or based on
* this library. If you modify this library, you may extend this exception
* to your version of the library, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
* Please refer to the file LICENSE for details.
*/
package jvm;
/**
* @author Tomasz Grabiec
*/
public class ExceptionsTest extends TestCase {
public static int static_field;
public int field;
private void privateMethod() {
}
public void publicMethod() {
}
public static void takeInt(int val) {
}
public static void takeLong(long val) {
}
public static void takeObject(Object obj) {
}
public static void testTryBlockDoesNotThrowAnything() {
boolean caught;
try {
caught = false;
} catch (Exception e) {
caught = true;
}
assertFalse(caught);
}
public static void testThrowAndCatchInTheSameMethod() {
Exception exception = null;
boolean caught;
try {
caught = false;
throw exception = new Exception();
} catch (Exception e) {
assertEquals(exception, e);
caught = true;
}
assertTrue(caught);
}
public static void testUnwinding() {
String s = "unwind";
boolean caught = false;
try {
recurseTimesThenThrow(10, s);
} catch (Exception e) {
assertEquals(e.getMessage(), s);
caught = true;
}
assertTrue(caught);
}
public static void recurseTimesThenThrow(int counter, String s) {
if (counter == 0)
throw new RuntimeException(s);
recurseTimesThenThrow(counter - 1, s);
}
public static void testMultipleCatchBlocks() {
int section = 0;
try {
throw new MyException();
} catch (MyException2 e) {
section = 1;
} catch (MyException e) {
section = 2;
} catch (Exception e) {
section = 3;
}
assertEquals(section, 2);
}
private static class MyException extends Exception {
static final long serialVersionUID = 0;
};
private static class MyException2 extends MyException {
static final long serialVersionUID = 0;
};
public static void throwException(Exception e) throws Exception {
throw e;
}
public static void testNestedTryCatch() {
Exception a = new RuntimeException();
Exception b = new RuntimeException();
try {
throwException(a);
} catch (Exception _a) {
try {
throwException(b);
} catch (Exception _b) {
assertEquals(b, _b);
}
assertEquals(a, _a);
}
}
public static void testEmptyCatchBlock() {
try {
throw new Exception();
} catch (Exception e) {}
}
public static void testInvokespecial() {
boolean caught = false;
ExceptionsTest test = null;
try {
test.privateMethod();
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testInvokevirtual() {
boolean caught = false;
ExceptionsTest test = null;
try {
test.publicMethod();
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testArrayLoadThrowsNullPointerException() {
boolean caught = false;
Object[] array = null;
try {
takeObject(array[0]);
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testArrayLoadThrowsArrayIndexOutOfBoundsException() {
boolean caught = false;
Object[] array = new String[3];
try {
takeObject(array[3]);
} catch (ArrayIndexOutOfBoundsException e) {
caught = true;
}
assertTrue(caught);
}
public static void testArrayLoad() {
testArrayLoadThrowsNullPointerException();
testArrayLoadThrowsArrayIndexOutOfBoundsException();
}
public static void testArrayStoreThrowsNullPointerException() {
boolean caught = false;
Object[] array = null;
try {
array[0] = null;
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testArrayStoreThrowsArrayIndexOutOfBoundsException() {
boolean caught = false;
Object[] array = new String[3];
try {
array[3] = "test";
} catch (ArrayIndexOutOfBoundsException e) {
caught = true;
}
assertTrue(caught);
}
public static void testArrayStoreThrowsArrayStoreException() {
boolean caught = false;
Object[] array = new String[3];
try {
array[2] = new Integer(0);
} catch (ArrayStoreException e) {
caught = true;
}
assertTrue(caught);
}
public static void testArrayStore() {
testArrayStoreThrowsNullPointerException();
testArrayStoreThrowsArrayIndexOutOfBoundsException();
testArrayStoreThrowsArrayStoreException();
}
public static void testArraylength() {
boolean caught = false;
Object[] array = null;
try {
takeInt(array.length);
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testAthrow() {
boolean caught = false;
Exception exception = null;
try {
throw exception;
} catch (NullPointerException e) {
caught = true;
} catch (Exception e) {
}
assertTrue(caught);
}
public static void testGetfield() {
boolean caught = false;
ExceptionsTest test = null;
try {
takeInt(test.field);
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testPutfield() {
boolean caught = false;
ExceptionsTest test = null;
try {
test.field = 1;
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testMonitorenter() {
boolean caught = false;
Object mon = null;
try {
synchronized(mon) {
takeInt(1);
}
} catch (NullPointerException e) {
caught = true;
}
assertTrue(caught);
}
public static void testIdiv() {
boolean caught = false;
int denominator = 0;
try {
takeInt(1 / denominator);
} catch (ArithmeticException e) {
caught = true;
}
assertTrue(caught);
}
public static void testIrem() {
boolean caught = false;
int denominator = 0;
try {
takeInt(1 % denominator);
} catch (ArithmeticException e) {
caught = true;
}
assertTrue(caught);
}
public static void testLdiv() {
boolean caught = false;
long denominator = 0;
try {
takeLong(1L / denominator);
} catch (ArithmeticException e) {
caught = true;
}
assertTrue(caught);
}
public static void testLrem() {
boolean caught = false;
long denominator = 0;
try {
takeLong(1L % denominator);
} catch (ArithmeticException e) {
caught = true;
}
assertTrue(caught);
}
public static void testCheckcast() {
boolean caught = false;
Object o = null;
String s = null;
try {
s = (String)o;
} catch (ClassCastException e) {
caught = true;
}
assertFalse(caught);
o = new Object();
try {
s = (String)o;
} catch (ClassCastException e) {
caught = true;
}
assertTrue(caught);
takeObject(s);
}
public static void testAnewarray() {
boolean caught = false;
Object array[] = null;
try {
array = new Object[-1];
} catch (NegativeArraySizeException e) {
caught = true;
}
assertTrue(caught);
takeObject(array);
}
public static void testNewarray() {
boolean caught = false;
int array[] = null;
try {
array = new int[-1];
} catch (NegativeArraySizeException e) {
caught = true;
}
assertTrue(caught);
takeObject(array);
}
public static void testMultianewarray() {
boolean caught = false;
Object array[][] = null;
try {
array = new Object[1][-1];
} catch (NegativeArraySizeException e) {
caught = true;
}
assertTrue(caught);
caught = false;
try {
array = new Object[-1][1];
} catch (NegativeArraySizeException e) {
caught = true;
}
assertTrue(caught);
takeObject(array);
}
public static native void nativeMethod();
public static void testUnsatisfiedLinkError() {
boolean caught = false;
try {
nativeMethod();
} catch (UnsatisfiedLinkError e) {
caught = true;
}
assertTrue(caught);
}
public static void main(String args[]) {
testTryBlockDoesNotThrowAnything();
testThrowAndCatchInTheSameMethod();
/* FIXME
testUnwinding();
testMultipleCatchBlocks();
testNestedTryCatch();
+*/
testEmptyCatchBlock();
testInvokespecial();
testInvokevirtual();
testArrayLoad();
+/* FIXME
testArrayStore();
+*/
testArraylength();
testAthrow();
testGetfield();
testPutfield();
testMonitorenter();
-*/
/* TODO: testMonitorexit() */
-/* FIXME
testIdiv();
testIrem();
testLdiv();
testLrem();
testCheckcast();
testAnewarray();
testNewarray();
testMultianewarray();
testUnsatisfiedLinkError();
-*/
exit();
}
};
| false | true | public static void main(String args[]) {
testTryBlockDoesNotThrowAnything();
testThrowAndCatchInTheSameMethod();
/* FIXME
testUnwinding();
testMultipleCatchBlocks();
testNestedTryCatch();
testEmptyCatchBlock();
testInvokespecial();
testInvokevirtual();
testArrayLoad();
testArrayStore();
testArraylength();
testAthrow();
testGetfield();
testPutfield();
testMonitorenter();
*/
/* TODO: testMonitorexit() */
/* FIXME
testIdiv();
testIrem();
testLdiv();
testLrem();
testCheckcast();
testAnewarray();
testNewarray();
testMultianewarray();
testUnsatisfiedLinkError();
*/
exit();
}
| public static void main(String args[]) {
testTryBlockDoesNotThrowAnything();
testThrowAndCatchInTheSameMethod();
/* FIXME
testUnwinding();
testMultipleCatchBlocks();
testNestedTryCatch();
*/
testEmptyCatchBlock();
testInvokespecial();
testInvokevirtual();
testArrayLoad();
/* FIXME
testArrayStore();
*/
testArraylength();
testAthrow();
testGetfield();
testPutfield();
testMonitorenter();
/* TODO: testMonitorexit() */
testIdiv();
testIrem();
testLdiv();
testLrem();
testCheckcast();
testAnewarray();
testNewarray();
testMultianewarray();
testUnsatisfiedLinkError();
exit();
}
|
diff --git a/deprecated/org.atl.engine.repositories.emf4atl/src/org/atl/engine/repositories/emf4atl/ASMEMFModel.java b/deprecated/org.atl.engine.repositories.emf4atl/src/org/atl/engine/repositories/emf4atl/ASMEMFModel.java
index def8e27a..6c3751f8 100644
--- a/deprecated/org.atl.engine.repositories.emf4atl/src/org/atl/engine/repositories/emf4atl/ASMEMFModel.java
+++ b/deprecated/org.atl.engine.repositories.emf4atl/src/org/atl/engine/repositories/emf4atl/ASMEMFModel.java
@@ -1,542 +1,542 @@
package org.atl.engine.repositories.emf4atl;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.atl.engine.vm.ModelLoader;
import org.atl.engine.vm.nativelib.ASMModel;
import org.atl.engine.vm.nativelib.ASMModelElement;
import org.atl.engine.vm.nativelib.ASMString;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
/**
* @author Fr�d�ric Jouault
* @author Dennis Wagelaar <[email protected]>
*/
public class ASMEMFModel extends ASMModel {
// true if extent was explicitly loaded and requires explicit unloading
private boolean unload = false;
// nsURIs that were explicitly registered and need unregistering
private Set unregister = new HashSet();
// if not null, model could not yet be loaded from URI and needs to be loaded later from this URI
private String resolveURI = null;
private boolean checkSameModel = true;
public static ASMModel getMOF() {
return mofmm;
}
private Map modelElements = new HashMap();
public ASMModelElement getASMModelElement(EObject object) {
ASMModelElement ret = null;
synchronized(modelElements) {
ret = (ASMModelElement)modelElements.get(object);
if(ret == null) {
ret = new ASMEMFModelElement(modelElements, this, object);
}
}
return ret;
}
private Map classifiers = null;
private ASMModelElement getClassifier(String name) {
if(classifiers == null) {
classifiers = new HashMap();
initClassifiersInAllExtents(classifiers);
}
ASMModelElement ret = null;
EObject eo = (EObject)classifiers.get(name);
if(eo != null) {
ret = getASMModelElement(eo);
}
return ret;
}
/**
* Indexes all classifiers in main extent and
* referenced extents.
* @param classifiers The classifier map to build.
* @see #register(Map, String, EObject)
* @author Dennis Wagelaar <[email protected]>
*/
private void initClassifiersInAllExtents(Map classifiers) {
initClassifiers(getExtent().getContents().iterator(), classifiers, null);
Iterator refExtents = referencedExtents.iterator();
while (refExtents.hasNext()) {
initClassifiers(
((Resource)refExtents.next()).getContents().iterator(),
classifiers,
null);
}
}
private void initClassifiers(Iterator i, Map classifiers, String base) {
for( ; i.hasNext() ; ) {
EObject eo = (EObject)i.next();
if(eo instanceof EPackage) {
String name = ((EPackage)eo).getName();
if(base != null) {
name = base + "::" + name;
}
initClassifiers(((EPackage)eo).eContents().iterator(), classifiers, name);
} else if(eo instanceof EClassifier) {
String name = ((EClassifier)eo).getName();
// register the classifier under its simple name
register(classifiers, name, eo);
if(base != null) {
name = base + "::" + name;
// register the classifier under its full name
register(classifiers, name, eo);
}
} else {
// No meta-package or meta-class => just keep digging.
// N.B. This situation occurs in UML2 profiles, where
// EPackages containing EClasses are buried somewhere
// underneath other elements.
initClassifiers(eo.eContents().iterator(), classifiers, base);
}
}
}
private void register(Map classifiers, String name, EObject classifier) {
if(classifiers.containsKey(name)) {
System.out.println("Warning: metamodel contains several classifiers with same name: " + name);
}
classifiers.put(name, classifier);
}
public ASMModelElement findModelElement(String name) {
ASMModelElement ret = null;
ret = getClassifier(name);
return ret;
}
/*
public ASMModelElement findModelElement(String name) {
ASMModelElement ret = null;
EObject eo = null;
eo = findModelElementIn(name, extent.getContents().iterator());
if(eo != null)
ret = getASMModelElement(eo);
return ret;
}
private EObject findModelElementIn(String name, Iterator i) {
EObject ret = null;
for( ; i.hasNext() && (ret == null); ) {
EObject t = (EObject)i.next();
if(t instanceof EPackage) {
ret = ((EPackage)t).getEClassifier(name);
if(ret == null) {
ret = findModelElementIn(name, ((EPackage)t).getESubpackages().iterator());
}
}
}
return ret;
}
*/
/**
* @param type The type of element to search for.
* @return The set of ASMModelElements that are instances of type.
* @see ASMModelElement
*/
public Set getElementsByType(ASMModelElement type) {
Set ret = new HashSet();
EClass t = (EClass)((ASMEMFModelElement)type).getObject();
addElementsOfType(ret, t, getExtent());
for (Iterator i = referencedExtents.iterator(); i.hasNext() ; ) {
Resource res = (Resource) i.next();
addElementsOfType(ret, t, res);
}
return ret;
}
/**
* Adds all elements of the given type to the set.
* @param elements The set to add to.
* @param type The type to test for.
* @param res The resource containing the elements.
*/
private void addElementsOfType(Set elements, EClassifier type, Resource res) {
for(Iterator i = res.getAllContents() ; i.hasNext() ; ) {
EObject eo = (EObject)i.next();
if(type.isInstance(eo)) {
elements.add(getASMModelElement(eo));
}
}
}
public ASMModelElement newModelElement(ASMModelElement type) {
ASMModelElement ret = null;
EClass t = (EClass)((ASMEMFModelElement)type).getObject();
EObject eo = t.getEPackage().getEFactoryInstance().create(t);
ret = (ASMEMFModelElement)getASMModelElement(eo);
getExtent().getContents().add(eo);
return ret;
}
/**
* @param name
* @param metamodel
* @param isTarget
*/
protected ASMEMFModel(String name, Resource extent, ASMEMFModel metamodel, boolean isTarget, ModelLoader ml) {
super(name, metamodel, isTarget, ml);
this.extent = extent;
}
/**
* Simple Resource wrapping factory.
* @param ml ModelLoader used to load the model if available, null otherwise.
*/
public static ASMEMFModel loadASMEMFModel(String name, ASMEMFModel metamodel, Resource extent, ModelLoader ml) throws Exception {
ASMEMFModel ret = null;
ret = new ASMEMFModel(name, extent, metamodel, false, ml);
return ret;
}
public void dispose() {
//System.err.println("INFO: Disposing ASMEMFModel " + getName());
if (extent != null) {
referencedExtents.clear();
referencedExtents = null;
for (Iterator unrs = unregister.iterator(); unrs.hasNext();) {
String nsURI = (String)unrs.next();
resourceSet.getPackageRegistry().remove(nsURI);
//System.err.println("\tINFO: Unregistering " + nsURI + " from local EMF registry");
}
resourceSet.getResources().remove(extent);
if (unload) {
extent.unload();
}
extent = null;
modelElements.clear();
unregister.clear();
}
}
public void finalize() {
dispose();
}
/**
* Creates a new ASMEMFModel. Do not use this method for models that
* require a special registered factory (e.g. uml2).
* @param name The model name. Also used as EMF model URI.
* @param metamodel
* @param ml
* @return
* @throws Exception
*/
public static ASMEMFModel newASMEMFModel(String name, ASMEMFModel metamodel, ModelLoader ml) throws Exception {
return newASMEMFModel(name, name, metamodel, ml);
}
/**
* Creates a new ASMEMFModel.
* @param name The model name. Not used by EMF.
* @param uri The model URI. EMF uses this to determine the correct factory.
* @param metamodel
* @param ml
* @return
* @throws Exception
* @author Dennis Wagelaar <[email protected]>
*/
public static ASMEMFModel newASMEMFModel(String name, String uri, ASMEMFModel metamodel, ModelLoader ml) throws Exception {
ASMEMFModel ret = null;
Resource extent = resourceSet.createResource(URI.createURI(uri));
ret = new ASMEMFModel(name, extent, metamodel, true, ml);
ret.unload = true;
return ret;
}
public static ASMEMFModel loadASMEMFModel(String name, ASMEMFModel metamodel, String url, ModelLoader ml) throws Exception {
ASMEMFModel ret = null;
if(url.startsWith("uri:")) {
String uri = url.substring(4);
EPackage pack = resourceSet.getPackageRegistry().getEPackage(uri);
if (pack == null) {
ret = new ASMEMFModel(name, null, metamodel, false, ml);
ret.resolveURI = uri;
} else {
Resource extent = pack.eResource();
ret = new ASMEMFModel(name, extent, metamodel, false, ml);
ret.addAllReferencedExtents();
}
} else {
ret = loadASMEMFModel(name, metamodel, URI.createURI(url), ml);
}
return ret;
}
public static ASMEMFModel loadASMEMFModel(String name, ASMEMFModel metamodel, URL url, ModelLoader ml) throws Exception {
ASMEMFModel ret = null;
ret = loadASMEMFModel(name, metamodel, url.openStream(), ml);
return ret;
}
public static ASMEMFModel loadASMEMFModel(String name, ASMEMFModel metamodel, URI uri, ModelLoader ml) throws Exception {
ASMEMFModel ret = null;
try {
Resource extent = resourceSet.createResource(uri);
extent.load(Collections.EMPTY_MAP);
// Resource extent = resourceSet.getResource(uri, true);
ret = new ASMEMFModel(name, extent, metamodel, true, ml);
ret.addAllReferencedExtents();
ret.setIsTarget(false);
ret.unload = true;
} catch(Exception e) {
e.printStackTrace();
}
adaptMetamodel(ret, metamodel);
return ret;
}
public static ASMEMFModel loadASMEMFModel(String name, ASMEMFModel metamodel, InputStream in, ModelLoader ml) throws Exception {
ASMEMFModel ret = newASMEMFModel(name, metamodel, ml);
try {
ret.getExtent().load(in, Collections.EMPTY_MAP);
ret.addAllReferencedExtents();
ret.unload = true;
} catch(Exception e) {
e.printStackTrace();
}
adaptMetamodel(ret, metamodel);
ret.setIsTarget(false);
return ret;
}
private static void adaptMetamodel(ASMEMFModel model, ASMEMFModel metamodel) {
if(metamodel == mofmm) {
for(Iterator i = model.getElementsByType("EPackage").iterator() ; i.hasNext() ; ) {
ASMEMFModelElement ame = (ASMEMFModelElement)i.next();
EPackage p = (EPackage)ame.getObject();
String nsURI = p.getNsURI();
if(nsURI == null) {
//System.err.println("DEBUG: EPackage " + p.getName() + " in model " + model.getName() + " has no nsURI.");
- nsURI = model.getName() ;//+ "_" + p.getName() ;//+ "_" + Double.toHexString((Math.random()));
+ nsURI = p.getName() ;
p.setNsURI(nsURI);
}
if (resourceSet.getPackageRegistry().containsKey(nsURI)) {
if (!p.equals(resourceSet.getPackageRegistry().getEPackage(nsURI))) {
//System.err.println("WARNING: overwriting local EMF registry entry for " + nsURI);
}
} else {
model.unregister.add(nsURI);
}
resourceSet.getPackageRegistry().put(nsURI, p);
//System.err.println("INFO: Registering " + nsURI + " in local EMF registry");
}
for(Iterator i = model.getElementsByType("EDataType").iterator() ; i.hasNext() ; ) {
ASMEMFModelElement ame = (ASMEMFModelElement)i.next();
String tname = ((ASMString)ame.get(null, "name")).getSymbol();
String icn = null;
if(tname.equals("Boolean")) {
icn = "boolean"; //"java.lang.Boolean";
} else if(tname.equals("Double")) {
icn = "java.lang.Double";
} else if(tname.equals("Float")) {
icn = "java.lang.Float";
} else if(tname.equals("Integer")) {
icn = "java.lang.Integer";
} else if(tname.equals("String")) {
icn = "java.lang.String";
}
if(icn != null)
ame.set(null, "instanceClassName", new ASMString(icn));
}
}
/*
reader.read(url.openStream(), url.toString(), ret.pack);
ret.getAllAcquaintances();
*/
}
public static ASMEMFModel createMOF(ModelLoader ml) {
if(mofmm == null) {
// Resource extent = resourceSet.createResource(URI.createURI("http://www.eclipse.org/emf/2002/Ecore"));
// System.out.println("Actual resource class: " + extent.getClass());
// extent.getContents().add(EcorePackage.eINSTANCE);
mofmm = new ASMEMFModel("MOF", EcorePackage.eINSTANCE.eResource(), null, false, ml);
}
return mofmm;
}
public Resource getExtent() {
if ((extent == null) && (resolveURI != null)) {
EPackage pack = resourceSet.getPackageRegistry().getEPackage(resolveURI);
extent = pack.eResource();
addAllReferencedExtents();
}
return extent;
}
static {
init();
}
private static void init() {
Map etfm = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap();
if(!etfm.containsKey("*")) {
etfm.put("*", new XMIResourceFactoryImpl());
}
// System.out.println(Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap());
// System.out.println(Resource.Factory.Registry.INSTANCE.getProtocolToFactoryMap());
resourceSet = new ResourceSetImpl();
}
public static ResourceSet getResourceSet() {
return resourceSet;
}
public boolean equals(Object o) {
return (o instanceof ASMEMFModel) && (((ASMEMFModel)o).extent == extent);
}
private static ResourceSet resourceSet;
private static ASMEMFModel mofmm = null;
private Resource extent;
private Set referencedExtents = new HashSet();
public boolean isCheckSameModel() {
return checkSameModel;
}
public void setCheckSameModel(boolean checkSameModel) {
this.checkSameModel = checkSameModel;
}
/**
* Searches for and adds all Resource extents that are
* referenced from the main extent to referencedExtents.
* @author Dennis Wagelaar <[email protected]>
*/
private void addAllReferencedExtents() {
Iterator contents = getExtent().getAllContents();
while (contents.hasNext()) {
Object o = contents.next();
if (o instanceof EClass) {
addReferencedExtentsFor((EClass)o, new HashSet());
}
}
referencedExtents.remove(getExtent());
}
/**
* Searches for and adds all Resource extents that are
* referenced from eClass to referencedExtents.
* @author Dennis Wagelaar <[email protected]>
* @param eClass
* @param ignore Set of classes to ignore for searching.
*/
private void addReferencedExtentsFor(EClass eClass, Set ignore) {
if (ignore.contains(eClass)) {
return;
}
ignore.add(eClass);
Iterator eRefs = eClass.getEReferences().iterator();
while (eRefs.hasNext()) {
EReference eRef = (EReference) eRefs.next();
if (eRef.isContainment()) {
EClassifier eType = eRef.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
System.err.println("WARNING: Resource for " +
eType.toString() + " is null; cannot be referenced");
}
if (eType instanceof EClass) {
addReferencedExtentsFor((EClass) eType, ignore);
}
}
}
Iterator eAtts = eClass.getEAttributes().iterator();
while (eAtts.hasNext()) {
EAttribute eAtt = (EAttribute) eAtts.next();
EClassifier eType = eAtt.getEType();
if (eType.eResource() != null) {
referencedExtents.add(eType.eResource());
} else {
System.err.println("WARNING: Resource for " +
eType.toString() + " is null; cannot be referenced");
}
}
Iterator eSupers = eClass.getESuperTypes().iterator();
while (eSupers.hasNext()) {
EClass eSuper = (EClass) eSupers.next();
if (eSuper.eResource() != null) {
referencedExtents.add(eSuper.eResource());
addReferencedExtentsFor(eSuper, ignore);
} else {
System.err.println("WARNING: Resource for " +
eSuper.toString() + " is null; cannot be referenced");
}
}
}
/**
* @return The set of referenced Resources.
*/
public Set getReferencedExtents() {
return referencedExtents;
}
}
| true | true | private static void adaptMetamodel(ASMEMFModel model, ASMEMFModel metamodel) {
if(metamodel == mofmm) {
for(Iterator i = model.getElementsByType("EPackage").iterator() ; i.hasNext() ; ) {
ASMEMFModelElement ame = (ASMEMFModelElement)i.next();
EPackage p = (EPackage)ame.getObject();
String nsURI = p.getNsURI();
if(nsURI == null) {
//System.err.println("DEBUG: EPackage " + p.getName() + " in model " + model.getName() + " has no nsURI.");
nsURI = model.getName() ;//+ "_" + p.getName() ;//+ "_" + Double.toHexString((Math.random()));
p.setNsURI(nsURI);
}
if (resourceSet.getPackageRegistry().containsKey(nsURI)) {
if (!p.equals(resourceSet.getPackageRegistry().getEPackage(nsURI))) {
//System.err.println("WARNING: overwriting local EMF registry entry for " + nsURI);
}
} else {
model.unregister.add(nsURI);
}
resourceSet.getPackageRegistry().put(nsURI, p);
//System.err.println("INFO: Registering " + nsURI + " in local EMF registry");
}
for(Iterator i = model.getElementsByType("EDataType").iterator() ; i.hasNext() ; ) {
ASMEMFModelElement ame = (ASMEMFModelElement)i.next();
String tname = ((ASMString)ame.get(null, "name")).getSymbol();
String icn = null;
if(tname.equals("Boolean")) {
icn = "boolean"; //"java.lang.Boolean";
} else if(tname.equals("Double")) {
icn = "java.lang.Double";
} else if(tname.equals("Float")) {
icn = "java.lang.Float";
} else if(tname.equals("Integer")) {
icn = "java.lang.Integer";
} else if(tname.equals("String")) {
icn = "java.lang.String";
}
if(icn != null)
ame.set(null, "instanceClassName", new ASMString(icn));
}
}
/*
reader.read(url.openStream(), url.toString(), ret.pack);
ret.getAllAcquaintances();
*/
}
| private static void adaptMetamodel(ASMEMFModel model, ASMEMFModel metamodel) {
if(metamodel == mofmm) {
for(Iterator i = model.getElementsByType("EPackage").iterator() ; i.hasNext() ; ) {
ASMEMFModelElement ame = (ASMEMFModelElement)i.next();
EPackage p = (EPackage)ame.getObject();
String nsURI = p.getNsURI();
if(nsURI == null) {
//System.err.println("DEBUG: EPackage " + p.getName() + " in model " + model.getName() + " has no nsURI.");
nsURI = p.getName() ;
p.setNsURI(nsURI);
}
if (resourceSet.getPackageRegistry().containsKey(nsURI)) {
if (!p.equals(resourceSet.getPackageRegistry().getEPackage(nsURI))) {
//System.err.println("WARNING: overwriting local EMF registry entry for " + nsURI);
}
} else {
model.unregister.add(nsURI);
}
resourceSet.getPackageRegistry().put(nsURI, p);
//System.err.println("INFO: Registering " + nsURI + " in local EMF registry");
}
for(Iterator i = model.getElementsByType("EDataType").iterator() ; i.hasNext() ; ) {
ASMEMFModelElement ame = (ASMEMFModelElement)i.next();
String tname = ((ASMString)ame.get(null, "name")).getSymbol();
String icn = null;
if(tname.equals("Boolean")) {
icn = "boolean"; //"java.lang.Boolean";
} else if(tname.equals("Double")) {
icn = "java.lang.Double";
} else if(tname.equals("Float")) {
icn = "java.lang.Float";
} else if(tname.equals("Integer")) {
icn = "java.lang.Integer";
} else if(tname.equals("String")) {
icn = "java.lang.String";
}
if(icn != null)
ame.set(null, "instanceClassName", new ASMString(icn));
}
}
/*
reader.read(url.openStream(), url.toString(), ret.pack);
ret.getAllAcquaintances();
*/
}
|
diff --git a/src/main/java/com/wormhole_xtreme/command/WXGo.java b/src/main/java/com/wormhole_xtreme/command/WXGo.java
index 954c51c..66e6f35 100644
--- a/src/main/java/com/wormhole_xtreme/command/WXGo.java
+++ b/src/main/java/com/wormhole_xtreme/command/WXGo.java
@@ -1,94 +1,102 @@
/**
* Wormhole X-Treme Plugin for Bukkit
* Copyright (C) 2011 Ben Echols
* Dean Bailey
*
* 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.wormhole_xtreme.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.wormhole_xtreme.WormholeXTreme;
import com.wormhole_xtreme.config.ConfigManager;
import com.wormhole_xtreme.config.ConfigManager.StringTypes;
import com.wormhole_xtreme.model.Stargate;
import com.wormhole_xtreme.model.StargateManager;
/**
* @author alron
*
*/
public class WXGo implements CommandExecutor {
/**
*
*/
public WXGo(WormholeXTreme wormholeXTreme) {
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
Player player = null;
if (!CommandUtlities.playerCheck(sender))
{
return true;
}
else
{
player = (Player)sender;
}
boolean allowed = false;
if ( player.isOp() || ( WormholeXTreme.Permissions != null && !ConfigManager.getSimplePermissions() && WormholeXTreme.Permissions.has(player, "wormhole.go"))
|| (WormholeXTreme.Permissions != null && ConfigManager.getSimplePermissions() && WormholeXTreme.Permissions.has(player, "wormhole.config")))
{
allowed = true;
}
if (allowed)
{
args = CommandUtlities.commandEscaper(args);
if ( args.length == 1)
{
String gogate = args[0].trim().replace("\n", "").replace("\r", "");
Stargate s = StargateManager.GetStargate(gogate);
- if ( s != null )
+ if ( s != null)
{
- player.teleportTo(s.TeleportLocation);
+ if (player.getWorld() != s.TeleportLocation.getWorld())
+ {
+ player.teleportTo(s.TeleportLocation.getWorld().getSpawnLocation());
+ player.teleportTo(s.TeleportLocation);
+ }
+ else
+ {
+ player.teleportTo(s.TeleportLocation);
+ }
}
else
{
player.sendMessage(ConfigManager.errorheader + "Gate does not exist: " + args[0]);
}
}
else
{
return false;
}
}
else
{
player.sendMessage(ConfigManager.output_strings.get(StringTypes.PERMISSION_NO));
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
Player player = null;
if (!CommandUtlities.playerCheck(sender))
{
return true;
}
else
{
player = (Player)sender;
}
boolean allowed = false;
if ( player.isOp() || ( WormholeXTreme.Permissions != null && !ConfigManager.getSimplePermissions() && WormholeXTreme.Permissions.has(player, "wormhole.go"))
|| (WormholeXTreme.Permissions != null && ConfigManager.getSimplePermissions() && WormholeXTreme.Permissions.has(player, "wormhole.config")))
{
allowed = true;
}
if (allowed)
{
args = CommandUtlities.commandEscaper(args);
if ( args.length == 1)
{
String gogate = args[0].trim().replace("\n", "").replace("\r", "");
Stargate s = StargateManager.GetStargate(gogate);
if ( s != null )
{
player.teleportTo(s.TeleportLocation);
}
else
{
player.sendMessage(ConfigManager.errorheader + "Gate does not exist: " + args[0]);
}
}
else
{
return false;
}
}
else
{
player.sendMessage(ConfigManager.output_strings.get(StringTypes.PERMISSION_NO));
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
Player player = null;
if (!CommandUtlities.playerCheck(sender))
{
return true;
}
else
{
player = (Player)sender;
}
boolean allowed = false;
if ( player.isOp() || ( WormholeXTreme.Permissions != null && !ConfigManager.getSimplePermissions() && WormholeXTreme.Permissions.has(player, "wormhole.go"))
|| (WormholeXTreme.Permissions != null && ConfigManager.getSimplePermissions() && WormholeXTreme.Permissions.has(player, "wormhole.config")))
{
allowed = true;
}
if (allowed)
{
args = CommandUtlities.commandEscaper(args);
if ( args.length == 1)
{
String gogate = args[0].trim().replace("\n", "").replace("\r", "");
Stargate s = StargateManager.GetStargate(gogate);
if ( s != null)
{
if (player.getWorld() != s.TeleportLocation.getWorld())
{
player.teleportTo(s.TeleportLocation.getWorld().getSpawnLocation());
player.teleportTo(s.TeleportLocation);
}
else
{
player.teleportTo(s.TeleportLocation);
}
}
else
{
player.sendMessage(ConfigManager.errorheader + "Gate does not exist: " + args[0]);
}
}
else
{
return false;
}
}
else
{
player.sendMessage(ConfigManager.output_strings.get(StringTypes.PERMISSION_NO));
}
return true;
}
|
diff --git a/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java b/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java
index b34d3b43..ded39d41 100644
--- a/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java
+++ b/src/main/java/com/metaweb/gridworks/browsing/facets/NumericBinIndex.java
@@ -1,102 +1,102 @@
package com.metaweb.gridworks.browsing.facets;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.metaweb.gridworks.expr.Evaluable;
import com.metaweb.gridworks.expr.ExpressionUtils;
import com.metaweb.gridworks.model.Cell;
import com.metaweb.gridworks.model.Project;
import com.metaweb.gridworks.model.Row;
public class NumericBinIndex {
private double _min;
private double _max;
private double _step;
private int[] _bins;
public NumericBinIndex(Project project, int cellIndex, Evaluable eval) {
Properties bindings = ExpressionUtils.createBindings(project);
_min = Double.POSITIVE_INFINITY;
_max = Double.NEGATIVE_INFINITY;
List<Double> allValues = new ArrayList<Double>();
for (int i = 0; i < project.rows.size(); i++) {
Row row = project.rows.get(i);
Cell cell = row.getCell(cellIndex);
ExpressionUtils.bind(bindings, row, cell);
Object value = eval.evaluate(bindings);
if (value != null) {
if (value.getClass().isArray()) {
Object[] a = (Object[]) value;
for (Object v : a) {
if (v instanceof Number) {
processValue(((Number) v).doubleValue(), allValues);
}
}
} else if (value instanceof Number) {
processValue(((Number) value).doubleValue(), allValues);
}
}
}
- if (getMin() >= getMax()) {
+ if (_min >= _max) {
_step = 0;
- _bins = new int[0];
+ _bins = new int[1];
return;
}
double diff = getMax() - getMin();
_step = 1;
if (diff > 10) {
while (getStep() * 100 < diff) {
_step *= 10;
}
} else {
while (getStep() * 100 > diff) {
_step /= 10;
}
}
_min = (Math.floor(_min / _step) * _step);
_max = (Math.ceil(_max / _step) * _step);
int binCount = 1 + (int) Math.ceil((getMax() - getMin()) / getStep());
if (binCount > 100) {
_step *= 2;
binCount = Math.round((1 + binCount) / 2);
}
_bins = new int[binCount];
for (double d : allValues) {
int bin = (int) Math.round((d - _min) / _step);
_bins[bin]++;
}
}
public double getMin() {
return _min;
}
public double getMax() {
return _max;
}
public double getStep() {
return _step;
}
public int[] getBins() {
return _bins;
}
protected void processValue(double v, List<Double> allValues) {
_min = Math.min(getMin(), v);
_max = Math.max(getMax(), v);
allValues.add(v);
}
}
| false | true | public NumericBinIndex(Project project, int cellIndex, Evaluable eval) {
Properties bindings = ExpressionUtils.createBindings(project);
_min = Double.POSITIVE_INFINITY;
_max = Double.NEGATIVE_INFINITY;
List<Double> allValues = new ArrayList<Double>();
for (int i = 0; i < project.rows.size(); i++) {
Row row = project.rows.get(i);
Cell cell = row.getCell(cellIndex);
ExpressionUtils.bind(bindings, row, cell);
Object value = eval.evaluate(bindings);
if (value != null) {
if (value.getClass().isArray()) {
Object[] a = (Object[]) value;
for (Object v : a) {
if (v instanceof Number) {
processValue(((Number) v).doubleValue(), allValues);
}
}
} else if (value instanceof Number) {
processValue(((Number) value).doubleValue(), allValues);
}
}
}
if (getMin() >= getMax()) {
_step = 0;
_bins = new int[0];
return;
}
double diff = getMax() - getMin();
_step = 1;
if (diff > 10) {
while (getStep() * 100 < diff) {
_step *= 10;
}
} else {
while (getStep() * 100 > diff) {
_step /= 10;
}
}
_min = (Math.floor(_min / _step) * _step);
_max = (Math.ceil(_max / _step) * _step);
int binCount = 1 + (int) Math.ceil((getMax() - getMin()) / getStep());
if (binCount > 100) {
_step *= 2;
binCount = Math.round((1 + binCount) / 2);
}
_bins = new int[binCount];
for (double d : allValues) {
int bin = (int) Math.round((d - _min) / _step);
_bins[bin]++;
}
}
| public NumericBinIndex(Project project, int cellIndex, Evaluable eval) {
Properties bindings = ExpressionUtils.createBindings(project);
_min = Double.POSITIVE_INFINITY;
_max = Double.NEGATIVE_INFINITY;
List<Double> allValues = new ArrayList<Double>();
for (int i = 0; i < project.rows.size(); i++) {
Row row = project.rows.get(i);
Cell cell = row.getCell(cellIndex);
ExpressionUtils.bind(bindings, row, cell);
Object value = eval.evaluate(bindings);
if (value != null) {
if (value.getClass().isArray()) {
Object[] a = (Object[]) value;
for (Object v : a) {
if (v instanceof Number) {
processValue(((Number) v).doubleValue(), allValues);
}
}
} else if (value instanceof Number) {
processValue(((Number) value).doubleValue(), allValues);
}
}
}
if (_min >= _max) {
_step = 0;
_bins = new int[1];
return;
}
double diff = getMax() - getMin();
_step = 1;
if (diff > 10) {
while (getStep() * 100 < diff) {
_step *= 10;
}
} else {
while (getStep() * 100 > diff) {
_step /= 10;
}
}
_min = (Math.floor(_min / _step) * _step);
_max = (Math.ceil(_max / _step) * _step);
int binCount = 1 + (int) Math.ceil((getMax() - getMin()) / getStep());
if (binCount > 100) {
_step *= 2;
binCount = Math.round((1 + binCount) / 2);
}
_bins = new int[binCount];
for (double d : allValues) {
int bin = (int) Math.round((d - _min) / _step);
_bins[bin]++;
}
}
|
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/issue/ignore/IgnoreIssuesConfiguration.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/issue/ignore/IgnoreIssuesConfiguration.java
index d1ac261f3b..d51360f98d 100644
--- a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/issue/ignore/IgnoreIssuesConfiguration.java
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/issue/ignore/IgnoreIssuesConfiguration.java
@@ -1,132 +1,132 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.core.issue.ignore;
import org.sonar.api.PropertyType;
import org.sonar.api.config.PropertyFieldDefinition;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.CoreProperties;
import com.google.common.collect.ImmutableList;
import org.sonar.api.config.PropertyDefinition;
import java.util.List;
public final class IgnoreIssuesConfiguration {
public static final String CONFIG_DOCUMENTATION_LINK = "More information on the "
+ "<a href=\"http://docs.codehaus.org/display/SONAR/Project+Administration#ProjectAdministration-IgnoringIssues\">Project Administration page</a>.<br/>";
public static final String SUB_CATEGORY_IGNORE_ISSUES = "issues";
public static final String CORE_KEY_PREFIX = "sonar.issue.ignore";
public static final String MULTICRITERIA_SUFFIX = ".multicriteria";
public static final String PATTERNS_MULTICRITERIA_KEY = CORE_KEY_PREFIX + MULTICRITERIA_SUFFIX;
public static final String RESOURCE_KEY = "resourceKey";
public static final String RULE_KEY = "ruleKey";
public static final String LINE_RANGE_KEY = "lineRange";
public static final String BLOCK_SUFFIX = ".block";
public static final String PATTERNS_BLOCK_KEY = CORE_KEY_PREFIX + BLOCK_SUFFIX;
public static final String BEGIN_BLOCK_REGEXP = "beginBlockRegexp";
public static final String END_BLOCK_REGEXP = "endBlockRegexp";
public static final String ALLFILE_SUFFIX = ".allfile";
public static final String PATTERNS_ALLFILE_KEY = CORE_KEY_PREFIX + ALLFILE_SUFFIX;
public static final String FILE_REGEXP = "fileRegexp";
private IgnoreIssuesConfiguration() {
// static configuration declaration only
}
static final int LARGE_SIZE = 40;
static final int SMALL_SIZE = 10;
public static List<PropertyDefinition> getPropertyDefinitions() {
return ImmutableList.of(
PropertyDefinition.builder(PATTERNS_MULTICRITERIA_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
- .name("Multi-criteria exclusion patterns")
+ .name("Multi-criteria Exclusion Patterns")
.description("Patterns used to identify which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(3)
.fields(
PropertyFieldDefinition.build(RESOURCE_KEY)
.name("File Path Pattern")
- .description("Pattern used to match files which should be ignored")
+ .description("Pattern used to match files which should be ignored.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(RULE_KEY)
.name("Rule Key Pattern")
- .description("Pattern used to match rules which should be ignored")
+ .description("Pattern used to match rules which should be ignored.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(LINE_RANGE_KEY)
.name("Line Range")
.description("Range of lines that should be ignored.")
.type(PropertyType.STRING)
.indicativeSize(SMALL_SIZE)
.build())
.build(),
PropertyDefinition.builder(PATTERNS_BLOCK_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
- .name("Block exclusion patterns")
+ .name("Block Exclusion Patterns")
.description("Patterns used to identify blocks in which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(2)
.fields(
PropertyFieldDefinition.build(BEGIN_BLOCK_REGEXP)
- .name("Regular expression for start of block")
+ .name("Regular Expression for Start of Block")
.description("If this regular expression is found in a file, then following lines are ignored until end of block.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(END_BLOCK_REGEXP)
- .name("Regular expression for end of block")
+ .name("Regular Expression for End of Block")
.description("If specified, this regular expression is used to determine the end of code blocks to ignore. If not, then block ends at the end of file.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build())
.build(),
PropertyDefinition.builder(PATTERNS_ALLFILE_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
- .name("File exclusion patterns")
+ .name("File Exclusion Patterns")
.description("Patterns used to identify files in which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(1)
.fields(
PropertyFieldDefinition.build(FILE_REGEXP)
- .name("Regular expression")
+ .name("Regular Expression")
.description("If this regular expression is found in a file, then the whole file is ignored.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build())
.build());
}
}
| false | true | public static List<PropertyDefinition> getPropertyDefinitions() {
return ImmutableList.of(
PropertyDefinition.builder(PATTERNS_MULTICRITERIA_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
.name("Multi-criteria exclusion patterns")
.description("Patterns used to identify which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(3)
.fields(
PropertyFieldDefinition.build(RESOURCE_KEY)
.name("File Path Pattern")
.description("Pattern used to match files which should be ignored")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(RULE_KEY)
.name("Rule Key Pattern")
.description("Pattern used to match rules which should be ignored")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(LINE_RANGE_KEY)
.name("Line Range")
.description("Range of lines that should be ignored.")
.type(PropertyType.STRING)
.indicativeSize(SMALL_SIZE)
.build())
.build(),
PropertyDefinition.builder(PATTERNS_BLOCK_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
.name("Block exclusion patterns")
.description("Patterns used to identify blocks in which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(2)
.fields(
PropertyFieldDefinition.build(BEGIN_BLOCK_REGEXP)
.name("Regular expression for start of block")
.description("If this regular expression is found in a file, then following lines are ignored until end of block.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(END_BLOCK_REGEXP)
.name("Regular expression for end of block")
.description("If specified, this regular expression is used to determine the end of code blocks to ignore. If not, then block ends at the end of file.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build())
.build(),
PropertyDefinition.builder(PATTERNS_ALLFILE_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
.name("File exclusion patterns")
.description("Patterns used to identify files in which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(1)
.fields(
PropertyFieldDefinition.build(FILE_REGEXP)
.name("Regular expression")
.description("If this regular expression is found in a file, then the whole file is ignored.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build())
.build());
}
| public static List<PropertyDefinition> getPropertyDefinitions() {
return ImmutableList.of(
PropertyDefinition.builder(PATTERNS_MULTICRITERIA_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
.name("Multi-criteria Exclusion Patterns")
.description("Patterns used to identify which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(3)
.fields(
PropertyFieldDefinition.build(RESOURCE_KEY)
.name("File Path Pattern")
.description("Pattern used to match files which should be ignored.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(RULE_KEY)
.name("Rule Key Pattern")
.description("Pattern used to match rules which should be ignored.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(LINE_RANGE_KEY)
.name("Line Range")
.description("Range of lines that should be ignored.")
.type(PropertyType.STRING)
.indicativeSize(SMALL_SIZE)
.build())
.build(),
PropertyDefinition.builder(PATTERNS_BLOCK_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
.name("Block Exclusion Patterns")
.description("Patterns used to identify blocks in which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(2)
.fields(
PropertyFieldDefinition.build(BEGIN_BLOCK_REGEXP)
.name("Regular Expression for Start of Block")
.description("If this regular expression is found in a file, then following lines are ignored until end of block.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build(),
PropertyFieldDefinition.build(END_BLOCK_REGEXP)
.name("Regular Expression for End of Block")
.description("If specified, this regular expression is used to determine the end of code blocks to ignore. If not, then block ends at the end of file.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build())
.build(),
PropertyDefinition.builder(PATTERNS_ALLFILE_KEY)
.category(CoreProperties.CATEGORY_EXCLUSIONS)
.subCategory(SUB_CATEGORY_IGNORE_ISSUES)
.name("File Exclusion Patterns")
.description("Patterns used to identify files in which issues are ignored.<br/>" +
CONFIG_DOCUMENTATION_LINK)
.onQualifiers(Qualifiers.PROJECT)
.index(1)
.fields(
PropertyFieldDefinition.build(FILE_REGEXP)
.name("Regular Expression")
.description("If this regular expression is found in a file, then the whole file is ignored.")
.type(PropertyType.STRING)
.indicativeSize(LARGE_SIZE)
.build())
.build());
}
|
diff --git a/src/com/cyprias/Lifestones/Lifestones.java b/src/com/cyprias/Lifestones/Lifestones.java
index bb72499..5af5665 100644
--- a/src/com/cyprias/Lifestones/Lifestones.java
+++ b/src/com/cyprias/Lifestones/Lifestones.java
@@ -1,430 +1,430 @@
package com.cyprias.Lifestones;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.mcstats.Metrics;
import com.cyprias.Lifestones.Config.lifestoneStructure;
import com.wimbli.WorldBorder.WorldBorder;
public class Lifestones extends JavaPlugin {
public static String chatPrefix = "�f[�aLs�f] ";
static String pluginName;
public Commands commands;
public Events events;
public HashMap<String, Double> playerProtections = new HashMap<String, Double>();
private WorldBorder wb;
private Logger log = Logger.getLogger("Minecraft");
public void onLoad() {
pluginName = getDescription().getName();
new Config(this);
Config.reloadOurConfig();
new Attunements(getServer());
new Database(this);
Database.createTables();
this.commands = new Commands(this);
this.events = new Events(this);
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
}
if (Config.checkForNewVersion == true)
VersionChecker.retreiveVersionInfo(this, "http://dev.bukkit.org/server-mods/lifestones/files.rss");
wb = (WorldBorder) getServer().getPluginManager().getPlugin("WorldBorder");
log.info(String.format("%s v%s is loaded.", pluginName, this.getDescription().getVersion()));
}
public static HashMap<String, String> locales = new HashMap<String, String>();
public void onEnable() {
Config.onEnable();
loadLocales();
loadAliases();
getCommand("lifestone").setExecutor(this.commands);
getCommand("lifestones").setExecutor(this.commands);
getServer().getPluginManager().registerEvents(this.events, this);
Attunements.onEnable();
Database.loadDatabases(Config.preferAsyncDBCalls);
log.info(String.format("%s v%s is enabled.", pluginName, this.getDescription().getVersion()));
}
public void onDisable() {
getCommand("lifestones").setExecutor(null);
events.unregisterEvents();
}
private void loadLocales(){
String localeDir = getDataFolder().separator + "locales" +getDataFolder().separator;
//Copy existing locales into plugin dir, so admin knows what's available.
new YML(getResource("enUS.yml"), getDataFolder(), localeDir + "enUS.yml", true);
new YML(getResource("ptBR.yml"), getDataFolder(), localeDir + "ptBR.yml", true);
//Copy any new locale strings to file on disk.
YML resLocale = new YML(getResource("enUS.yml"));
YML locale = new YML(getResource(Config.localeFile), getDataFolder(), localeDir+ Config.localeFile);
for (String key : resLocale.getKeys(false)) {
if (locale.get(key) == null){
info("Adding new locale " + key + " = " + resLocale.getString(key).replaceAll("(?i)&([a-k0-9])", "\u00A7$1"));
locale.set(key, resLocale.getString(key));
}
}
//Load locales into our hashmap.
locales.clear();
for (String key : locale.getKeys(false)) {
locales.put(key, locale.getString(key).replaceAll("(?i)&([a-k0-9])", "\u00A7$1"));// �
}
}
private void loadAliases(){
YML yml = new YML(getResource("aliases.yml"),getDataFolder(), "aliases.yml");
for (String key : yml.getKeys(false)) {
Events.aliases.put(key, yml.getString(key));
}
}
public void info(String msg) {
getServer().getConsoleSender().sendMessage(chatPrefix + msg);
}
public void debug(String msg) {
if (Config.debugMessages == true) {
info(ChatColor.DARK_GRAY + "[Debug] " + ChatColor.WHITE + msg);
}
}
//
public boolean hasPermission(CommandSender sender, String node) {
if (!(sender instanceof Player)) {
return true;
}
Player player = (Player) sender;
if (player.isPermissionSet(node)) // in case admin purposely set the
// node to false.
return player.hasPermission(node);
if (player.isPermissionSet(pluginName.toLowerCase() + ".*"))
return player.hasPermission(pluginName.toLowerCase() + ".*");
String[] temp = node.split("\\.");
String wildNode = temp[0];
for (int i = 1; i < (temp.length); i++) {
wildNode = wildNode + "." + temp[i];
if (player.isPermissionSet(wildNode + ".*"))
// plugin.info("wildNode1 " + wildNode+".*");
return player.hasPermission(wildNode + ".*");
}
return player.hasPermission(node);
}
public void sendMessage(CommandSender sender, String message, Boolean showConsole, Boolean sendPrefix) {
if (sender instanceof Player && showConsole == true) {
info("�e" + sender.getName() + "->�f" + message);
}
if (sendPrefix == true) {
sender.sendMessage(chatPrefix + message);
} else {
sender.sendMessage(message);
}
}
public void sendMessage(CommandSender sender, String message, Boolean showConsole) {
sendMessage(sender, message, showConsole, true);
}
public void sendMessage(CommandSender sender, String message) {
sendMessage(sender, message, true);
}
/**/
static public class lifestoneLoc {
String world;
int X, Y, Z;
public lifestoneLoc(String world, int X, int Y, int Z) {
this.world = world;
this.X = X;
this.Y = Y;
this.Z = Z;
}
}
public static double getUnixTime() {
return (System.currentTimeMillis() / 1000D);
}
public ArrayList<lifestoneLoc> lifestoneLocations = new ArrayList<lifestoneLoc>();
public void regsterLifestone(final lifestoneLoc lsLoc) {
for (int i = 0; i < lifestoneLocations.size(); i++) {
if (lifestoneLocations.get(i).world.equals(lsLoc.world)) {
if (lifestoneLocations.get(i).X == lsLoc.X && lifestoneLocations.get(i).Y == lsLoc.Y && lifestoneLocations.get(i).Z == lsLoc.Z) {
// info("LS already in aray...");
return;
}
}
}
lifestoneLocations.add(lsLoc);
debug("Registered LS at " + lsLoc.world + ", " + lsLoc.X + ", " + lsLoc.Y + ", " + lsLoc.Z);
// isLifestoneCache.clear();
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
cacheSurroundBlocks(lsLoc);
}
});
}
public static HashMap<Block, Block> isLifestoneCache = new HashMap<Block, Block>();
public static HashMap<Block, Block> isProtectedCache = new HashMap<Block, Block>();
public World getWorld(String worldName){
for (int i=0; i< getServer().getWorlds().size(); i++){
if (getServer().getWorlds().get(i).getName().equalsIgnoreCase(worldName)){
return getServer().getWorlds().get(i);
}
}
return null;
}
private void cacheSurroundBlocks(lifestoneLoc loc) {
World world = getWorld(loc.world);
if (world != null){
Block cBlock = world.getBlockAt(loc.X, loc.Y, loc.Z);
lifestoneStructure lsBlock;
for (int b = 0; b < Config.structureBlocks.size(); b++) {
lsBlock = Config.structureBlocks.get(b);
isLifestoneCache.put(world.getBlockAt(loc.X + lsBlock.rX, loc.Y + lsBlock.rY, loc.Z + lsBlock.rZ), cBlock);
// info("caching " + (loc.X+lsBlock.rX) +", " + (loc.Y+lsBlock.rY) +
// ", " + (loc.Z+lsBlock.rZ));
}
for (int y_iter = cBlock.getX() + Config.protectLifestoneRadius; y_iter > cBlock.getX() - Config.protectLifestoneRadius; y_iter--) {
for (int x_iter = cBlock.getY() + Config.protectLifestoneRadius; x_iter > cBlock.getY() - Config.protectLifestoneRadius; x_iter--) {
for (int z_iter = cBlock.getZ() + Config.protectLifestoneRadius; z_iter > cBlock.getZ() - Config.protectLifestoneRadius; z_iter--) {
isProtectedCache.put(world.getBlockAt(y_iter, x_iter, z_iter), cBlock);
// info("protecting " + y_iter +", " +x_iter + ", " +
// z_iter);
}
}
}
}
}
private void removeCachedSurroundBlocks(Player player, lifestoneLoc loc) {
Block cBlock = getServer().getWorld(loc.world).getBlockAt(loc.X, loc.Y, loc.Z);
lifestoneStructure lsBlock;
Block rBlock;
// for (int b=0; b<Config.structureBlocks.size();b++){
BlockPlaceEvent e;
for (int b = Config.structureBlocks.size() - 1; b >= 0; b--) {
lsBlock = Config.structureBlocks.get(b);
rBlock = getServer().getWorld(loc.world).getBlockAt(loc.X + lsBlock.rX, loc.Y + lsBlock.rY, loc.Z + lsBlock.rZ);
isLifestoneCache.remove(rBlock);
if (Config.setUnregisteredLifestonesToAir == true) {
if (Config.callBlockPlaceEvent == true){
e = new BlockPlaceEvent(rBlock, rBlock.getState(), cBlock, player.getItemInHand(), player, false);
e.getBlock().setTypeId(0);
player.getServer().getPluginManager().callEvent(e);
}
rBlock.setTypeId(0);
}
}
for (int y_iter = cBlock.getX() + Config.protectLifestoneRadius; y_iter > cBlock.getX() - Config.protectLifestoneRadius; y_iter--) {
for (int x_iter = cBlock.getY() + Config.protectLifestoneRadius; x_iter > cBlock.getY() - Config.protectLifestoneRadius; x_iter--) {
for (int z_iter = cBlock.getZ() + Config.protectLifestoneRadius; z_iter > cBlock.getZ() - Config.protectLifestoneRadius; z_iter--) {
isProtectedCache.remove(getServer().getWorld(loc.world).getBlockAt(y_iter, x_iter, z_iter));
// info("protecting " + y_iter +", " +x_iter + ", " +
// z_iter);
}
}
}
}
public void unregsterLifestone(Player player, final lifestoneLoc lsLoc) {
for (int i = 0; i < lifestoneLocations.size(); i++) {
if (lifestoneLocations.get(i).world.equals(lsLoc.world)) {
if (lifestoneLocations.get(i).X == lsLoc.X && lifestoneLocations.get(i).Y == lsLoc.Y && lifestoneLocations.get(i).Z == lsLoc.Z) {
lifestoneLocations.remove(i);
removeCachedSurroundBlocks(player, lsLoc);
return;
}
}
}
}
public Boolean isProtected(Block block) {
if (isProtectedCache.containsKey(block))
return true;
return false;
}
public Boolean isLifestone(Block block) {
if (isLifestoneCache.containsKey(block))
return true;
return false;
}
public Block getLifestoneCenterBlock(Block block) {
if (isLifestone(block)) {
return isLifestoneCache.get(block);
}
return null;
}
public Location getRandomLocation(World world, int fails){
int rad = Config.randomTPRadius;
double bX = 0;
double bZ = 0;
if (wb != null){
rad = wb.GetWorldBorder(world.getName()).getRadius();
bX = wb.GetWorldBorder(world.getName()).getX();
bZ = wb.GetWorldBorder(world.getName()).getZ();
}
- if (fails >= 0)
+ if (fails >= 10)
return null;
Double rX = (bX-rad) + (Math.random() * (rad*2));
Double rZ = (bZ-rad) + (Math.random() * (rad*2));
Block b = getTopBlock(world, (int) Math.round(rX), (int) Math.round(rZ));
if (b != null){
Location blockLoc;
switch (b.getTypeId()){
case 1:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 3, blockLoc.getBlockZ() + .5);
case 2:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 3:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 12:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 13:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 78:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 79:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 110:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 87:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 121:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
default:
return getRandomLocation(world, fails+1);
}
}
return null;
}
public Location getRandomLocation(World world){
return getRandomLocation(world, 0);
}
private Block getTopBlock(World world, int X, int Z){
Block b;
for (int i=255; i>0; i--){
b = world.getBlockAt(X, i, Z);
if (b.getTypeId() != 0){
//plugin.info("found" + b.getType() + " (" + b.getTypeId() + ")");
return b; //world.getBlockAt(X, i, Z);
}
}
return null;
}
public static boolean isInt(final String sInt) {
try {
Integer.parseInt(sInt);
} catch (NumberFormatException e) {
return false;
}
return true;
}
static public String L(String key) {
if (locales.containsKey(key))
return locales.get(key).toString();
return "MISSING LOCALE: " + ChatColor.RED + key;
}
static public String F(String key, Object... args) {
String value = L(key);
try {
if (value != null || args != null)
value = String.format(value, args); // arg.toString()
} catch (Exception e) {e.printStackTrace();
}
return value;
}
}
| true | true | public Location getRandomLocation(World world, int fails){
int rad = Config.randomTPRadius;
double bX = 0;
double bZ = 0;
if (wb != null){
rad = wb.GetWorldBorder(world.getName()).getRadius();
bX = wb.GetWorldBorder(world.getName()).getX();
bZ = wb.GetWorldBorder(world.getName()).getZ();
}
if (fails >= 0)
return null;
Double rX = (bX-rad) + (Math.random() * (rad*2));
Double rZ = (bZ-rad) + (Math.random() * (rad*2));
Block b = getTopBlock(world, (int) Math.round(rX), (int) Math.round(rZ));
if (b != null){
Location blockLoc;
switch (b.getTypeId()){
case 1:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 3, blockLoc.getBlockZ() + .5);
case 2:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 3:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 12:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 13:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 78:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 79:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 110:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 87:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 121:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
default:
return getRandomLocation(world, fails+1);
}
}
return null;
}
| public Location getRandomLocation(World world, int fails){
int rad = Config.randomTPRadius;
double bX = 0;
double bZ = 0;
if (wb != null){
rad = wb.GetWorldBorder(world.getName()).getRadius();
bX = wb.GetWorldBorder(world.getName()).getX();
bZ = wb.GetWorldBorder(world.getName()).getZ();
}
if (fails >= 10)
return null;
Double rX = (bX-rad) + (Math.random() * (rad*2));
Double rZ = (bZ-rad) + (Math.random() * (rad*2));
Block b = getTopBlock(world, (int) Math.round(rX), (int) Math.round(rZ));
if (b != null){
Location blockLoc;
switch (b.getTypeId()){
case 1:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 3, blockLoc.getBlockZ() + .5);
case 2:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 3:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 12:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 13:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 78:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 79:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 110:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 87:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
case 121:
blockLoc = b.getLocation();
return new Location(world, blockLoc.getBlockX() + .5, blockLoc.getBlockY() + 2, blockLoc.getBlockZ() + .5);
default:
return getRandomLocation(world, fails+1);
}
}
return null;
}
|
diff --git a/servers/sip-servlets/sip-servlets-management/src/main/java/org/mobicents/servlet/management/server/deploy/DeploymentServiceImpl.java b/servers/sip-servlets/sip-servlets-management/src/main/java/org/mobicents/servlet/management/server/deploy/DeploymentServiceImpl.java
index de35e1818..003f4170f 100644
--- a/servers/sip-servlets/sip-servlets-management/src/main/java/org/mobicents/servlet/management/server/deploy/DeploymentServiceImpl.java
+++ b/servers/sip-servlets/sip-servlets-management/src/main/java/org/mobicents/servlet/management/server/deploy/DeploymentServiceImpl.java
@@ -1,87 +1,89 @@
package org.mobicents.servlet.management.server.deploy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import org.mobicents.servlet.management.client.deploy.DeploymentService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class DeploymentServiceImpl extends RemoteServiceServlet implements DeploymentService{
private static String[] appExtensions = {"war", "sar", "sar2", "ear"};
public void deploy(String application) {
String serverHome = System.getProperty("jboss.server.home.dir");
String jbossHome = System.getProperty("jboss.home.dir");
String appToDeploy = jbossHome + "/examples/" + application;
String deployFolder = serverHome + "/deploy/";
String targetFile = deployFolder + application;
copyFile(appToDeploy, targetFile);
}
public String[] getApplications(String directory) {
String serverHome = System.getProperty("jboss.server.home.dir");
String jbossHome = System.getProperty("jboss.home.dir");
String deployFolder = serverHome + "/deploy/";
String examplesFolder = jbossHome + "/examples/";
String folder = null;
if(directory.equals("examples")) {
folder = examplesFolder;
} else {
folder = deployFolder;
}
ArrayList<String> result = new ArrayList<String>();
File root = new File(folder);
File[] files = root.listFiles();
- for(int q=0; q<files.length; q++) {
- File file = files[q];
- String fileName = file.getName();
- boolean isApp = false;
- for(String ext: appExtensions) {
- if(fileName.endsWith(ext)) {
- isApp = true;
- break;
+ if(files != null) {
+ for(int q=0; q<files.length; q++) {
+ File file = files[q];
+ String fileName = file.getName();
+ boolean isApp = false;
+ for(String ext: appExtensions) {
+ if(fileName.endsWith(ext)) {
+ isApp = true;
+ break;
+ }
+ }
+ if(isApp)
+ {
+ result.add(fileName);
}
- }
- if(isApp)
- {
- result.add(fileName);
}
}
return result.toArray(new String[]{});
}
private static boolean copyFile(String from, String to){
try {
File f1 = new File(from);
File f2 = new File(to);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[10000];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
}
catch(Exception ex){
return false;
}
return true;
}
public boolean isJBoss() {
String serverHome = System.getProperty("jboss.server.home.dir");
if(serverHome != null) return true;
return false;
}
}
| false | true | public String[] getApplications(String directory) {
String serverHome = System.getProperty("jboss.server.home.dir");
String jbossHome = System.getProperty("jboss.home.dir");
String deployFolder = serverHome + "/deploy/";
String examplesFolder = jbossHome + "/examples/";
String folder = null;
if(directory.equals("examples")) {
folder = examplesFolder;
} else {
folder = deployFolder;
}
ArrayList<String> result = new ArrayList<String>();
File root = new File(folder);
File[] files = root.listFiles();
for(int q=0; q<files.length; q++) {
File file = files[q];
String fileName = file.getName();
boolean isApp = false;
for(String ext: appExtensions) {
if(fileName.endsWith(ext)) {
isApp = true;
break;
}
}
if(isApp)
{
result.add(fileName);
}
}
return result.toArray(new String[]{});
}
| public String[] getApplications(String directory) {
String serverHome = System.getProperty("jboss.server.home.dir");
String jbossHome = System.getProperty("jboss.home.dir");
String deployFolder = serverHome + "/deploy/";
String examplesFolder = jbossHome + "/examples/";
String folder = null;
if(directory.equals("examples")) {
folder = examplesFolder;
} else {
folder = deployFolder;
}
ArrayList<String> result = new ArrayList<String>();
File root = new File(folder);
File[] files = root.listFiles();
if(files != null) {
for(int q=0; q<files.length; q++) {
File file = files[q];
String fileName = file.getName();
boolean isApp = false;
for(String ext: appExtensions) {
if(fileName.endsWith(ext)) {
isApp = true;
break;
}
}
if(isApp)
{
result.add(fileName);
}
}
}
return result.toArray(new String[]{});
}
|
diff --git a/src/org/thoughtcrime/securesms/service/MmsListener.java b/src/org/thoughtcrime/securesms/service/MmsListener.java
index d5250891d..c5a8efc9c 100644
--- a/src/org/thoughtcrime/securesms/service/MmsListener.java
+++ b/src/org/thoughtcrime/securesms/service/MmsListener.java
@@ -1,93 +1,93 @@
/**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationPreferencesActivity;
import org.thoughtcrime.securesms.protocol.WirePrefix;
import org.thoughtcrime.securesms.util.Util;
import ws.com.google.android.mms.pdu.GenericPdu;
import ws.com.google.android.mms.pdu.NotificationInd;
import ws.com.google.android.mms.pdu.PduHeaders;
import ws.com.google.android.mms.pdu.PduParser;
public class MmsListener extends BroadcastReceiver {
private boolean isRelevant(Context context, Intent intent) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.DONUT) {
return false;
}
if (!ApplicationMigrationService.isDatabaseImported(context)) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) &&
Util.isDefaultSmsProvider(context))
{
return false;
}
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT &&
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ||
PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(ApplicationPreferencesActivity.ALL_MMS_PERF, true))
{
return true;
}
byte[] mmsData = intent.getByteArrayExtra("data");
PduParser parser = new PduParser(mmsData);
GenericPdu pdu = parser.parse();
if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND)
return false;
NotificationInd notificationPdu = (NotificationInd)pdu;
if (notificationPdu.getSubject() == null)
return false;
return WirePrefix.isEncryptedMmsSubject(notificationPdu.getSubject().getString());
}
@Override
public void onReceive(Context context, Intent intent) {
Log.w("MmsListener", "Got MMS broadcast..." + intent.getAction());
if (isRelevant(context, intent)) {
Log.w("MmsListener", "Relevant!");
intent.setAction(SendReceiveService.RECEIVE_MMS_ACTION);
intent.putExtra("ResultCode", this.getResultCode());
intent.setClass(context, SendReceiveService.class);
context.startService(intent);
abortBroadcast();
}
}
}
| true | true | private boolean isRelevant(Context context, Intent intent) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.DONUT) {
return false;
}
if (!ApplicationMigrationService.isDatabaseImported(context)) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) &&
Util.isDefaultSmsProvider(context))
{
return false;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT &&
PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(ApplicationPreferencesActivity.ALL_MMS_PERF, true))
{
return true;
}
byte[] mmsData = intent.getByteArrayExtra("data");
PduParser parser = new PduParser(mmsData);
GenericPdu pdu = parser.parse();
if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND)
return false;
NotificationInd notificationPdu = (NotificationInd)pdu;
if (notificationPdu.getSubject() == null)
return false;
return WirePrefix.isEncryptedMmsSubject(notificationPdu.getSubject().getString());
}
| private boolean isRelevant(Context context, Intent intent) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.DONUT) {
return false;
}
if (!ApplicationMigrationService.isDatabaseImported(context)) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) &&
Util.isDefaultSmsProvider(context))
{
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ||
PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(ApplicationPreferencesActivity.ALL_MMS_PERF, true))
{
return true;
}
byte[] mmsData = intent.getByteArrayExtra("data");
PduParser parser = new PduParser(mmsData);
GenericPdu pdu = parser.parse();
if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND)
return false;
NotificationInd notificationPdu = (NotificationInd)pdu;
if (notificationPdu.getSubject() == null)
return false;
return WirePrefix.isEncryptedMmsSubject(notificationPdu.getSubject().getString());
}
|
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/ManagePagePreprocessor.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/ManagePagePreprocessor.java
index 29077de2c..31063bf39 100644
--- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/ManagePagePreprocessor.java
+++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/preprocessors/ManagePagePreprocessor.java
@@ -1,373 +1,378 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.BaseEditSubmissionPreprocessorVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.MultiValueEditSubmission;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfigurationConstants;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.ManagePageGenerator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessDataGetterN3;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessDataGetterN3Utils;
public class ManagePagePreprocessor extends
BaseEditSubmissionPreprocessorVTwo {
protected static final Log log = LogFactory
.getLog(ManagePagePreprocessor.class.getName());
private static MultiValueEditSubmission submission = null;
private static EditConfigurationVTwo editConfiguration = null;
private static Map<String, List<String>> transformedLiteralsFromForm = null;
private static Map<String, List<String>> urisFromForm = null;
private static List<String> pageContentUnits = null;//String submission from form
private static List<JSONObject> pageContentUnitsJSON = null;//converted to JSON objects that can be read
// String datatype
// Will be editing the edit configuration as well as edit submission here
public ManagePagePreprocessor(EditConfigurationVTwo editConfig) {
super(editConfig);
editConfiguration = editConfig;
}
public void preprocess(MultiValueEditSubmission inputSubmission) {
submission = inputSubmission;
// Get the input elements for concept node and concept label as well
// as vocab uri (which is based on thge
// For query parameters, check whether CUI
copySubmissionValues();
processDataGetters();
//In case of edit, need to force deletion of existing values where necessary
//In our case, values that already exist and will be overwritten will be in submission already
//just as new values will
//Anything left over should be replaced with blank value sentinel as that would
//no longer be on the form and have a value submitted and we can delete that statement
//if it exists
processExistingValues();
}
//Since we will change the uris and literals from form, we should make copies
//of the original values and store them, this will also make iterations
//and updates to the submission independent from accessing the values
private void copySubmissionValues() {
Map<String, List<Literal>> literalsFromForm = submission.getLiteralsFromForm();
transformedLiteralsFromForm = copyMap(EditConfigurationUtils.transformLiteralMap(literalsFromForm));
urisFromForm = copyMap(submission.getUrisFromForm());
pageContentUnits = transformedLiteralsFromForm.get("pageContentUnit");
}
private Map<String, List<String>> copyMap(
Map<String, List<String>> originalMap) {
Map<String, List<String>> copyMap = new HashMap<String, List<String>>();
copyMap.putAll(originalMap);
return copyMap;
}
private void processExistingValues() {
//For all literals that were originally in scope that don't have values on the form
//anymore, replace with null value
//For those literals, those values will be replaced with form values where overwritten
//And will be deleted where not overwritten which is the behavior we desire
if(this.editConfiguration.isParamUpdate()) {
Map<String, List<Literal>> literalsInScope = this.editConfiguration.getLiteralsInScope();
Map<String, List<String>> urisInScope = this.editConfiguration.getUrisInScope();
List<String> literalKeys = new ArrayList<String>(literalsInScope.keySet());
List<String> uriKeys = new ArrayList<String>(urisInScope.keySet());
for(String literalName: literalKeys) {
//if submission already has value for this, then leave be
//otherwise replace with null which will not be valid N3
//TODO: Replace with better solution for forcing literal deletion
boolean haslv = submission.hasLiteralValue(literalName);
if(!submission.hasLiteralValue(literalName)) {
submission.addLiteralToForm(editConfiguration,
editConfiguration.getField(literalName),
literalName,
(new String[] {null}));
}
}
for(String uriName: uriKeys) {
//these values should never be overwritten or deleted
//if(uriName != "page" && uriName != "menuItem" && !uriName.startsWith("dataGetter")) {
if(uriName != "page") {
boolean hasuv = submission.hasUriValue(uriName);
if(!submission.hasUriValue(uriName)) {
submission.addUriToForm(editConfiguration,
uriName,
(new String[] {EditConfigurationConstants.BLANK_SENTINEL}));
}
}
}
}
}
private void processDataGetters() {
convertToJson();
int counter = 0;
for(JSONObject jsonObject:pageContentUnitsJSON) {
String dataGetterClass = getDataGetterClass(jsonObject);
ProcessDataGetterN3 pn = ProcessDataGetterN3Utils.getDataGetterProcessorN3(dataGetterClass, jsonObject);
//Removing n3 required b/c retracts in edit case depend on both n3 required and n3 optional
//To not muddle up logic, we will just add ALL required and optional statements
//from data getters directly to N3 optional
//Add n3 required
//addN3Required(pn, counter);
//Add N3 Optional as well
addN3Optional(pn, counter);
// Add URIs on Form and Add Literals On Form
addLiteralsAndUrisOnForm(pn, counter);
// Add fields
addFields(pn, counter);
//Add new resources - data getters need to be new resources
addNewResources(pn, counter);
//Add input values to submission
addInputsToSubmission(pn, counter, jsonObject);
counter++;
}
}
private void addNewResources(ProcessDataGetterN3 pn, int counter) {
// TODO Auto-generated method stub
List<String> newResources = pn.getNewResources(counter);
for(String newResource:newResources) {
//Will null get us display vocabulary or something else?
editConfiguration.addNewResource(newResource, null);
//Weirdly enough, the defaultDisplayNS doesn't act as a namespace REALLY
//as it first gets assigned as the URI itself and this lead to an error
//instead of repetitively trying to get another URI
//editConfiguration.addNewResource(newResource, ManagePageGenerator.defaultDisplayNs );
}
}
private void convertToJson() {
//Iterate through list of inputs
pageContentUnitsJSON = new ArrayList<JSONObject>();
//page content units might return null in case self-contained template is selected
//otherwise there should be page content units returned from the form
if(pageContentUnits != null) {
for(String pageContentUnit: pageContentUnits) {
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( pageContentUnit );
pageContentUnitsJSON.add(jsonObject);
}
}
}
//This is where the actual values will be submitted as if they were separate input fields
//Each field name will correspond to the names of the fileds/uris on form/literals on form
//generated here
private void addInputsToSubmission(ProcessDataGetterN3 pn, int counter, JSONObject jsonObject) {
List<String> literalLabels = pn.getLiteralVarNamesBase();
List<String> uriLabels = pn.getUriVarNamesBase();
for(String literalLabel:literalLabels) {
List<String> literalValues = new ArrayList<String>();
Object jsonValue = jsonObject.get(literalLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionLiteralName = pn.getVarName(literalLabel, counter);
//Single value
if(jsonValue instanceof String) {
//TODO: Deal with multiple submission values
//This retrieves the value for this particular json object
String jsonString = jsonObject.getString(literalLabel);
jsonString = pn.replaceEncodedQuotesWithEscapedQuotes(jsonString);
literalValues.add(jsonString);
} else if(jsonValue instanceof JSONArray) {
JSONArray values = jsonObject.getJSONArray(literalLabel);
literalValues = (List<String>) JSONSerializer.toJava(values);
//Replacing encoded quotes here as well
this.replaceEncodedQuotesInList(pn, literalValues);
} else if(jsonValue instanceof Boolean) {
Boolean booleanValue = jsonObject.getBoolean(literalLabel);
//Adds string version
literalValues.add(booleanValue.toString());
}
String[] literalValuesSubmission = new String[literalValues.size()];
literalValuesSubmission = literalValues.toArray(literalValuesSubmission);
//This adds literal, connecting the field with
submission.addLiteralToForm(editConfiguration,
editConfiguration.getField(submissionLiteralName),
submissionLiteralName,
literalValuesSubmission);
}
for(String uriLabel:uriLabels) {
List<String> uriValues = new ArrayList<String>();
Object jsonValue = jsonObject.get(uriLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionUriName = pn.getVarName(uriLabel, counter);
//if single value, then, add to values
if(jsonValue instanceof String) {
//Var names will depend on which data getter object this is on the page, so depends on counter
//This retrieves the value for this particular json object and adds to list
uriValues.add(jsonObject.getString(uriLabel));
} else if(jsonValue instanceof JSONArray) {
//multiple values
JSONArray values = jsonObject.getJSONArray(uriLabel);
uriValues = (List<String>) JSONSerializer.toJava(values);
} else {
//This may include JSON Objects but no way to deal with these right now
}
String[] uriValuesSubmission = new String[uriValues.size()];
uriValuesSubmission = uriValues.toArray(uriValuesSubmission);
//This adds literal, connecting the field with the value
submission.addUriToForm(editConfiguration, submissionUriName, uriValuesSubmission);
}
//To get data getter uris, check if editing an existing set and include those as form inputs
if(editConfiguration.isParamUpdate()) {
- String URIValue = jsonObject.getString("URI");
- if(URIValue != null) {
- String dataGetterURISubmissionName = pn.getDataGetterVarName(counter);
- submission.addUriToForm(editConfiguration, dataGetterURISubmissionName, new String[]{URIValue});
+ //Although this is editing an existing page, new content might have been added which would not include
+ //existing data getter URIs, so important to check whether the key exists within the json object in the first place
+ if(jsonObject.containsKey("URI")) {
+ String URIValue = jsonObject.getString("URI");
+ if(URIValue != null) {
+ log.debug("Existing URI for data getter found: " + URIValue);
+ String dataGetterURISubmissionName = pn.getDataGetterVarName(counter);
+ submission.addUriToForm(editConfiguration, dataGetterURISubmissionName, new String[]{URIValue});
+ }
}
}
}
private void replaceEncodedQuotesInList(ProcessDataGetterN3 pn, List<String> values) {
int i;
int len = values.size();
for(i = 0; i < len; i++) {
String value = values.get(i);
if(value.contains(""") || value.contains("'")) {
value = pn.replaceEncodedQuotesWithEscapedQuotes(value);
values.set(i,value);
}
}
}
private void addFields(ProcessDataGetterN3 pn, int counter) {
List<FieldVTwo> fields = pn.retrieveFields(counter);
//Check if fields don't already exist in case of editing
Map<String, FieldVTwo> existingFields = editConfiguration.getFields();
for(FieldVTwo newField: fields) {
String newFieldName = newField.getName();
//if not already in list and about the same
if(existingFields.containsKey(newFieldName)) {
FieldVTwo existingField = existingFields.get(newFieldName);
if(existingField.isEqualTo(newField)) {
log.debug("This field already exists and so will not be added:" + newFieldName);
} else {
log.error("The field with the same name is different and will not be added as a different field exists which is different:" + newFieldName);
}
} else {
editConfiguration.addField(newField);
}
}
}
//original literals on form: label, uris on form: conceptNode and conceptSource
//This will overwrite the original values in the edit configuration
private void addLiteralsAndUrisOnForm(ProcessDataGetterN3 pn, int counter) {
List<String> literalsOnForm = pn.retrieveLiteralsOnForm(counter);
editConfiguration.addLiteralsOnForm(literalsOnForm);
List<String> urisOnForm = pn.retrieveUrisOnForm(counter);
editConfiguration.addUrisOnForm(urisOnForm);
}
// N3 being reproduced
/*
* ?subject ?predicate ?conceptNode .
*/
//NOT Using this right now
//This will overwrite the original with the set of new n3 required
/*
private void addN3Required(ProcessDataGetterN3 pn, int counter) {
//Use the process utils to figure out what class required to retrieve the N3 required
List<String> requiredList = pn.retrieveN3Required(counter);
//Add connection between data getter and page
requiredList.addAll(getPageToDataGetterN3(pn, counter));
if(requiredList != null) {
editConfiguration.addN3Required(requiredList);
}
}*/
private List<String> getPageToDataGetterN3(
ProcessDataGetterN3 pn, int counter) {
String dataGetterVar = pn.getDataGetterVar(counter);
//Put this method in the generator but can be put elsewhere
String pageToDataGetterN3 = ManagePageGenerator.getDataGetterN3(dataGetterVar);
return Arrays.asList(pageToDataGetterN3);
}
//Add n3 optional
private void addN3Optional(ProcessDataGetterN3 pn, int counter) {
List<String> addList = new ArrayList<String>();
//Get required list
List<String> requiredList = pn.retrieveN3Required(counter);
//Add connection between data getter and page
requiredList.addAll(getPageToDataGetterN3(pn, counter));
//get optional n3
List<String> optionalList = pn.retrieveN3Optional(counter);
if(requiredList != null) {
addList.addAll(requiredList);
}
if(optionalList != null) {
addList.addAll(optionalList);
}
editConfiguration.addN3Optional(addList);
}
//Each JSON Object will indicate the type of the data getter within it
private String getDataGetterClass(JSONObject jsonObject) {
String javaURI = jsonObject.getString("dataGetterClass");
return getQualifiedDataGetterName(javaURI);
}
//Get rid of java: in front of class name
private String getQualifiedDataGetterName(String dataGetterTypeURI) {
String javaURI = "java:";
if(dataGetterTypeURI.startsWith(javaURI)) {
int beginIndex = javaURI.length();
return dataGetterTypeURI.substring(beginIndex);
}
return dataGetterTypeURI;
}
}
| true | true | private void addInputsToSubmission(ProcessDataGetterN3 pn, int counter, JSONObject jsonObject) {
List<String> literalLabels = pn.getLiteralVarNamesBase();
List<String> uriLabels = pn.getUriVarNamesBase();
for(String literalLabel:literalLabels) {
List<String> literalValues = new ArrayList<String>();
Object jsonValue = jsonObject.get(literalLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionLiteralName = pn.getVarName(literalLabel, counter);
//Single value
if(jsonValue instanceof String) {
//TODO: Deal with multiple submission values
//This retrieves the value for this particular json object
String jsonString = jsonObject.getString(literalLabel);
jsonString = pn.replaceEncodedQuotesWithEscapedQuotes(jsonString);
literalValues.add(jsonString);
} else if(jsonValue instanceof JSONArray) {
JSONArray values = jsonObject.getJSONArray(literalLabel);
literalValues = (List<String>) JSONSerializer.toJava(values);
//Replacing encoded quotes here as well
this.replaceEncodedQuotesInList(pn, literalValues);
} else if(jsonValue instanceof Boolean) {
Boolean booleanValue = jsonObject.getBoolean(literalLabel);
//Adds string version
literalValues.add(booleanValue.toString());
}
String[] literalValuesSubmission = new String[literalValues.size()];
literalValuesSubmission = literalValues.toArray(literalValuesSubmission);
//This adds literal, connecting the field with
submission.addLiteralToForm(editConfiguration,
editConfiguration.getField(submissionLiteralName),
submissionLiteralName,
literalValuesSubmission);
}
for(String uriLabel:uriLabels) {
List<String> uriValues = new ArrayList<String>();
Object jsonValue = jsonObject.get(uriLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionUriName = pn.getVarName(uriLabel, counter);
//if single value, then, add to values
if(jsonValue instanceof String) {
//Var names will depend on which data getter object this is on the page, so depends on counter
//This retrieves the value for this particular json object and adds to list
uriValues.add(jsonObject.getString(uriLabel));
} else if(jsonValue instanceof JSONArray) {
//multiple values
JSONArray values = jsonObject.getJSONArray(uriLabel);
uriValues = (List<String>) JSONSerializer.toJava(values);
} else {
//This may include JSON Objects but no way to deal with these right now
}
String[] uriValuesSubmission = new String[uriValues.size()];
uriValuesSubmission = uriValues.toArray(uriValuesSubmission);
//This adds literal, connecting the field with the value
submission.addUriToForm(editConfiguration, submissionUriName, uriValuesSubmission);
}
//To get data getter uris, check if editing an existing set and include those as form inputs
if(editConfiguration.isParamUpdate()) {
String URIValue = jsonObject.getString("URI");
if(URIValue != null) {
String dataGetterURISubmissionName = pn.getDataGetterVarName(counter);
submission.addUriToForm(editConfiguration, dataGetterURISubmissionName, new String[]{URIValue});
}
}
}
| private void addInputsToSubmission(ProcessDataGetterN3 pn, int counter, JSONObject jsonObject) {
List<String> literalLabels = pn.getLiteralVarNamesBase();
List<String> uriLabels = pn.getUriVarNamesBase();
for(String literalLabel:literalLabels) {
List<String> literalValues = new ArrayList<String>();
Object jsonValue = jsonObject.get(literalLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionLiteralName = pn.getVarName(literalLabel, counter);
//Single value
if(jsonValue instanceof String) {
//TODO: Deal with multiple submission values
//This retrieves the value for this particular json object
String jsonString = jsonObject.getString(literalLabel);
jsonString = pn.replaceEncodedQuotesWithEscapedQuotes(jsonString);
literalValues.add(jsonString);
} else if(jsonValue instanceof JSONArray) {
JSONArray values = jsonObject.getJSONArray(literalLabel);
literalValues = (List<String>) JSONSerializer.toJava(values);
//Replacing encoded quotes here as well
this.replaceEncodedQuotesInList(pn, literalValues);
} else if(jsonValue instanceof Boolean) {
Boolean booleanValue = jsonObject.getBoolean(literalLabel);
//Adds string version
literalValues.add(booleanValue.toString());
}
String[] literalValuesSubmission = new String[literalValues.size()];
literalValuesSubmission = literalValues.toArray(literalValuesSubmission);
//This adds literal, connecting the field with
submission.addLiteralToForm(editConfiguration,
editConfiguration.getField(submissionLiteralName),
submissionLiteralName,
literalValuesSubmission);
}
for(String uriLabel:uriLabels) {
List<String> uriValues = new ArrayList<String>();
Object jsonValue = jsonObject.get(uriLabel);
//Var names will depend on which data getter object this is on the page, so depends on counter
String submissionUriName = pn.getVarName(uriLabel, counter);
//if single value, then, add to values
if(jsonValue instanceof String) {
//Var names will depend on which data getter object this is on the page, so depends on counter
//This retrieves the value for this particular json object and adds to list
uriValues.add(jsonObject.getString(uriLabel));
} else if(jsonValue instanceof JSONArray) {
//multiple values
JSONArray values = jsonObject.getJSONArray(uriLabel);
uriValues = (List<String>) JSONSerializer.toJava(values);
} else {
//This may include JSON Objects but no way to deal with these right now
}
String[] uriValuesSubmission = new String[uriValues.size()];
uriValuesSubmission = uriValues.toArray(uriValuesSubmission);
//This adds literal, connecting the field with the value
submission.addUriToForm(editConfiguration, submissionUriName, uriValuesSubmission);
}
//To get data getter uris, check if editing an existing set and include those as form inputs
if(editConfiguration.isParamUpdate()) {
//Although this is editing an existing page, new content might have been added which would not include
//existing data getter URIs, so important to check whether the key exists within the json object in the first place
if(jsonObject.containsKey("URI")) {
String URIValue = jsonObject.getString("URI");
if(URIValue != null) {
log.debug("Existing URI for data getter found: " + URIValue);
String dataGetterURISubmissionName = pn.getDataGetterVarName(counter);
submission.addUriToForm(editConfiguration, dataGetterURISubmissionName, new String[]{URIValue});
}
}
}
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index 6b4d3f4a..d9017dab 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1244 +1,1239 @@
/*
* Copyright (C) 2008 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.launcher2;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private boolean mBeforeFirstLoad = true;
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList = new AllAppsList();
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindPackageAdded(ArrayList<ApplicationInfo> apps);
public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps);
public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps);
}
LauncherModel(LauncherApplication app) {
mApp = app;
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
- boolean update = false;
- boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
- update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
- remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
- update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
- if (update || modified != null) {
+ if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
- if (remove || removed != null) {
+ if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
if (itemType
!= LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info.title = c.getString(titleIndex);
}
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| false | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
if (itemType
!= LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info.title = c.getString(titleIndex);
}
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
if (itemType
!= LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info.title = c.getString(titleIndex);
}
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
|
diff --git a/src/main/java/framework/utils/RecipeInstaller.java b/src/main/java/framework/utils/RecipeInstaller.java
index 4c991e8d..92c73372 100644
--- a/src/main/java/framework/utils/RecipeInstaller.java
+++ b/src/main/java/framework/utils/RecipeInstaller.java
@@ -1,261 +1,261 @@
package framework.utils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import test.cli.cloudify.CommandTestUtils;
import test.cli.cloudify.security.SecurityConstants;
public abstract class RecipeInstaller {
private String restUrl;
private String recipePath;
private boolean disableSelfHealing = false;
private Map<String, Object> overrideProperties;
private Map<String, Object> cloudOverrideProperties;
private long timeoutInMinutes;
private boolean waitForFinish = true;
private boolean expectToFail = false;
private String cloudifyUsername;
private String cloudifyPassword;
private String authGroups;
public RecipeInstaller(final String restUrl, int timeout) {
this.restUrl = restUrl;
this.timeoutInMinutes = timeout;
}
public boolean isDisableSelfHealing() {
return disableSelfHealing;
}
public RecipeInstaller setDisableSelfHealing(boolean disableSelfHealing) {
this.disableSelfHealing = disableSelfHealing;
return this;
}
public String getRestUrl() {
return restUrl;
}
public RecipeInstaller restUrl(String restUrl) {
this.restUrl = restUrl;
return this;
}
public String getRecipePath() {
return recipePath;
}
public RecipeInstaller recipePath(String recipePath) {
this.recipePath = recipePath;
return this;
}
public Map<String, Object> getOverrides() {
return overrideProperties;
}
public RecipeInstaller overrides(Map<String, Object> overridesFilePath) {
this.overrideProperties = overridesFilePath;
return this;
}
public Map<String, Object> getCloudOverrides() {
return cloudOverrideProperties;
}
public RecipeInstaller cloudOverrides(Map<String, Object> cloudOverridesFilePath) {
this.cloudOverrideProperties = cloudOverridesFilePath;
return this;
}
public long getTimeoutInMinutes() {
return timeoutInMinutes;
}
public RecipeInstaller timeoutInMinutes(long timeoutInMinutes) {
this.timeoutInMinutes = timeoutInMinutes;
return this;
}
public boolean isWaitForFinish() {
return waitForFinish;
}
public RecipeInstaller waitForFinish(boolean waitForFinish) {
this.waitForFinish = waitForFinish;
return this;
}
public boolean isExpectToFail() {
return expectToFail;
}
public RecipeInstaller expectToFail(boolean expectToFail) {
this.expectToFail = expectToFail;
return this;
}
public RecipeInstaller cloudifyUsername(String cloudifyUsername) {
this.cloudifyUsername = cloudifyUsername;
return this;
}
public RecipeInstaller cloudifyPassword(String cloudifyPassword) {
this.cloudifyPassword = cloudifyPassword;
return this;
}
public String getCloudifyUsername() {
return cloudifyUsername;
}
public String getCloudifyPassword() {
return cloudifyPassword;
}
public String getAuthGroups() {
return authGroups;
}
public RecipeInstaller authGroups(String authGroups) {
this.authGroups = authGroups;
return this;
}
public String install() throws IOException, InterruptedException {
String installCommand = null;
String excpectedResult = null;
String recipeName = null;
if (this instanceof ServiceInstaller) {
installCommand = "install-service";
recipeName = ((ServiceInstaller)this).getServiceName();
excpectedResult = "Service \"" + recipeName + "\" uninstalled successfully";
} else if (this instanceof ApplicationInstaller) {
installCommand = "install-application";
recipeName = ((ApplicationInstaller)this).getApplicationName();
excpectedResult = "Application " + recipeName + " installed successfully";
}
if (recipePath == null) {
throw new IllegalStateException("recipe path cannot be null. please use setRecipePath before calling install");
}
StringBuilder connectCommandBuilder = new StringBuilder()
.append("connect").append(" ");
if (StringUtils.isNotBlank(cloudifyUsername) && StringUtils.isNotBlank(cloudifyPassword)){
connectCommandBuilder.append("-user").append(" ")
.append(cloudifyUsername).append(" ")
.append("-password").append(" ")
.append(cloudifyPassword).append(" ");
}
connectCommandBuilder.append(restUrl).append(";");
StringBuilder commandBuilder = new StringBuilder()
.append(installCommand).append(" ")
.append("--verbose").append(" ")
.append("-timeout").append(" ")
.append(timeoutInMinutes).append(" ");
if (disableSelfHealing) {
commandBuilder.append("-disableSelfHealing").append(" ");
}
if (cloudOverrideProperties != null && !cloudOverrideProperties.isEmpty()) {
File cloudOverridesFile = IOUtils.createTempOverridesFile(cloudOverrideProperties);
commandBuilder.append("-cloud-overrides").append(" ").append(cloudOverridesFile.getAbsolutePath().replace("\\", "/")).append(" ");
}
if (overrideProperties != null && !overrideProperties.isEmpty()) {
File serviceOverridesFile = IOUtils.createTempOverridesFile(overrideProperties);
commandBuilder.append("-overrides").append(" ").append(serviceOverridesFile.getAbsolutePath().replace("\\", "/")).append(" ");
}
if (authGroups != null && !authGroups.isEmpty()) {
commandBuilder.append("-authGroups").append(" ").append(authGroups).append(" ");
}
if (recipeName != null && !recipeName.isEmpty()) {
commandBuilder.append("-name").append(" ").append(recipeName).append(" ");
}
commandBuilder.append(recipePath.replace('\\', '/'));
final String installationCommand = commandBuilder.toString();
final String connectCommand = connectCommandBuilder.toString();
if (expectToFail) {
String output = CommandTestUtils.runCommandExpectedFail(connectCommand + installationCommand);
- AssertUtils.assertTrue("Installation succeeded", output.toLowerCase().contains("operation failed"));
+ AssertUtils.assertTrue("Installation of " + recipeName + "was expected to fail. but it succeeded", output.toLowerCase().contains("operation failed"));
return output;
}
if (waitForFinish) {
String output = CommandTestUtils.runCommandAndWait(connectCommand + installationCommand);
- AssertUtils.assertTrue("Installation failed", output.toLowerCase().contains(excpectedResult.toLowerCase()));
+ AssertUtils.assertTrue("Installation of " + recipeName + " was expected to succeed, but it failed", output.toLowerCase().contains(excpectedResult.toLowerCase()));
return output;
} else {
return CommandTestUtils.runCommand(connectCommand + installationCommand);
}
}
public String uninstall() throws IOException, InterruptedException {
String uninstallCommand = null;
String excpectedResult = null;
String recipeName = null;
if (this instanceof ServiceInstaller) {
uninstallCommand = "uninstall-service";
recipeName = ((ServiceInstaller)this).getServiceName();
excpectedResult = "Service \"" + recipeName + "\" uninstalled successfully";
} else if (this instanceof ApplicationInstaller) {
uninstallCommand = "uninstall-application";
recipeName = ((ApplicationInstaller)this).getApplicationName();
excpectedResult = "Application " + recipeName + " uninstalled successfully";
}
String url = null;
try {
url = restUrl + "/service/dump/machines/?fileSizeLimit=50000000";
DumpUtils.dumpMachines(restUrl, SecurityConstants.USER_PWD_ALL_ROLES, SecurityConstants.USER_PWD_ALL_ROLES);
} catch (final Exception e) {
LogUtils.log("Failed to create dump for this url - " + url, e);
}
StringBuilder connectCommandBuilder = new StringBuilder()
.append("connect").append(" ");
if (StringUtils.isNotBlank(cloudifyUsername) && StringUtils.isNotBlank(cloudifyPassword)){
connectCommandBuilder.append("-user").append(" ")
.append(cloudifyUsername).append(" ")
.append("-password").append(" ")
.append(cloudifyPassword).append(" ");
}
connectCommandBuilder.append(restUrl).append(";");
final String uninstallationCommand = new StringBuilder()
.append(uninstallCommand).append(" ")
.append("--verbose").append(" ")
.append("-timeout").append(" ")
.append(timeoutInMinutes).append(" ")
.append(recipeName)
.toString();
final String connectCommand = connectCommandBuilder.toString();
if (expectToFail) {
String output = CommandTestUtils.runCommandExpectedFail(connectCommand + uninstallationCommand);
AssertUtils.assertTrue("Installation succeeded", output.toLowerCase().contains("operation failed"));
return output;
}
if (waitForFinish) {
String output = CommandTestUtils.runCommandAndWait(connectCommand + uninstallationCommand);
AssertUtils.assertTrue(output.toLowerCase().contains(excpectedResult.toLowerCase()));
return output;
} else {
return CommandTestUtils.runCommand(connectCommand + uninstallationCommand);
}
}
}
| false | true | public String install() throws IOException, InterruptedException {
String installCommand = null;
String excpectedResult = null;
String recipeName = null;
if (this instanceof ServiceInstaller) {
installCommand = "install-service";
recipeName = ((ServiceInstaller)this).getServiceName();
excpectedResult = "Service \"" + recipeName + "\" uninstalled successfully";
} else if (this instanceof ApplicationInstaller) {
installCommand = "install-application";
recipeName = ((ApplicationInstaller)this).getApplicationName();
excpectedResult = "Application " + recipeName + " installed successfully";
}
if (recipePath == null) {
throw new IllegalStateException("recipe path cannot be null. please use setRecipePath before calling install");
}
StringBuilder connectCommandBuilder = new StringBuilder()
.append("connect").append(" ");
if (StringUtils.isNotBlank(cloudifyUsername) && StringUtils.isNotBlank(cloudifyPassword)){
connectCommandBuilder.append("-user").append(" ")
.append(cloudifyUsername).append(" ")
.append("-password").append(" ")
.append(cloudifyPassword).append(" ");
}
connectCommandBuilder.append(restUrl).append(";");
StringBuilder commandBuilder = new StringBuilder()
.append(installCommand).append(" ")
.append("--verbose").append(" ")
.append("-timeout").append(" ")
.append(timeoutInMinutes).append(" ");
if (disableSelfHealing) {
commandBuilder.append("-disableSelfHealing").append(" ");
}
if (cloudOverrideProperties != null && !cloudOverrideProperties.isEmpty()) {
File cloudOverridesFile = IOUtils.createTempOverridesFile(cloudOverrideProperties);
commandBuilder.append("-cloud-overrides").append(" ").append(cloudOverridesFile.getAbsolutePath().replace("\\", "/")).append(" ");
}
if (overrideProperties != null && !overrideProperties.isEmpty()) {
File serviceOverridesFile = IOUtils.createTempOverridesFile(overrideProperties);
commandBuilder.append("-overrides").append(" ").append(serviceOverridesFile.getAbsolutePath().replace("\\", "/")).append(" ");
}
if (authGroups != null && !authGroups.isEmpty()) {
commandBuilder.append("-authGroups").append(" ").append(authGroups).append(" ");
}
if (recipeName != null && !recipeName.isEmpty()) {
commandBuilder.append("-name").append(" ").append(recipeName).append(" ");
}
commandBuilder.append(recipePath.replace('\\', '/'));
final String installationCommand = commandBuilder.toString();
final String connectCommand = connectCommandBuilder.toString();
if (expectToFail) {
String output = CommandTestUtils.runCommandExpectedFail(connectCommand + installationCommand);
AssertUtils.assertTrue("Installation succeeded", output.toLowerCase().contains("operation failed"));
return output;
}
if (waitForFinish) {
String output = CommandTestUtils.runCommandAndWait(connectCommand + installationCommand);
AssertUtils.assertTrue("Installation failed", output.toLowerCase().contains(excpectedResult.toLowerCase()));
return output;
} else {
return CommandTestUtils.runCommand(connectCommand + installationCommand);
}
}
| public String install() throws IOException, InterruptedException {
String installCommand = null;
String excpectedResult = null;
String recipeName = null;
if (this instanceof ServiceInstaller) {
installCommand = "install-service";
recipeName = ((ServiceInstaller)this).getServiceName();
excpectedResult = "Service \"" + recipeName + "\" uninstalled successfully";
} else if (this instanceof ApplicationInstaller) {
installCommand = "install-application";
recipeName = ((ApplicationInstaller)this).getApplicationName();
excpectedResult = "Application " + recipeName + " installed successfully";
}
if (recipePath == null) {
throw new IllegalStateException("recipe path cannot be null. please use setRecipePath before calling install");
}
StringBuilder connectCommandBuilder = new StringBuilder()
.append("connect").append(" ");
if (StringUtils.isNotBlank(cloudifyUsername) && StringUtils.isNotBlank(cloudifyPassword)){
connectCommandBuilder.append("-user").append(" ")
.append(cloudifyUsername).append(" ")
.append("-password").append(" ")
.append(cloudifyPassword).append(" ");
}
connectCommandBuilder.append(restUrl).append(";");
StringBuilder commandBuilder = new StringBuilder()
.append(installCommand).append(" ")
.append("--verbose").append(" ")
.append("-timeout").append(" ")
.append(timeoutInMinutes).append(" ");
if (disableSelfHealing) {
commandBuilder.append("-disableSelfHealing").append(" ");
}
if (cloudOverrideProperties != null && !cloudOverrideProperties.isEmpty()) {
File cloudOverridesFile = IOUtils.createTempOverridesFile(cloudOverrideProperties);
commandBuilder.append("-cloud-overrides").append(" ").append(cloudOverridesFile.getAbsolutePath().replace("\\", "/")).append(" ");
}
if (overrideProperties != null && !overrideProperties.isEmpty()) {
File serviceOverridesFile = IOUtils.createTempOverridesFile(overrideProperties);
commandBuilder.append("-overrides").append(" ").append(serviceOverridesFile.getAbsolutePath().replace("\\", "/")).append(" ");
}
if (authGroups != null && !authGroups.isEmpty()) {
commandBuilder.append("-authGroups").append(" ").append(authGroups).append(" ");
}
if (recipeName != null && !recipeName.isEmpty()) {
commandBuilder.append("-name").append(" ").append(recipeName).append(" ");
}
commandBuilder.append(recipePath.replace('\\', '/'));
final String installationCommand = commandBuilder.toString();
final String connectCommand = connectCommandBuilder.toString();
if (expectToFail) {
String output = CommandTestUtils.runCommandExpectedFail(connectCommand + installationCommand);
AssertUtils.assertTrue("Installation of " + recipeName + "was expected to fail. but it succeeded", output.toLowerCase().contains("operation failed"));
return output;
}
if (waitForFinish) {
String output = CommandTestUtils.runCommandAndWait(connectCommand + installationCommand);
AssertUtils.assertTrue("Installation of " + recipeName + " was expected to succeed, but it failed", output.toLowerCase().contains(excpectedResult.toLowerCase()));
return output;
} else {
return CommandTestUtils.runCommand(connectCommand + installationCommand);
}
}
|
diff --git a/app/controllers/PageController.java b/app/controllers/PageController.java
index 2f68cb7..e4f0897 100644
--- a/app/controllers/PageController.java
+++ b/app/controllers/PageController.java
@@ -1,169 +1,169 @@
package controllers;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import models.Page;
import models.PageRef;
import models.Tag;
import play.data.validation.Validation;
import play.mvc.Controller;
import play.mvc.With;
import play.vfs.VirtualFile;
/**
*
* @author waxzce
* @author keruspe
*/
@With(Secure.class)
public class PageController extends Controller {
public static void listPages(Integer pagenumber) {
if (pagenumber == null) {
pagenumber = 0;
}
List<PageRef> pages = PageRef.getPageRefPage(pagenumber, 20);
render(pages, pagenumber);
}
public static void deletePage_confirm(String urlId, String language) {
Page page = Page.getPageByLocale(urlId, new Locale(language));
render(page);
}
public static void deletePage(String urlId, String language) {
Page page = Page.getPageByLocale(urlId, new Locale(language));
if (page == null) {
return;
}
PageRef pageRef = page.pageReference;
page.delete();
if (Page.getFirstPageByPageRef(pageRef) == null) {
pageRef.delete();
}
PageViewer.index();
}
public static void newPage() {
renderArgs.put("action", "create");
render("PageController/newPage.html");
}
public static void edit(String urlId, String language) {
Page otherPage = Page.getPageByLocale(urlId, new Locale(language));
renderArgs.put("otherPage", otherPage);
renderArgs.put("action", "edit");
String overrider = null;
for (Page p : Page.getPagesByPageRef(otherPage.pageReference)) {
overrider = "/view/PageEvent/edit/" + p.urlId + ".html";
if (VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists())
break;
}
if (VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists()) {
render(overrider);
} else {
render("PageController/newPage.html");
}
}
public static void translate(String otherUrlId, String language) {
Page otherPage = Page.getPageByLocale(otherUrlId, new Locale(language));
renderArgs.put("otherPage", otherPage);
renderArgs.put("action", "translate");
String overrider = null;
for (Page p : Page.getPagesByPageRef(otherPage.pageReference)) {
overrider = "/view/PageEvent/translate/" + p.urlId + ".html";
if (VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists())
break;
}
if (VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists()) {
render(overrider);
} else {
render("PageController/newPage.html");
}
}
public static void doNewPage(String actionz, String otherUrlId, String otherLanguage) {
String urlId = otherUrlId;
Page page = null;
PageRef pageRef = null;
String tagsString = params.get("pageReference.tags");
if (urlId != null && !urlId.equals("")) {
page = Page.getPageByUrlId(urlId);
}
if (page != null) {
pageRef = page.pageReference;
} else {
- pageRef = PageController.doNewPageRef("edit", otherUrlId, otherLanguage);
+ pageRef = PageController.doNewPageRef(actionz, otherUrlId, otherLanguage);
}
urlId = params.get("page.urlId");
Set<Tag> tags = new TreeSet<Tag>();
if (tagsString != null && !tagsString.isEmpty()) {
for (String tag : Arrays.asList(tagsString.split(","))) {
tags.add(Tag.findOrCreateByName(tag));
}
}
pageRef.tags = tags;
if (!actionz.equals("edit")) {
page = new Page();
}
page.pageReference = pageRef;
page.urlId = urlId;
page.title = params.get("page.title");
page.content = params.get("page.content");
page.language = params.get("page.language", Locale.class);
page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE;
validation.valid(page);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (actionz.equals("edit")) {
PageController.edit(otherUrlId, otherLanguage);
} else if (actionz.equals("translate")) {
PageController.translate(otherUrlId, otherLanguage);
} else {
PageController.newPage();
}
}
page.pageReference.save();
page.save();
if (page.published) {
PageViewer.page(urlId);
} else {
PageViewer.index();
}
}
private static PageRef doNewPageRef(String action, String otherUrlId, String otherLanguage) {
PageRef pageRef = new PageRef();
validation.valid(pageRef);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (action.equals("edit")) {
PageController.edit(otherUrlId, otherLanguage);
} else if (action.equals("translate")) {
PageController.translate(otherUrlId, otherLanguage);
} else {
PageController.newPage();
}
}
return pageRef;
}
}
| true | true | public static void doNewPage(String actionz, String otherUrlId, String otherLanguage) {
String urlId = otherUrlId;
Page page = null;
PageRef pageRef = null;
String tagsString = params.get("pageReference.tags");
if (urlId != null && !urlId.equals("")) {
page = Page.getPageByUrlId(urlId);
}
if (page != null) {
pageRef = page.pageReference;
} else {
pageRef = PageController.doNewPageRef("edit", otherUrlId, otherLanguage);
}
urlId = params.get("page.urlId");
Set<Tag> tags = new TreeSet<Tag>();
if (tagsString != null && !tagsString.isEmpty()) {
for (String tag : Arrays.asList(tagsString.split(","))) {
tags.add(Tag.findOrCreateByName(tag));
}
}
pageRef.tags = tags;
if (!actionz.equals("edit")) {
page = new Page();
}
page.pageReference = pageRef;
page.urlId = urlId;
page.title = params.get("page.title");
page.content = params.get("page.content");
page.language = params.get("page.language", Locale.class);
page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE;
validation.valid(page);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (actionz.equals("edit")) {
PageController.edit(otherUrlId, otherLanguage);
} else if (actionz.equals("translate")) {
PageController.translate(otherUrlId, otherLanguage);
} else {
PageController.newPage();
}
}
page.pageReference.save();
page.save();
if (page.published) {
PageViewer.page(urlId);
} else {
PageViewer.index();
}
}
| public static void doNewPage(String actionz, String otherUrlId, String otherLanguage) {
String urlId = otherUrlId;
Page page = null;
PageRef pageRef = null;
String tagsString = params.get("pageReference.tags");
if (urlId != null && !urlId.equals("")) {
page = Page.getPageByUrlId(urlId);
}
if (page != null) {
pageRef = page.pageReference;
} else {
pageRef = PageController.doNewPageRef(actionz, otherUrlId, otherLanguage);
}
urlId = params.get("page.urlId");
Set<Tag> tags = new TreeSet<Tag>();
if (tagsString != null && !tagsString.isEmpty()) {
for (String tag : Arrays.asList(tagsString.split(","))) {
tags.add(Tag.findOrCreateByName(tag));
}
}
pageRef.tags = tags;
if (!actionz.equals("edit")) {
page = new Page();
}
page.pageReference = pageRef;
page.urlId = urlId;
page.title = params.get("page.title");
page.content = params.get("page.content");
page.language = params.get("page.language", Locale.class);
page.published = (params.get("page.published") == null) ? Boolean.FALSE : Boolean.TRUE;
validation.valid(page);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (actionz.equals("edit")) {
PageController.edit(otherUrlId, otherLanguage);
} else if (actionz.equals("translate")) {
PageController.translate(otherUrlId, otherLanguage);
} else {
PageController.newPage();
}
}
page.pageReference.save();
page.save();
if (page.published) {
PageViewer.page(urlId);
} else {
PageViewer.index();
}
}
|
diff --git a/src/java/org/apache/poi/hssf/usermodel/HSSFSheet.java b/src/java/org/apache/poi/hssf/usermodel/HSSFSheet.java
index 84a71a89a..ef3d58006 100644
--- a/src/java/org/apache/poi/hssf/usermodel/HSSFSheet.java
+++ b/src/java/org/apache/poi/hssf/usermodel/HSSFSheet.java
@@ -1,1834 +1,1835 @@
/* ====================================================================
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.poi.hssf.usermodel;
import java.awt.font.FontRenderContext;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.io.PrintWriter;
import java.text.AttributedString;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import org.apache.poi.ddf.EscherRecord;
import org.apache.poi.hssf.model.FormulaParser;
import org.apache.poi.hssf.model.Sheet;
import org.apache.poi.hssf.model.Workbook;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.record.aggregates.DataValidityTable;
import org.apache.poi.hssf.record.formula.Ptg;
import org.apache.poi.hssf.record.formula.RefPtg;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.PaneInformation;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
/**
* High level representation of a worksheet.
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Glen Stampoultzis (glens at apache.org)
* @author Libin Roman (romal at vistaportal.com)
* @author Shawn Laubach (slaubach at apache dot org) (Just a little)
* @author Jean-Pierre Paris (jean-pierre.paris at m4x dot org) (Just a little, too)
* @author Yegor Kozlov (yegor at apache.org) (Autosizing columns)
*/
public final class HSSFSheet {
private static final int DEBUG = POILogger.DEBUG;
/* Constants for margins */
public static final short LeftMargin = Sheet.LeftMargin;
public static final short RightMargin = Sheet.RightMargin;
public static final short TopMargin = Sheet.TopMargin;
public static final short BottomMargin = Sheet.BottomMargin;
public static final byte PANE_LOWER_RIGHT = (byte)0;
public static final byte PANE_UPPER_RIGHT = (byte)1;
public static final byte PANE_LOWER_LEFT = (byte)2;
public static final byte PANE_UPPER_LEFT = (byte)3;
/**
* Used for compile-time optimization. This is the initial size for the collection of
* rows. It is currently set to 20. If you generate larger sheets you may benefit
* by setting this to a higher number and recompiling a custom edition of HSSFSheet.
*/
public final static int INITIAL_CAPACITY = 20;
/**
* reference to the low level Sheet object
*/
private Sheet sheet;
/** stores <tt>HSSFRow</tt>s by <tt>Integer</tt> (zero-based row number) key */
private TreeMap rows;
protected Workbook book;
protected HSSFWorkbook workbook;
private int firstrow;
private int lastrow;
private static POILogger log = POILogFactory.getLogger(HSSFSheet.class);
/**
* Creates new HSSFSheet - called by HSSFWorkbook to create a sheet from
* scratch. You should not be calling this from application code (its protected anyhow).
*
* @param workbook - The HSSF Workbook object associated with the sheet.
* @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createSheet()
*/
protected HSSFSheet(HSSFWorkbook workbook)
{
sheet = Sheet.createSheet();
rows = new TreeMap();
this.workbook = workbook;
this.book = workbook.getWorkbook();
}
/**
* Creates an HSSFSheet representing the given Sheet object. Should only be
* called by HSSFWorkbook when reading in an exisiting file.
*
* @param workbook - The HSSF Workbook object associated with the sheet.
* @param sheet - lowlevel Sheet object this sheet will represent
* @see org.apache.poi.hssf.usermodel.HSSFWorkbook#createSheet()
*/
protected HSSFSheet(HSSFWorkbook workbook, Sheet sheet)
{
this.sheet = sheet;
rows = new TreeMap();
this.workbook = workbook;
this.book = workbook.getWorkbook();
setPropertiesFromSheet(sheet);
}
HSSFSheet cloneSheet(HSSFWorkbook workbook) {
return new HSSFSheet(workbook, sheet.cloneSheet());
}
/**
* used internally to set the properties given a Sheet object
*/
private void setPropertiesFromSheet(Sheet sheet) {
RowRecord row = sheet.getNextRow();
boolean rowRecordsAlreadyPresent = row!=null;
while (row != null) {
createRowFromRecord(row);
row = sheet.getNextRow();
}
CellValueRecordInterface[] cvals = sheet.getValueRecords();
long timestart = System.currentTimeMillis();
if (log.check( POILogger.DEBUG ))
log.log(DEBUG, "Time at start of cell creating in HSSF sheet = ",
new Long(timestart));
HSSFRow lastrow = null;
// Add every cell to its row
for (int i = 0; i < cvals.length; i++) {
CellValueRecordInterface cval = cvals[i];
long cellstart = System.currentTimeMillis();
HSSFRow hrow = lastrow;
if (hrow == null || hrow.getRowNum() != cval.getRow()) {
hrow = getRow( cval.getRow() );
lastrow = hrow;
if (hrow == null) {
// Some tools (like Perl module Spreadsheet::WriteExcel - bug 41187) skip the RowRecords
// Excel, OpenOffice.org and GoogleDocs are all OK with this, so POI should be too.
if (rowRecordsAlreadyPresent) {
// if at least one row record is present, all should be present.
throw new RuntimeException("Unexpected missing row when some rows already present");
}
// create the row record on the fly now.
RowRecord rowRec = new RowRecord(cval.getRow());
sheet.addRow(rowRec);
hrow = createRowFromRecord(rowRec);
}
}
if (log.check( POILogger.DEBUG ))
log.log( DEBUG, "record id = " + Integer.toHexString( ( (Record) cval ).getSid() ) );
hrow.createCellFromRecord( cval );
if (log.check( POILogger.DEBUG ))
log.log( DEBUG, "record took ",
new Long( System.currentTimeMillis() - cellstart ) );
}
if (log.check( POILogger.DEBUG ))
log.log(DEBUG, "total sheet cell creation took ",
new Long(System.currentTimeMillis() - timestart));
}
/**
* Create a new row within the sheet and return the high level representation
*
* @param rownum row number
* @return High level HSSFRow object representing a row in the sheet
* @see org.apache.poi.hssf.usermodel.HSSFRow
* @see #removeRow(HSSFRow)
*/
public HSSFRow createRow(int rownum)
{
HSSFRow row = new HSSFRow(workbook, sheet, rownum);
addRow(row, true);
return row;
}
/**
* Used internally to create a high level Row object from a low level row object.
* USed when reading an existing file
* @param row low level record to represent as a high level Row and add to sheet
* @return HSSFRow high level representation
*/
private HSSFRow createRowFromRecord(RowRecord row)
{
HSSFRow hrow = new HSSFRow(workbook, sheet, row);
addRow(hrow, false);
return hrow;
}
/**
* Remove a row from this sheet. All cells contained in the row are removed as well
*
* @param row representing a row to remove.
*/
public void removeRow(HSSFRow row) {
if (rows.size() > 0)
{
Integer key = new Integer(row.getRowNum());
HSSFRow removedRow = (HSSFRow) rows.remove(key);
if (removedRow != row) {
if (removedRow != null) {
rows.put(key, removedRow);
}
throw new RuntimeException("Specified row does not belong to this sheet");
}
if (row.getRowNum() == getLastRowNum())
{
lastrow = findLastRow(lastrow);
}
if (row.getRowNum() == getFirstRowNum())
{
firstrow = findFirstRow(firstrow);
}
sheet.removeRow(row.getRowRecord());
}
}
/**
* used internally to refresh the "last row" when the last row is removed.
*/
private int findLastRow(int lastrow) {
if (lastrow < 1) {
return -1;
}
int rownum = lastrow - 1;
HSSFRow r = getRow(rownum);
while (r == null && rownum > 0) {
r = getRow(--rownum);
}
if (r == null) {
return -1;
}
return rownum;
}
/**
* used internally to refresh the "first row" when the first row is removed.
*/
private int findFirstRow(int firstrow)
{
int rownum = firstrow + 1;
HSSFRow r = getRow(rownum);
while (r == null && rownum <= getLastRowNum())
{
r = getRow(++rownum);
}
if (rownum > getLastRowNum())
return -1;
return rownum;
}
/**
* add a row to the sheet
*
* @param addLow whether to add the row to the low level model - false if its already there
*/
private void addRow(HSSFRow row, boolean addLow)
{
rows.put(new Integer(row.getRowNum()), row);
if (addLow)
{
sheet.addRow(row.getRowRecord());
}
if (row.getRowNum() > getLastRowNum())
{
lastrow = row.getRowNum();
}
if (row.getRowNum() < getFirstRowNum())
{
firstrow = row.getRowNum();
}
}
/**
* Returns the logical row (not physical) 0-based. If you ask for a row that is not
* defined you get a null. This is to say row 4 represents the fifth row on a sheet.
* @param rowIndex row to get
* @return HSSFRow representing the rownumber or null if its not defined on the sheet
*/
public HSSFRow getRow(int rowIndex) {
return (HSSFRow) rows.get(new Integer(rowIndex));
}
/**
* Returns the number of phsyically defined rows (NOT the number of rows in the sheet)
*/
public int getPhysicalNumberOfRows()
{
return rows.size();
}
/**
* Gets the first row on the sheet
* @return the number of the first logical row on the sheet, zero based
*/
public int getFirstRowNum()
{
return firstrow;
}
/**
* Gets the number last row on the sheet.
* Owing to idiosyncrasies in the excel file
* format, if the result of calling this method
* is zero, you can't tell if that means there
* are zero rows on the sheet, or one at
* position zero. For that case, additionally
* call {@link #getPhysicalNumberOfRows()} to
* tell if there is a row at position zero
* or not.
* @return the number of the last row contained in this sheet, zero based.
*/
public int getLastRowNum()
{
return lastrow;
}
/**
* Creates a data validation object
* @param dataValidation The Data validation object settings
*/
public void addValidationData(HSSFDataValidation dataValidation) {
if (dataValidation == null) {
throw new IllegalArgumentException("objValidation must not be null");
}
DataValidityTable dvt = sheet.getOrCreateDataValidityTable();
DVRecord dvRecord = dataValidation.createDVRecord(workbook);
dvt.addDataValidation(dvRecord);
}
/**
* Get the visibility state for a given column.
* @param column - the column to get (0-based)
* @param hidden - the visiblity state of the column
*/
public void setColumnHidden(short column, boolean hidden)
{
sheet.setColumnHidden(column, hidden);
}
/**
* Get the hidden state for a given column.
* @param column - the column to set (0-based)
* @return hidden - the visiblity state of the column
*/
public boolean isColumnHidden(short column)
{
return sheet.isColumnHidden(column);
}
/**
* set the width (in units of 1/256th of a character width)
* @param column - the column to set (0-based)
* @param width - the width in units of 1/256th of a character width
*/
public void setColumnWidth(short column, short width)
{
sheet.setColumnWidth(column, width);
}
/**
* get the width (in units of 1/256th of a character width )
* @param column - the column to set (0-based)
* @return width - the width in units of 1/256th of a character width
*/
public short getColumnWidth(short column)
{
return sheet.getColumnWidth(column);
}
/**
* get the default column width for the sheet (if the columns do not define their own width) in
* characters
* @return default column width
*/
public short getDefaultColumnWidth()
{
return sheet.getDefaultColumnWidth();
}
/**
* get the default row height for the sheet (if the rows do not define their own height) in
* twips (1/20 of a point)
* @return default row height
*/
public short getDefaultRowHeight()
{
return sheet.getDefaultRowHeight();
}
/**
* get the default row height for the sheet (if the rows do not define their own height) in
* points.
* @return default row height in points
*/
public float getDefaultRowHeightInPoints()
{
return (sheet.getDefaultRowHeight() / 20);
}
/**
* set the default column width for the sheet (if the columns do not define their own width) in
* characters
* @param width default column width
*/
public void setDefaultColumnWidth(short width)
{
sheet.setDefaultColumnWidth(width);
}
/**
* set the default row height for the sheet (if the rows do not define their own height) in
* twips (1/20 of a point)
* @param height default row height
*/
public void setDefaultRowHeight(short height)
{
sheet.setDefaultRowHeight(height);
}
/**
* set the default row height for the sheet (if the rows do not define their own height) in
* points
* @param height default row height
*/
public void setDefaultRowHeightInPoints(float height)
{
sheet.setDefaultRowHeight((short) (height * 20));
}
/**
* get whether gridlines are printed.
* @return true if printed
*/
public boolean isGridsPrinted()
{
return sheet.isGridsPrinted();
}
/**
* set whether gridlines printed.
* @param value false if not printed.
*/
public void setGridsPrinted(boolean value)
{
sheet.setGridsPrinted(value);
}
/**
* @deprecated (Aug-2008) use <tt>CellRangeAddress</tt> instead of <tt>Region</tt>
*/
public int addMergedRegion(Region region)
{
return sheet.addMergedRegion( region.getRowFrom(),
region.getColumnFrom(),
//(short) region.getRowTo(),
region.getRowTo(),
region.getColumnTo());
}
/**
* adds a merged region of cells (hence those cells form one)
* @param region (rowfrom/colfrom-rowto/colto) to merge
* @return index of this region
*/
public int addMergedRegion(CellRangeAddress region)
{
return sheet.addMergedRegion( region.getFirstRow(),
region.getFirstColumn(),
region.getLastRow(),
region.getLastColumn());
}
/**
* Whether a record must be inserted or not at generation to indicate that
* formula must be recalculated when workbook is opened.
* @param value true if an uncalced record must be inserted or not at generation
*/
public void setForceFormulaRecalculation(boolean value)
{
sheet.setUncalced(value);
}
/**
* Whether a record must be inserted or not at generation to indicate that
* formula must be recalculated when workbook is opened.
* @return true if an uncalced record must be inserted or not at generation
*/
public boolean getForceFormulaRecalculation()
{
return sheet.getUncalced();
}
/**
* determines whether the output is vertically centered on the page.
* @param value true to vertically center, false otherwise.
*/
public void setVerticallyCenter(boolean value)
{
sheet.getPageSettings().getVCenter().setVCenter(value);
}
/**
* TODO: Boolean not needed, remove after next release
* @deprecated (Mar-2008) use getVerticallyCenter() instead
*/
public boolean getVerticallyCenter(boolean value) {
return getVerticallyCenter();
}
/**
* Determine whether printed output for this sheet will be vertically centered.
*/
public boolean getVerticallyCenter()
{
return sheet.getPageSettings().getVCenter().getVCenter();
}
/**
* determines whether the output is horizontally centered on the page.
* @param value true to horizontally center, false otherwise.
*/
public void setHorizontallyCenter(boolean value)
{
sheet.getPageSettings().getHCenter().setHCenter(value);
}
/**
* Determine whether printed output for this sheet will be horizontally centered.
*/
public boolean getHorizontallyCenter()
{
return sheet.getPageSettings().getHCenter().getHCenter();
}
/**
* removes a merged region of cells (hence letting them free)
* @param index of the region to unmerge
*/
public void removeMergedRegion(int index)
{
sheet.removeMergedRegion(index);
}
/**
* returns the number of merged regions
* @return number of merged regions
*/
public int getNumMergedRegions()
{
return sheet.getNumMergedRegions();
}
/**
* @deprecated (Aug-2008) use {@link HSSFSheet#getMergedRegion(int)}
*/
public Region getMergedRegionAt(int index) {
CellRangeAddress cra = getMergedRegion(index);
return new Region(cra.getFirstRow(), (short)cra.getFirstColumn(),
cra.getLastRow(), (short)cra.getLastColumn());
}
/**
* @return the merged region at the specified index
*/
public CellRangeAddress getMergedRegion(int index) {
return sheet.getMergedRegionAt(index);
}
/**
* @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not
* be the third row if say for instance the second row is undefined.
* Call getRowNum() on each row if you care which one it is.
*/
public Iterator rowIterator()
{
return rows.values().iterator();
}
/**
* Alias for {@link #rowIterator()} to allow
* foreach loops
*/
public Iterator iterator() {
return rowIterator();
}
/**
* used internally in the API to get the low level Sheet record represented by this
* Object.
* @return Sheet - low level representation of this HSSFSheet.
*/
protected Sheet getSheet()
{
return sheet;
}
/**
* whether alternate expression evaluation is on
* @param b alternative expression evaluation or not
*/
public void setAlternativeExpression(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setAlternateExpression(b);
}
/**
* whether alternative formula entry is on
* @param b alternative formulas or not
*/
public void setAlternativeFormula(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setAlternateFormula(b);
}
/**
* show automatic page breaks or not
* @param b whether to show auto page breaks
*/
public void setAutobreaks(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setAutobreaks(b);
}
/**
* set whether sheet is a dialog sheet or not
* @param b isDialog or not
*/
public void setDialog(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setDialog(b);
}
/**
* set whether to display the guts or not
*
* @param b guts or no guts (or glory)
*/
public void setDisplayGuts(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setDisplayGuts(b);
}
/**
* fit to page option is on
* @param b fit or not
*/
public void setFitToPage(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setFitToPage(b);
}
/**
* set if row summaries appear below detail in the outline
* @param b below or not
*/
public void setRowSumsBelow(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setRowSumsBelow(b);
}
/**
* set if col summaries appear right of the detail in the outline
* @param b right or not
*/
public void setRowSumsRight(boolean b)
{
WSBoolRecord record =
(WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid);
record.setRowSumsRight(b);
}
/**
* whether alternate expression evaluation is on
* @return alternative expression evaluation or not
*/
public boolean getAlternateExpression()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getAlternateExpression();
}
/**
* whether alternative formula entry is on
* @return alternative formulas or not
*/
public boolean getAlternateFormula()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getAlternateFormula();
}
/**
* show automatic page breaks or not
* @return whether to show auto page breaks
*/
public boolean getAutobreaks()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getAutobreaks();
}
/**
* get whether sheet is a dialog sheet or not
* @return isDialog or not
*/
public boolean getDialog()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getDialog();
}
/**
* get whether to display the guts or not
*
* @return guts or no guts (or glory)
*/
public boolean getDisplayGuts()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getDisplayGuts();
}
/**
* fit to page option is on
* @return fit or not
*/
public boolean getFitToPage()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getFitToPage();
}
/**
* get if row summaries appear below detail in the outline
* @return below or not
*/
public boolean getRowSumsBelow()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getRowSumsBelow();
}
/**
* get if col summaries appear right of the detail in the outline
* @return right or not
*/
public boolean getRowSumsRight()
{
return ((WSBoolRecord) sheet.findFirstRecordBySid(WSBoolRecord.sid))
.getRowSumsRight();
}
/**
* Returns whether gridlines are printed.
* @return Gridlines are printed
*/
public boolean isPrintGridlines() {
return getSheet().getPrintGridlines().getPrintGridlines();
}
/**
* Turns on or off the printing of gridlines.
* @param newPrintGridlines boolean to turn on or off the printing of
* gridlines
*/
public void setPrintGridlines( boolean newPrintGridlines )
{
getSheet().getPrintGridlines().setPrintGridlines( newPrintGridlines );
}
/**
* Gets the print setup object.
* @return The user model for the print setup object.
*/
public HSSFPrintSetup getPrintSetup()
{
return new HSSFPrintSetup( sheet.getPageSettings().getPrintSetup() );
}
/**
* Gets the user model for the document header.
* @return The Document header.
*/
public HSSFHeader getHeader()
{
return new HSSFHeader( sheet.getPageSettings().getHeader() );
}
/**
* Gets the user model for the document footer.
* @return The Document footer.
*/
public HSSFFooter getFooter()
{
return new HSSFFooter( sheet.getPageSettings().getFooter() );
}
/**
* Note - this is not the same as whether the sheet is focused (isActive)
* @return <code>true</code> if this sheet is currently selected
*/
public boolean isSelected() {
return getSheet().getWindowTwo().getSelected();
}
/**
* Sets whether sheet is selected.
* @param sel Whether to select the sheet or deselect the sheet.
*/
public void setSelected( boolean sel )
{
getSheet().getWindowTwo().setSelected(sel);
}
/**
* @return <code>true</code> if this sheet is currently focused
*/
public boolean isActive() {
return getSheet().getWindowTwo().isActive();
}
/**
* Sets whether sheet is selected.
* @param sel Whether to select the sheet or deselect the sheet.
*/
public void setActive(boolean sel )
{
getSheet().getWindowTwo().setActive(sel);
}
/**
* Gets the size of the margin in inches.
* @param margin which margin to get
* @return the size of the margin
*/
public double getMargin( short margin )
{
return sheet.getPageSettings().getMargin( margin );
}
/**
* Sets the size of the margin in inches.
* @param margin which margin to get
* @param size the size of the margin
*/
public void setMargin( short margin, double size )
{
sheet.getPageSettings().setMargin( margin, size );
}
/**
* Answer whether protection is enabled or disabled
* @return true => protection enabled; false => protection disabled
*/
public boolean getProtect() {
return getSheet().isProtected()[0];
}
/**
* @return hashed password
*/
public short getPassword() {
return getSheet().getPassword().getPassword();
}
/**
* Answer whether object protection is enabled or disabled
* @return true => protection enabled; false => protection disabled
*/
public boolean getObjectProtect() {
return getSheet().isProtected()[1];
}
/**
* Answer whether scenario protection is enabled or disabled
* @return true => protection enabled; false => protection disabled
*/
public boolean getScenarioProtect() {
return getSheet().isProtected()[2];
}
/**
* Sets the protection on enabled or disabled
* @param protect true => protection enabled; false => protection disabled
* @deprecated use protectSheet(String, boolean, boolean)
*/
public void setProtect(boolean protect) {
getSheet().getProtect().setProtect(protect);
}
/**
* Sets the protection enabled as well as the password
* @param password to set for protection
*/
public void protectSheet(String password) {
getSheet().protectSheet(password, true, true); //protect objs&scenarios(normal)
}
/**
* Sets the zoom magnication for the sheet. The zoom is expressed as a
* fraction. For example to express a zoom of 75% use 3 for the numerator
* and 4 for the denominator.
*
* @param numerator The numerator for the zoom magnification.
* @param denominator The denominator for the zoom magnification.
*/
public void setZoom( int numerator, int denominator)
{
if (numerator < 1 || numerator > 65535)
throw new IllegalArgumentException("Numerator must be greater than 1 and less than 65536");
if (denominator < 1 || denominator > 65535)
throw new IllegalArgumentException("Denominator must be greater than 1 and less than 65536");
SCLRecord sclRecord = new SCLRecord();
sclRecord.setNumerator((short)numerator);
sclRecord.setDenominator((short)denominator);
getSheet().setSCLRecord(sclRecord);
}
/**
* The top row in the visible view when the sheet is
* first viewed after opening it in a viewer
* @return short indicating the rownum (0 based) of the top row
*/
public short getTopRow()
{
return sheet.getTopRow();
}
/**
* The left col in the visible view when the sheet is
* first viewed after opening it in a viewer
* @return short indicating the rownum (0 based) of the top row
*/
public short getLeftCol()
{
return sheet.getLeftCol();
}
/**
* Sets desktop window pane display area, when the
* file is first opened in a viewer.
* @param toprow the top row to show in desktop window pane
* @param leftcol the left column to show in desktop window pane
*/
public void showInPane(short toprow, short leftcol){
this.sheet.setTopRow(toprow);
this.sheet.setLeftCol(leftcol);
}
/**
* Shifts the merged regions left or right depending on mode
* <p>
* TODO: MODE , this is only row specific
* @param startRow
* @param endRow
* @param n
* @param isRow
*/
protected void shiftMerged(int startRow, int endRow, int n, boolean isRow) {
List shiftedRegions = new ArrayList();
//move merged regions completely if they fall within the new region boundaries when they are shifted
for (int i = 0; i < getNumMergedRegions(); i++) {
CellRangeAddress merged = getMergedRegion(i);
boolean inStart= (merged.getFirstRow() >= startRow || merged.getLastRow() >= startRow);
boolean inEnd = (merged.getFirstRow() <= endRow || merged.getLastRow() <= endRow);
//don't check if it's not within the shifted area
if (!inStart || !inEnd) {
continue;
}
//only shift if the region outside the shifted rows is not merged too
if (!containsCell(merged, startRow-1, 0) && !containsCell(merged, endRow+1, 0)){
merged.setFirstRow(merged.getFirstRow()+n);
merged.setLastRow(merged.getLastRow()+n);
//have to remove/add it back
shiftedRegions.add(merged);
removeMergedRegion(i);
i = i -1; // we have to back up now since we removed one
}
}
//read so it doesn't get shifted again
Iterator iterator = shiftedRegions.iterator();
while (iterator.hasNext()) {
CellRangeAddress region = (CellRangeAddress)iterator.next();
this.addMergedRegion(region);
}
}
private static boolean containsCell(CellRangeAddress cr, int rowIx, int colIx) {
if (cr.getFirstRow() <= rowIx && cr.getLastRow() >= rowIx
&& cr.getFirstColumn() <= colIx && cr.getLastColumn() >= colIx)
{
return true;
}
return false;
}
/**
* Shifts rows between startRow and endRow n number of rows.
* If you use a negative number, it will shift rows up.
* Code ensures that rows don't wrap around.
*
* Calls shiftRows(startRow, endRow, n, false, false);
*
* <p>
* Additionally shifts merged regions that are completely defined in these
* rows (ie. merged 2 cells on a row to be shifted).
* @param startRow the row to start shifting
* @param endRow the row to end shifting
* @param n the number of rows to shift
*/
public void shiftRows( int startRow, int endRow, int n ) {
shiftRows(startRow, endRow, n, false, false);
}
/**
* Shifts rows between startRow and endRow n number of rows.
* If you use a negative number, it will shift rows up.
* Code ensures that rows don't wrap around
*
* <p>
* Additionally shifts merged regions that are completely defined in these
* rows (ie. merged 2 cells on a row to be shifted).
* <p>
* TODO Might want to add bounds checking here
* @param startRow the row to start shifting
* @param endRow the row to end shifting
* @param n the number of rows to shift
* @param copyRowHeight whether to copy the row height during the shift
* @param resetOriginalRowHeight whether to set the original row's height to the default
*/
public void shiftRows( int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight)
{
shiftRows(startRow, endRow, n, copyRowHeight, resetOriginalRowHeight, true);
}
/**
* Shifts rows between startRow and endRow n number of rows.
* If you use a negative number, it will shift rows up.
* Code ensures that rows don't wrap around
*
* <p>
* Additionally shifts merged regions that are completely defined in these
* rows (ie. merged 2 cells on a row to be shifted).
* <p>
* TODO Might want to add bounds checking here
* @param startRow the row to start shifting
* @param endRow the row to end shifting
* @param n the number of rows to shift
* @param copyRowHeight whether to copy the row height during the shift
* @param resetOriginalRowHeight whether to set the original row's height to the default
* @param moveComments whether to move comments at the same time as the cells they are attached to
*/
public void shiftRows( int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight, boolean moveComments)
{
int s, e, inc;
if ( n < 0 )
{
s = startRow;
e = endRow;
inc = 1;
}
else
{
s = endRow;
e = startRow;
inc = -1;
}
shiftMerged(startRow, endRow, n, true);
sheet.getPageSettings().shiftRowBreaks(startRow, endRow, n);
for ( int rowNum = s; rowNum >= startRow && rowNum <= endRow && rowNum >= 0 && rowNum < 65536; rowNum += inc )
{
HSSFRow row = getRow( rowNum );
HSSFRow row2Replace = getRow( rowNum + n );
if ( row2Replace == null )
row2Replace = createRow( rowNum + n );
HSSFCell cell;
// Remove all the old cells from the row we'll
// be writing too, before we start overwriting
// any cells. This avoids issues with cells
// changing type, and records not being correctly
// overwritten
row2Replace.removeAllCells();
// If this row doesn't exist, nothing needs to
// be done for the now empty destination row
if (row == null) continue; // Nothing to do for this row
// Fetch the first and last columns of the
// row now, so we still have them to hand
// once we start removing cells
short firstCol = row.getFirstCellNum();
short lastCol = row.getLastCellNum();
// Fix up row heights if required
if (copyRowHeight) {
row2Replace.setHeight(row.getHeight());
}
if (resetOriginalRowHeight) {
row.setHeight((short)0xff);
}
// Copy each cell from the source row to
// the destination row
for(Iterator cells = row.cellIterator(); cells.hasNext(); ) {
cell = (HSSFCell)cells.next();
row.removeCell( cell );
CellValueRecordInterface cellRecord = cell.getCellValueRecord();
cellRecord.setRow( rowNum + n );
row2Replace.createCellFromRecord( cellRecord );
sheet.addValueRecord( rowNum + n, cellRecord );
}
// Now zap all the cells in the source row
row.removeAllCells();
// Move comments from the source row to the
// destination row. Note that comments can
// exist for cells which are null
if(moveComments) {
for( short col = firstCol; col <= lastCol; col++ ) {
HSSFComment comment = getCellComment(rowNum, col);
if (comment != null) {
comment.setRow(rowNum + n);
}
}
}
}
if ( endRow == lastrow || endRow + n > lastrow ) lastrow = Math.min( endRow + n, 65535 );
if ( startRow == firstrow || startRow + n < firstrow ) firstrow = Math.max( startRow + n, 0 );
// Update any formulas on this sheet that point to
// rows which have been moved
updateFormulasAfterShift(startRow, endRow, n);
}
/**
* Called by shiftRows to update formulas on this sheet
* to point to the new location of moved rows
*/
private void updateFormulasAfterShift(int startRow, int endRow, int n) {
// Need to look at every cell on the sheet
// Not just those that were moved
Iterator ri = rowIterator();
while(ri.hasNext()) {
HSSFRow r = (HSSFRow)ri.next();
Iterator ci = r.cellIterator();
while(ci.hasNext()) {
HSSFCell c = (HSSFCell)ci.next();
if(c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
// Since it's a formula cell, process the
// formula string, and look to see if
// it contains any references
FormulaParser fp = new FormulaParser(c.getCellFormula(), workbook);
fp.parse();
// Look for references, and update if needed
Ptg[] ptgs = fp.getRPNPtg();
boolean changed = false;
for(int i=0; i<ptgs.length; i++) {
if(ptgs[i] instanceof RefPtg) {
RefPtg rptg = (RefPtg)ptgs[i];
if(startRow <= rptg.getRowAsInt() &&
rptg.getRowAsInt() <= endRow) {
// References a row that moved
rptg.setRow(rptg.getRowAsInt() + n);
changed = true;
}
}
}
// If any references were changed, then
// re-create the formula string
if(changed) {
c.setCellFormula(
fp.toFormulaString(ptgs)
);
}
}
}
}
}
protected void insertChartRecords( List records )
{
int window2Loc = sheet.findFirstRecordLocBySid( WindowTwoRecord.sid );
sheet.getRecords().addAll( window2Loc, records );
}
/**
* Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
* @param colSplit Horizonatal position of split.
* @param rowSplit Vertical position of split.
* @param topRow Top row visible in bottom pane
* @param leftmostColumn Left column visible in right pane.
*/
public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow )
{
if (colSplit < 0 || colSplit > 255) throw new IllegalArgumentException("Column must be between 0 and 255");
if (rowSplit < 0 || rowSplit > 65535) throw new IllegalArgumentException("Row must be between 0 and 65535");
if (leftmostColumn < colSplit) throw new IllegalArgumentException("leftmostColumn parameter must not be less than colSplit parameter");
if (topRow < rowSplit) throw new IllegalArgumentException("topRow parameter must not be less than leftmostColumn parameter");
getSheet().createFreezePane( colSplit, rowSplit, topRow, leftmostColumn );
}
/**
* Creates a split (freezepane). Any existing freezepane or split pane is overwritten.
* @param colSplit Horizonatal position of split.
* @param rowSplit Vertical position of split.
*/
public void createFreezePane( int colSplit, int rowSplit )
{
createFreezePane( colSplit, rowSplit, colSplit, rowSplit );
}
/**
* Creates a split pane. Any existing freezepane or split pane is overwritten.
* @param xSplitPos Horizonatal position of split (in 1/20th of a point).
* @param ySplitPos Vertical position of split (in 1/20th of a point).
* @param topRow Top row visible in bottom pane
* @param leftmostColumn Left column visible in right pane.
* @param activePane Active pane. One of: PANE_LOWER_RIGHT,
* PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT
* @see #PANE_LOWER_LEFT
* @see #PANE_LOWER_RIGHT
* @see #PANE_UPPER_LEFT
* @see #PANE_UPPER_RIGHT
*/
public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane )
{
getSheet().createSplitPane( xSplitPos, ySplitPos, topRow, leftmostColumn, activePane );
}
/**
* Returns the information regarding the currently configured pane (split or freeze).
* @return null if no pane configured, or the pane information.
*/
public PaneInformation getPaneInformation() {
return getSheet().getPaneInformation();
}
/**
* Sets whether the gridlines are shown in a viewer.
* @param show whether to show gridlines or not
*/
public void setDisplayGridlines(boolean show) {
sheet.setDisplayGridlines(show);
}
/**
* Returns if gridlines are displayed.
* @return whether gridlines are displayed
*/
public boolean isDisplayGridlines() {
return sheet.isDisplayGridlines();
}
/**
* Sets whether the formulas are shown in a viewer.
* @param show whether to show formulas or not
*/
public void setDisplayFormulas(boolean show) {
sheet.setDisplayFormulas(show);
}
/**
* Returns if formulas are displayed.
* @return whether formulas are displayed
*/
public boolean isDisplayFormulas() {
return sheet.isDisplayFormulas();
}
/**
* Sets whether the RowColHeadings are shown in a viewer.
* @param show whether to show RowColHeadings or not
*/
public void setDisplayRowColHeadings(boolean show) {
sheet.setDisplayRowColHeadings(show);
}
/**
* Returns if RowColHeadings are displayed.
* @return whether RowColHeadings are displayed
*/
public boolean isDisplayRowColHeadings() {
return sheet.isDisplayRowColHeadings();
}
/**
* Sets a page break at the indicated row
* @param row FIXME: Document this!
*/
public void setRowBreak(int row) {
validateRow(row);
sheet.getPageSettings().setRowBreak(row, (short)0, (short)255);
}
/**
* @return <code>true</code> if there is a page break at the indicated row
*/
public boolean isRowBroken(int row) {
return sheet.getPageSettings().isRowBroken(row);
}
/**
* Removes the page break at the indicated row
*/
public void removeRowBreak(int row) {
sheet.getPageSettings().removeRowBreak(row);
}
/**
* @return row indexes of all the horizontal page breaks, never <code>null</code>
*/
public int[] getRowBreaks(){
//we can probably cache this information, but this should be a sparsely used function
return sheet.getPageSettings().getRowBreaks();
}
/**
* @return column indexes of all the vertical page breaks, never <code>null</code>
*/
public int[] getColumnBreaks(){
//we can probably cache this information, but this should be a sparsely used function
return sheet.getPageSettings().getColumnBreaks();
}
/**
* Sets a page break at the indicated column
* @param column
*/
public void setColumnBreak(short column) {
validateColumn(column);
sheet.getPageSettings().setColumnBreak(column, (short)0, (short)65535);
}
/**
* Determines if there is a page break at the indicated column
* @param column FIXME: Document this!
* @return FIXME: Document this!
*/
public boolean isColumnBroken(short column) {
return sheet.getPageSettings().isColumnBroken(column);
}
/**
* Removes a page break at the indicated column
* @param column
*/
public void removeColumnBreak(short column) {
sheet.getPageSettings().removeColumnBreak(column);
}
/**
* Runs a bounds check for row numbers
* @param row
*/
protected void validateRow(int row) {
if (row > 65535) throw new IllegalArgumentException("Maximum row number is 65535");
if (row < 0) throw new IllegalArgumentException("Minumum row number is 0");
}
/**
* Runs a bounds check for column numbers
* @param column
*/
protected void validateColumn(short column) {
if (column > 255) throw new IllegalArgumentException("Maximum column number is 255");
if (column < 0) throw new IllegalArgumentException("Minimum column number is 0");
}
/**
* Aggregates the drawing records and dumps the escher record hierarchy
* to the standard output.
*/
public void dumpDrawingRecords(boolean fat)
{
sheet.aggregateDrawingRecords(book.getDrawingManager(), false);
EscherAggregate r = (EscherAggregate) getSheet().findFirstRecordBySid(EscherAggregate.sid);
List escherRecords = r.getEscherRecords();
PrintWriter w = new PrintWriter(System.out);
for ( Iterator iterator = escherRecords.iterator(); iterator.hasNext(); )
{
EscherRecord escherRecord = (EscherRecord) iterator.next();
if (fat)
System.out.println(escherRecord.toString());
else
escherRecord.display(w, 0);
}
w.flush();
}
/**
* Creates the top-level drawing patriarch. This will have
* the effect of removing any existing drawings on this
* sheet.
* This may then be used to add graphics or charts
* @return The new patriarch.
*/
public HSSFPatriarch createDrawingPatriarch()
{
// Create the drawing group if it doesn't already exist.
book.createDrawingGroup();
sheet.aggregateDrawingRecords(book.getDrawingManager(), true);
EscherAggregate agg = (EscherAggregate) sheet.findFirstRecordBySid(EscherAggregate.sid);
HSSFPatriarch patriarch = new HSSFPatriarch(this, agg);
agg.clear(); // Initially the behaviour will be to clear out any existing shapes in the sheet when
// creating a new patriarch.
agg.setPatriarch(patriarch);
return patriarch;
}
/**
* Returns the agregate escher records for this sheet,
* it there is one.
* WARNING - calling this will trigger a parsing of the
* associated escher records. Any that aren't supported
* (such as charts and complex drawing types) will almost
* certainly be lost or corrupted when written out.
*/
public EscherAggregate getDrawingEscherAggregate() {
book.findDrawingGroup();
// If there's now no drawing manager, then there's
// no drawing escher records on the workbook
if(book.getDrawingManager() == null) {
return null;
}
int found = sheet.aggregateDrawingRecords(
book.getDrawingManager(), false
);
if(found == -1) {
// Workbook has drawing stuff, but this sheet doesn't
return null;
}
// Grab our aggregate record, and wire it up
EscherAggregate agg = (EscherAggregate) sheet.findFirstRecordBySid(EscherAggregate.sid);
return agg;
}
/**
* Returns the top-level drawing patriach, if there is
* one.
* This will hold any graphics or charts for the sheet.
* WARNING - calling this will trigger a parsing of the
* associated escher records. Any that aren't supported
* (such as charts and complex drawing types) will almost
* certainly be lost or corrupted when written out. Only
* use this with simple drawings, otherwise call
* {@link HSSFSheet#createDrawingPatriarch()} and
* start from scratch!
*/
public HSSFPatriarch getDrawingPatriarch() {
EscherAggregate agg = getDrawingEscherAggregate();
if(agg == null) return null;
HSSFPatriarch patriarch = new HSSFPatriarch(this, agg);
agg.setPatriarch(patriarch);
// Have it process the records into high level objects
// as best it can do (this step may eat anything
// that isn't supported, you were warned...)
agg.convertRecordsToUserModel();
// Return what we could cope with
return patriarch;
}
/**
* Expands or collapses a column group.
*
* @param columnNumber One of the columns in the group.
* @param collapsed true = collapse group, false = expand group.
*/
public void setColumnGroupCollapsed( short columnNumber, boolean collapsed )
{
sheet.setColumnGroupCollapsed( columnNumber, collapsed );
}
/**
* Create an outline for the provided column range.
*
* @param fromColumn beginning of the column range.
* @param toColumn end of the column range.
*/
public void groupColumn(short fromColumn, short toColumn)
{
sheet.groupColumnRange( fromColumn, toColumn, true );
}
public void ungroupColumn( short fromColumn, short toColumn )
{
sheet.groupColumnRange( fromColumn, toColumn, false );
}
public void groupRow(int fromRow, int toRow)
{
sheet.groupRowRange( fromRow, toRow, true );
}
public void ungroupRow(int fromRow, int toRow)
{
sheet.groupRowRange( fromRow, toRow, false );
}
public void setRowGroupCollapsed( int row, boolean collapse )
{
sheet.setRowGroupCollapsed( row, collapse );
}
/**
* Sets the default column style for a given column. POI will only apply this style to new cells added to the sheet.
*
* @param column the column index
* @param style the style to set
*/
public void setDefaultColumnStyle(short column, HSSFCellStyle style) {
sheet.setColumn(column, new Short(style.getIndex()), null, null, null, null);
}
/**
* Adjusts the column width to fit the contents.
*
* This process can be relatively slow on large sheets, so this should
* normally only be called once per column, at the end of your
* processing.
*
* @param column the column index
*/
public void autoSizeColumn(short column) {
autoSizeColumn(column, false);
}
/**
* Adjusts the column width to fit the contents.
*
* This process can be relatively slow on large sheets, so this should
* normally only be called once per column, at the end of your
* processing.
*
* You can specify whether the content of merged cells should be considered or ignored.
* Default is to ignore merged cells.
*
* @param column the column index
* @param useMergedCells whether to use the contents of merged cells when calculating the width of the column
*/
public void autoSizeColumn(short column, boolean useMergedCells) {
AttributedString str;
TextLayout layout;
/**
* Excel measures columns in units of 1/256th of a character width
* but the docs say nothing about what particular character is used.
* '0' looks to be a good choice.
*/
char defaultChar = '0';
/**
* This is the multiple that the font height is scaled by when determining the
* boundary of rotated text.
*/
double fontHeightMultiple = 2.0;
FontRenderContext frc = new FontRenderContext(null, true, true);
HSSFWorkbook wb = new HSSFWorkbook(book);
HSSFFont defaultFont = wb.getFontAt((short) 0);
str = new AttributedString("" + defaultChar);
copyAttributes(defaultFont, str, 0, 1);
layout = new TextLayout(str.getIterator(), frc);
int defaultCharWidth = (int)layout.getAdvance();
double width = -1;
rows:
for (Iterator it = rowIterator(); it.hasNext();) {
HSSFRow row = (HSSFRow) it.next();
HSSFCell cell = row.getCell(column);
if (cell == null) {
continue;
}
int colspan = 1;
for (int i = 0 ; i < getNumMergedRegions(); i++) {
CellRangeAddress region = getMergedRegion(i);
if (containsCell(region, row.getRowNum(), column)) {
if (!useMergedCells) {
// If we're not using merged cells, skip this one and move on to the next.
continue rows;
}
cell = row.getCell(region.getFirstColumn());
colspan = 1 + region.getLastColumn() - region.getFirstColumn();
}
}
HSSFCellStyle style = cell.getCellStyle();
HSSFFont font = wb.getFontAt(style.getFontIndex());
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
HSSFRichTextString rt = cell.getRichStringCellValue();
String[] lines = rt.getString().split("\\n");
for (int i = 0; i < lines.length; i++) {
String txt = lines[i] + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
if (rt.numFormattingRuns() > 0) {
for (int j = 0; j < lines[i].length(); j++) {
int idx = rt.getFontAtIndex(j);
if (idx != 0) {
HSSFFont fnt = wb.getFontAt((short) idx);
copyAttributes(fnt, str, j, j + 1);
}
}
}
layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
} else {
String sval = null;
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String format = style.getDataFormatString().replaceAll("\"", "");
double value = cell.getNumericCellValue();
try {
NumberFormat fmt;
if ("General".equals(format))
sval = "" + value;
else
{
fmt = new DecimalFormat(format);
sval = fmt.format(value);
}
} catch (Exception e) {
sval = "" + value;
}
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
sval = String.valueOf(cell.getBooleanCellValue());
}
if(sval != null) {
String txt = sval + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
}
}
if (width != -1) {
+ width *= 256;
if (width > Short.MAX_VALUE) { //width can be bigger that Short.MAX_VALUE!
width = Short.MAX_VALUE;
}
- sheet.setColumnWidth(column, (short) (width * 256));
+ sheet.setColumnWidth(column, (short) (width));
}
}
/**
* Copy text attributes from the supplied HSSFFont to Java2D AttributedString
*/
private void copyAttributes(HSSFFont font, AttributedString str, int startIdx, int endIdx) {
str.addAttribute(TextAttribute.FAMILY, font.getFontName(), startIdx, endIdx);
str.addAttribute(TextAttribute.SIZE, new Float(font.getFontHeightInPoints()));
if (font.getBoldweight() == HSSFFont.BOLDWEIGHT_BOLD) str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx);
if (font.getItalic() ) str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx);
if (font.getUnderline() == HSSFFont.U_SINGLE ) str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx);
}
/**
* Returns cell comment for the specified row and column
*
* @return cell comment or <code>null</code> if not found
*/
public HSSFComment getCellComment(int row, int column) {
// Don't call findCellComment directly, otherwise
// two calls to this method will result in two
// new HSSFComment instances, which is bad
HSSFRow r = getRow(row);
if(r != null) {
HSSFCell c = r.getCell((short)column);
if(c != null) {
return c.getCellComment();
} else {
// No cell, so you will get new
// objects every time, sorry...
return HSSFCell.findCellComment(sheet, row, column);
}
}
return null;
}
public HSSFSheetConditionalFormatting getSheetConditionalFormatting() {
return new HSSFSheetConditionalFormatting(workbook, sheet);
}
}
| false | true | public void autoSizeColumn(short column, boolean useMergedCells) {
AttributedString str;
TextLayout layout;
/**
* Excel measures columns in units of 1/256th of a character width
* but the docs say nothing about what particular character is used.
* '0' looks to be a good choice.
*/
char defaultChar = '0';
/**
* This is the multiple that the font height is scaled by when determining the
* boundary of rotated text.
*/
double fontHeightMultiple = 2.0;
FontRenderContext frc = new FontRenderContext(null, true, true);
HSSFWorkbook wb = new HSSFWorkbook(book);
HSSFFont defaultFont = wb.getFontAt((short) 0);
str = new AttributedString("" + defaultChar);
copyAttributes(defaultFont, str, 0, 1);
layout = new TextLayout(str.getIterator(), frc);
int defaultCharWidth = (int)layout.getAdvance();
double width = -1;
rows:
for (Iterator it = rowIterator(); it.hasNext();) {
HSSFRow row = (HSSFRow) it.next();
HSSFCell cell = row.getCell(column);
if (cell == null) {
continue;
}
int colspan = 1;
for (int i = 0 ; i < getNumMergedRegions(); i++) {
CellRangeAddress region = getMergedRegion(i);
if (containsCell(region, row.getRowNum(), column)) {
if (!useMergedCells) {
// If we're not using merged cells, skip this one and move on to the next.
continue rows;
}
cell = row.getCell(region.getFirstColumn());
colspan = 1 + region.getLastColumn() - region.getFirstColumn();
}
}
HSSFCellStyle style = cell.getCellStyle();
HSSFFont font = wb.getFontAt(style.getFontIndex());
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
HSSFRichTextString rt = cell.getRichStringCellValue();
String[] lines = rt.getString().split("\\n");
for (int i = 0; i < lines.length; i++) {
String txt = lines[i] + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
if (rt.numFormattingRuns() > 0) {
for (int j = 0; j < lines[i].length(); j++) {
int idx = rt.getFontAtIndex(j);
if (idx != 0) {
HSSFFont fnt = wb.getFontAt((short) idx);
copyAttributes(fnt, str, j, j + 1);
}
}
}
layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
} else {
String sval = null;
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String format = style.getDataFormatString().replaceAll("\"", "");
double value = cell.getNumericCellValue();
try {
NumberFormat fmt;
if ("General".equals(format))
sval = "" + value;
else
{
fmt = new DecimalFormat(format);
sval = fmt.format(value);
}
} catch (Exception e) {
sval = "" + value;
}
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
sval = String.valueOf(cell.getBooleanCellValue());
}
if(sval != null) {
String txt = sval + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
}
}
if (width != -1) {
if (width > Short.MAX_VALUE) { //width can be bigger that Short.MAX_VALUE!
width = Short.MAX_VALUE;
}
sheet.setColumnWidth(column, (short) (width * 256));
}
}
| public void autoSizeColumn(short column, boolean useMergedCells) {
AttributedString str;
TextLayout layout;
/**
* Excel measures columns in units of 1/256th of a character width
* but the docs say nothing about what particular character is used.
* '0' looks to be a good choice.
*/
char defaultChar = '0';
/**
* This is the multiple that the font height is scaled by when determining the
* boundary of rotated text.
*/
double fontHeightMultiple = 2.0;
FontRenderContext frc = new FontRenderContext(null, true, true);
HSSFWorkbook wb = new HSSFWorkbook(book);
HSSFFont defaultFont = wb.getFontAt((short) 0);
str = new AttributedString("" + defaultChar);
copyAttributes(defaultFont, str, 0, 1);
layout = new TextLayout(str.getIterator(), frc);
int defaultCharWidth = (int)layout.getAdvance();
double width = -1;
rows:
for (Iterator it = rowIterator(); it.hasNext();) {
HSSFRow row = (HSSFRow) it.next();
HSSFCell cell = row.getCell(column);
if (cell == null) {
continue;
}
int colspan = 1;
for (int i = 0 ; i < getNumMergedRegions(); i++) {
CellRangeAddress region = getMergedRegion(i);
if (containsCell(region, row.getRowNum(), column)) {
if (!useMergedCells) {
// If we're not using merged cells, skip this one and move on to the next.
continue rows;
}
cell = row.getCell(region.getFirstColumn());
colspan = 1 + region.getLastColumn() - region.getFirstColumn();
}
}
HSSFCellStyle style = cell.getCellStyle();
HSSFFont font = wb.getFontAt(style.getFontIndex());
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
HSSFRichTextString rt = cell.getRichStringCellValue();
String[] lines = rt.getString().split("\\n");
for (int i = 0; i < lines.length; i++) {
String txt = lines[i] + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
if (rt.numFormattingRuns() > 0) {
for (int j = 0; j < lines[i].length(); j++) {
int idx = rt.getFontAtIndex(j);
if (idx != 0) {
HSSFFont fnt = wb.getFontAt((short) idx);
copyAttributes(fnt, str, j, j + 1);
}
}
}
layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
} else {
String sval = null;
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String format = style.getDataFormatString().replaceAll("\"", "");
double value = cell.getNumericCellValue();
try {
NumberFormat fmt;
if ("General".equals(format))
sval = "" + value;
else
{
fmt = new DecimalFormat(format);
sval = fmt.format(value);
}
} catch (Exception e) {
sval = "" + value;
}
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
sval = String.valueOf(cell.getBooleanCellValue());
}
if(sval != null) {
String txt = sval + defaultChar;
str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
layout = new TextLayout(str.getIterator(), frc);
if(style.getRotation() != 0){
/*
* Transform the text using a scale so that it's height is increased by a multiple of the leading,
* and then rotate the text before computing the bounds. The scale results in some whitespace around
* the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
* is added by the standard Excel autosize.
*/
AffineTransform trans = new AffineTransform();
trans.concatenate(AffineTransform.getRotateInstance(style.getRotation()*2.0*Math.PI/360.0));
trans.concatenate(
AffineTransform.getScaleInstance(1, fontHeightMultiple)
);
width = Math.max(width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
} else {
width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention());
}
}
}
}
if (width != -1) {
width *= 256;
if (width > Short.MAX_VALUE) { //width can be bigger that Short.MAX_VALUE!
width = Short.MAX_VALUE;
}
sheet.setColumnWidth(column, (short) (width));
}
}
|
diff --git a/platform/src/main/java/gov/nasa/arc/mct/gui/housing/MCTStandardHousing.java b/platform/src/main/java/gov/nasa/arc/mct/gui/housing/MCTStandardHousing.java
index 610eede..92a8401 100644
--- a/platform/src/main/java/gov/nasa/arc/mct/gui/housing/MCTStandardHousing.java
+++ b/platform/src/main/java/gov/nasa/arc/mct/gui/housing/MCTStandardHousing.java
@@ -1,394 +1,394 @@
/*******************************************************************************
* Mission Control Technologies, Copyright (c) 2009-2012, United States Government
* as represented by the Administrator of the National Aeronautics and Space
* Administration. All rights reserved.
*
* The MCT platform is 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.
*
* MCT includes source code licensed under additional open source licenses. See
* the MCT Open Source Licenses file included with this distribution or the About
* MCT Licenses dialog available at runtime from the MCT Help menu for additional
* information.
*******************************************************************************/
/**
* MCTStandardHousing.java Aug 18, 2008
*
* This code is property of the National Aeronautics and Space Administration
* and was produced for the Mission Control Technologies (MCT) Project.
*
*/
package gov.nasa.arc.mct.gui.housing;
import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.context.GlobalContext;
import gov.nasa.arc.mct.defaults.view.MCTHousingViewManifestation;
import gov.nasa.arc.mct.gui.OptionBox;
import gov.nasa.arc.mct.gui.SelectionProvider;
import gov.nasa.arc.mct.gui.TwiddleView;
import gov.nasa.arc.mct.gui.View;
import gov.nasa.arc.mct.gui.ViewProvider;
import gov.nasa.arc.mct.gui.housing.registry.UserEnvironmentRegistry;
import gov.nasa.arc.mct.osgi.platform.EquinoxOSGIRuntimeImpl;
import gov.nasa.arc.mct.osgi.platform.OSGIRuntime;
import gov.nasa.arc.mct.platform.spi.PlatformAccess;
import gov.nasa.arc.mct.services.component.ViewType;
import java.awt.GraphicsConfiguration;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.swing.JPanel;
import org.slf4j.LoggerFactory;
/**
* A panel which contains the standard 3 section housing: a directory area, a
* content area, and an inspector area.
*
* TODO: Move the tree code elsewhere
*
* @author asi
*
*/
@SuppressWarnings("serial")
public class MCTStandardHousing extends MCTAbstractHousing implements TwiddleView {
private static final ResourceBundle BUNDLE =
ResourceBundle.getBundle(
MCTStandardHousing.class.getName().substring(0,
MCTStandardHousing.class.getName().lastIndexOf("."))+".Bundle");
private final Map<String, MCTHousingViewManifestation> housedManifestations = new HashMap<String, MCTHousingViewManifestation>();
private int width;
private int height;
private MCTHousingViewManifestation housingViewManifestation;
private final JPanel displayPanel = new JPanel(new GridLayout());
private SelectionProvider selectionProvider;
private final List<WeakReference<ControlProvider>> controlAreas = new ArrayList<WeakReference<ControlProvider>>();
public MCTStandardHousing(int width, int height, int closeAction, View housingView) {
this(GlobalContext.getGlobalContext().getUser().getUserId() + "'s User Environment", width, height,
closeAction, housingView);
}
public MCTStandardHousing(GraphicsConfiguration gc, String title, int width, int height, int closeAction,
View housingView) {
super(gc, housingView.getManifestedComponent().getId());
getContentPane().setLayout(new GridLayout());
this.width = width;
this.height = height;
setSize(this.width, this.height);
displayPanel.setSize(this.width, this.height);
setTitle(title);
setIconImage(housingView.getManifestedComponent().getIcon().getImage());
setDefaultCloseOperation(closeAction);
MCTHousingViewManifestation housingManifestation = (MCTHousingViewManifestation) housingView;
setHousingViewManifesation(housingManifestation);
addWindowListenerToHousing();
getContentPane().add(displayPanel);
}
public MCTStandardHousing(String title, int width, int height, int closeAction,
View housingView) {
super(housingView.getManifestedComponent().getId());
getContentPane().setLayout(new GridLayout());
this.width = width;
this.height = height;
setSize(this.width, this.height);
displayPanel.setSize(this.width, this.height);
setTitle(title);
setIconImage(housingView.getManifestedComponent().getIcon().getImage());
setDefaultCloseOperation(closeAction);
MCTHousingViewManifestation housingManifestation = (MCTHousingViewManifestation) housingView;
setHousingViewManifesation(housingManifestation);
addWindowListenerToHousing();
getContentPane().add(displayPanel);
}
@Override
public SelectionProvider getSelectionProvider() {
return selectionProvider;
}
public MCTHousingViewManifestation showHousedManifestationIfPresent(String manifestedType) {
MCTHousingViewManifestation targetViewManifestation = this.housedManifestations.get(manifestedType);
if (targetViewManifestation != null) {
showHousedViewManifestation(manifestedType);
}
return targetViewManifestation;
}
/**
* Swaps housing view manifestation.
*
* @param housingViewManifestation
*/
public void setHousingViewManifesation(MCTHousingViewManifestation housingViewManifestation) {
String viewName = housingViewManifestation.getInfo().getViewName();
housingViewManifestation.setParentHousing(this);
housingViewManifestation.setVisible(true);
housedManifestations.put(viewName, housingViewManifestation);
showHousedViewManifestation(viewName);
selectionProvider = housingViewManifestation.getSelectionProvider();
if (selectionProvider == null) {
throw new IllegalArgumentException("housing view role " + housingViewManifestation.getClass().getName()
+ " must not return null from getSelectionProvider");
}
}
private void showHousedViewManifestation(String manifestedType) {
MCTHousingViewManifestation displayedViewManifestation = housedManifestations.get(manifestedType);
displayPanel.removeAll();
this.housingViewManifestation = displayedViewManifestation;
displayPanel.add(this.housingViewManifestation);
displayPanel.revalidate();
}
private void addWindowListenerToHousing() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (UserEnvironmentRegistry.getHousingCount() == 1) {
Object[] options = { "Shut Down-Exit-All of MCT", "Cancel the Shutdown" };
String message = "<HTML><B>All of MCT Will Close, Stop, Exit, & Shut Down</B><BR>"
+ "<UL>- All MCT windows will close.</UL>"
+ "<UL>- All MCT processes will stop.</UL>"
+ "<UL>- The next MCT object you open will take longer to open as the <BR> underlying processes restart.</UL>"
+ "<UL>- To instead close all MCT windows but one: In any MCT window, <BR> pull down the Windows menu and choose <BR> \"Close All MCT Windows but This One.\"</UL>"
+ "</HTML>";
int answer = OptionBox.showOptionDialog(MCTStandardHousing.this,
message,
"Exit-Shut Down-All MCT Windows & Processes",
OptionBox.YES_NO_OPTION,
OptionBox.WARNING_MESSAGE,
null, options, options[0]);
switch (answer) {
case OptionBox.YES_OPTION:
OSGIRuntime osgiRuntime = EquinoxOSGIRuntimeImpl.getOSGIRuntime();
try {
osgiRuntime.stopOSGI();
} catch (Exception e1) {
LoggerFactory.getLogger(MCTStandardHousing.class).warn(e1.getMessage(), e1);
}
disposeHousing();
System.exit(0);
break;
default:
break;
}
} else {
boolean toCloseWindow = true;
MCTContentArea centerPane = housingViewManifestation.getContentArea();
if (centerPane != null) {
View centerPaneView = centerPane.getHousedViewManifestation();
if (centerPaneView.getManifestedComponent().isDirty()) {
toCloseWindow = commitOrAbortPendingChanges(centerPaneView,
MessageFormat.format(BUNDLE.getString("centerpane.modified.alert.text"),
centerPaneView.getInfo().getViewName(),
centerPaneView.getManifestedComponent().getDisplayName()));
}
}
View inspectionArea = housingViewManifestation.getInspectionArea();
if (inspectionArea != null) {
View inspectorPaneView = inspectionArea.getHousedViewManifestation();
if (inspectorPaneView.getManifestedComponent().isDirty()) {
toCloseWindow = commitOrAbortPendingChanges(inspectionArea,
MessageFormat.format(BUNDLE.getString("inspectorpane.modified.alert.text"),
inspectorPaneView.getInfo().getViewName(),
inspectorPaneView.getManifestedComponent().getDisplayName()));
}
}
if (toCloseWindow)
disposeHousing();
}
}
/**
* Prompts users to commit or abort pending changes in view.
* @param view the modified view
* @param dialogMessage the dialog message which differs from where the view is located (in the center or inspector pane)
* @return true to keep the window open, false to close the window
*/
private boolean commitOrAbortPendingChanges(View view, String dialogMessage) {
Object[] options = {
BUNDLE.getString("view.modified.alert.save"),
BUNDLE.getString("view.modified.alert.abort"),
BUNDLE.getString("view.modified.alert.cancel"),
};
int answer = OptionBox.showOptionDialog(view,
dialogMessage,
BUNDLE.getString("view.modified.alert.title"),
OptionBox.YES_NO_CANCEL_OPTION,
OptionBox.WARNING_MESSAGE,
null,
options, options[0]);
switch (answer) {
case OptionBox.CANCEL_OPTION:
- return true;
+ return false;
case OptionBox.YES_OPTION:
PlatformAccess.getPlatform().getPersistenceProvider().persist(Collections.singleton(view.getManifestedComponent()));
default:
- return false;
+ return true;
}
}
});
}
public void buildGUI() {
this.housingViewManifestation.buildGUI();
}
public void setControlArea(MCTControlArea controlArea) {
this.housingViewManifestation.setControlArea(controlArea);
}
public void setControlAreaVisible(boolean flag) {
if (this.housingViewManifestation != null)
this.housingViewManifestation.setControlAreaVisible(flag);
}
public boolean isControlAreaVisible() {
return this.housingViewManifestation.isControlAreaVisible();
}
public void setDirectoryArea(View directoryArea) {
if (directoryArea instanceof ControlProvider) {
addControlArea((ControlProvider)directoryArea);
}
this.housingViewManifestation.setDirectoryArea(directoryArea);
}
public void setContentArea(MCTContentArea contentArea) {
addControlArea(contentArea);
this.housingViewManifestation.setContentArea(contentArea);
}
public void setInspectionArea(View inspectionArea) {
if (inspectionArea instanceof ControlProvider) {
addControlArea((ControlProvider)inspectionArea);
}
this.housingViewManifestation.setInspectionArea(inspectionArea);
}
@Override
public View getInspectionArea() {
return this.housingViewManifestation.getInspectionArea();
}
@Override
public View getDirectoryArea() {
return this.housingViewManifestation.getDirectoryArea();
}
@Override
public MCTContentArea getContentArea() {
return this.housingViewManifestation.getContentArea();
}
@Override
public MCTControlArea getControlArea() {
return this.housingViewManifestation.getControlArea();
}
@Override
public View getCurrentManifestation() {
return this.housingViewManifestation.getCurrentManifestation();
}
public AbstractComponent getWindowComponent() {
return this.housingViewManifestation.getManifestedComponent();
}
@Override
public View getHousedViewManifestation() {
return housingViewManifestation;
}
@Override
public Collection<ViewProvider> getHousedManifestationProviders() {
List<ViewProvider> housedProviders = new ArrayList<ViewProvider>();
if (getDirectoryArea() != null) {
housedProviders.add(getDirectoryArea());
}
if (getContentArea() != null) {
housedProviders.add(getContentArea());
}
return housedProviders;
}
@Override
public void setStatusArea(MCTStatusArea statusArea) {
this.housingViewManifestation.setStatusArea(statusArea);
}
@Override
public MCTStatusArea getStatusArea() {
return this.housingViewManifestation.getStatusArea();
}
@Override
public void toggleControlAreas(boolean showing) {
Iterator<WeakReference<ControlProvider>> it = controlAreas.iterator();
while (it.hasNext()) {
ControlProvider cp = it.next().get();
if (cp == null) {
it.remove();
} else {
cp.showControl(showing);
}
}
}
@Override
public void addControlArea(ControlProvider provider) {
controlAreas.add(new WeakReference<ControlProvider>(provider));
}
private void disposeHousing() {
UserEnvironmentRegistry.removeHousing(this);
dispose();
}
@Override
public void enterTwiddleMode(AbstractComponent twiddledComponent) {
MCTHousingFactory.refreshHousing(this,twiddledComponent.getViewInfos(ViewType.LAYOUT).iterator().next().createView(twiddledComponent));
}
@Override
public void exitTwiddleMode(AbstractComponent originalComponent) {
MCTHousingFactory.refreshHousing(this, originalComponent.getViewInfos(ViewType.LAYOUT).iterator().next().createView(originalComponent));
}
}
| false | true | private void addWindowListenerToHousing() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (UserEnvironmentRegistry.getHousingCount() == 1) {
Object[] options = { "Shut Down-Exit-All of MCT", "Cancel the Shutdown" };
String message = "<HTML><B>All of MCT Will Close, Stop, Exit, & Shut Down</B><BR>"
+ "<UL>- All MCT windows will close.</UL>"
+ "<UL>- All MCT processes will stop.</UL>"
+ "<UL>- The next MCT object you open will take longer to open as the <BR> underlying processes restart.</UL>"
+ "<UL>- To instead close all MCT windows but one: In any MCT window, <BR> pull down the Windows menu and choose <BR> \"Close All MCT Windows but This One.\"</UL>"
+ "</HTML>";
int answer = OptionBox.showOptionDialog(MCTStandardHousing.this,
message,
"Exit-Shut Down-All MCT Windows & Processes",
OptionBox.YES_NO_OPTION,
OptionBox.WARNING_MESSAGE,
null, options, options[0]);
switch (answer) {
case OptionBox.YES_OPTION:
OSGIRuntime osgiRuntime = EquinoxOSGIRuntimeImpl.getOSGIRuntime();
try {
osgiRuntime.stopOSGI();
} catch (Exception e1) {
LoggerFactory.getLogger(MCTStandardHousing.class).warn(e1.getMessage(), e1);
}
disposeHousing();
System.exit(0);
break;
default:
break;
}
} else {
boolean toCloseWindow = true;
MCTContentArea centerPane = housingViewManifestation.getContentArea();
if (centerPane != null) {
View centerPaneView = centerPane.getHousedViewManifestation();
if (centerPaneView.getManifestedComponent().isDirty()) {
toCloseWindow = commitOrAbortPendingChanges(centerPaneView,
MessageFormat.format(BUNDLE.getString("centerpane.modified.alert.text"),
centerPaneView.getInfo().getViewName(),
centerPaneView.getManifestedComponent().getDisplayName()));
}
}
View inspectionArea = housingViewManifestation.getInspectionArea();
if (inspectionArea != null) {
View inspectorPaneView = inspectionArea.getHousedViewManifestation();
if (inspectorPaneView.getManifestedComponent().isDirty()) {
toCloseWindow = commitOrAbortPendingChanges(inspectionArea,
MessageFormat.format(BUNDLE.getString("inspectorpane.modified.alert.text"),
inspectorPaneView.getInfo().getViewName(),
inspectorPaneView.getManifestedComponent().getDisplayName()));
}
}
if (toCloseWindow)
disposeHousing();
}
}
/**
* Prompts users to commit or abort pending changes in view.
* @param view the modified view
* @param dialogMessage the dialog message which differs from where the view is located (in the center or inspector pane)
* @return true to keep the window open, false to close the window
*/
private boolean commitOrAbortPendingChanges(View view, String dialogMessage) {
Object[] options = {
BUNDLE.getString("view.modified.alert.save"),
BUNDLE.getString("view.modified.alert.abort"),
BUNDLE.getString("view.modified.alert.cancel"),
};
int answer = OptionBox.showOptionDialog(view,
dialogMessage,
BUNDLE.getString("view.modified.alert.title"),
OptionBox.YES_NO_CANCEL_OPTION,
OptionBox.WARNING_MESSAGE,
null,
options, options[0]);
switch (answer) {
case OptionBox.CANCEL_OPTION:
return true;
case OptionBox.YES_OPTION:
PlatformAccess.getPlatform().getPersistenceProvider().persist(Collections.singleton(view.getManifestedComponent()));
default:
return false;
}
}
});
}
| private void addWindowListenerToHousing() {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (UserEnvironmentRegistry.getHousingCount() == 1) {
Object[] options = { "Shut Down-Exit-All of MCT", "Cancel the Shutdown" };
String message = "<HTML><B>All of MCT Will Close, Stop, Exit, & Shut Down</B><BR>"
+ "<UL>- All MCT windows will close.</UL>"
+ "<UL>- All MCT processes will stop.</UL>"
+ "<UL>- The next MCT object you open will take longer to open as the <BR> underlying processes restart.</UL>"
+ "<UL>- To instead close all MCT windows but one: In any MCT window, <BR> pull down the Windows menu and choose <BR> \"Close All MCT Windows but This One.\"</UL>"
+ "</HTML>";
int answer = OptionBox.showOptionDialog(MCTStandardHousing.this,
message,
"Exit-Shut Down-All MCT Windows & Processes",
OptionBox.YES_NO_OPTION,
OptionBox.WARNING_MESSAGE,
null, options, options[0]);
switch (answer) {
case OptionBox.YES_OPTION:
OSGIRuntime osgiRuntime = EquinoxOSGIRuntimeImpl.getOSGIRuntime();
try {
osgiRuntime.stopOSGI();
} catch (Exception e1) {
LoggerFactory.getLogger(MCTStandardHousing.class).warn(e1.getMessage(), e1);
}
disposeHousing();
System.exit(0);
break;
default:
break;
}
} else {
boolean toCloseWindow = true;
MCTContentArea centerPane = housingViewManifestation.getContentArea();
if (centerPane != null) {
View centerPaneView = centerPane.getHousedViewManifestation();
if (centerPaneView.getManifestedComponent().isDirty()) {
toCloseWindow = commitOrAbortPendingChanges(centerPaneView,
MessageFormat.format(BUNDLE.getString("centerpane.modified.alert.text"),
centerPaneView.getInfo().getViewName(),
centerPaneView.getManifestedComponent().getDisplayName()));
}
}
View inspectionArea = housingViewManifestation.getInspectionArea();
if (inspectionArea != null) {
View inspectorPaneView = inspectionArea.getHousedViewManifestation();
if (inspectorPaneView.getManifestedComponent().isDirty()) {
toCloseWindow = commitOrAbortPendingChanges(inspectionArea,
MessageFormat.format(BUNDLE.getString("inspectorpane.modified.alert.text"),
inspectorPaneView.getInfo().getViewName(),
inspectorPaneView.getManifestedComponent().getDisplayName()));
}
}
if (toCloseWindow)
disposeHousing();
}
}
/**
* Prompts users to commit or abort pending changes in view.
* @param view the modified view
* @param dialogMessage the dialog message which differs from where the view is located (in the center or inspector pane)
* @return true to keep the window open, false to close the window
*/
private boolean commitOrAbortPendingChanges(View view, String dialogMessage) {
Object[] options = {
BUNDLE.getString("view.modified.alert.save"),
BUNDLE.getString("view.modified.alert.abort"),
BUNDLE.getString("view.modified.alert.cancel"),
};
int answer = OptionBox.showOptionDialog(view,
dialogMessage,
BUNDLE.getString("view.modified.alert.title"),
OptionBox.YES_NO_CANCEL_OPTION,
OptionBox.WARNING_MESSAGE,
null,
options, options[0]);
switch (answer) {
case OptionBox.CANCEL_OPTION:
return false;
case OptionBox.YES_OPTION:
PlatformAccess.getPlatform().getPersistenceProvider().persist(Collections.singleton(view.getManifestedComponent()));
default:
return true;
}
}
});
}
|
diff --git a/src/main/java/org/spout/engine/world/RegionSource.java b/src/main/java/org/spout/engine/world/RegionSource.java
index 47b284f6f..5c79c15d8 100644
--- a/src/main/java/org/spout/engine/world/RegionSource.java
+++ b/src/main/java/org/spout/engine/world/RegionSource.java
@@ -1,195 +1,196 @@
/*
* This file is part of Spout (http://www.spout.org/).
*
* Spout is licensed under the SpoutDev License Version 1.
*
* Spout 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Spout 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.engine.world;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import org.spout.api.Spout;
import org.spout.api.event.world.RegionLoadEvent;
import org.spout.api.event.world.RegionUnloadEvent;
import org.spout.api.geo.LoadGenerateOption;
import org.spout.api.geo.cuboid.Chunk;
import org.spout.api.geo.cuboid.Region;
import org.spout.api.scheduler.TaskManager;
import org.spout.api.util.map.concurrent.TSyncInt21TripleObjectHashMap;
import org.spout.api.util.thread.DelayedWrite;
import org.spout.api.util.thread.LiveRead;
import org.spout.api.util.thread.SnapshotRead;
import org.spout.engine.scheduler.SpoutParallelTaskManager;
import org.spout.engine.scheduler.SpoutScheduler;
import org.spout.engine.util.thread.snapshotable.SnapshotManager;
public class RegionSource implements Iterable<Region> {
/**
* A map of loaded regions, mapped to their x and z values.
*/
private final TSyncInt21TripleObjectHashMap<Region> loadedRegions;
/**
* World associated with this region source
*/
private final SpoutWorld world;
public RegionSource(SpoutWorld world, SnapshotManager snapshotManager) {
this.world = world;
loadedRegions = new TSyncInt21TripleObjectHashMap<Region>();
}
/**
* Gets the region associated with the block x, y, z coordinates
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @return region, if it is loaded and exists
*/
@SnapshotRead
public SpoutRegion getRegionFromBlock(int x, int y, int z) {
return getRegionFromBlock(x, y, z, LoadGenerateOption.NO_LOAD);
}
/**
* Gets the region associated with the block x, y, z coordinates
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @param loadopt to control whether to load or generate the region, if needed
* @return region
*/
@LiveRead
public SpoutRegion getRegionFromBlock(int x, int y, int z, LoadGenerateOption loadopt) {
int shifts = Region.REGION_SIZE_BITS + Chunk.CHUNK_SIZE_BITS;
return getRegion(x >> shifts, y >> shifts, z >> shifts, loadopt);
}
@DelayedWrite
public void removeRegion(final SpoutRegion r) {
if (!r.getWorld().equals(world)) {
return;
}
// removeRegion is called during snapshot copy on the Region thread (when the last chunk is removed)
// Needs re-syncing to a safe moment
((SpoutScheduler)Spout.getEngine().getScheduler()).scheduleCoreTask(new Runnable() {
@Override
public void run() {
int x = r.getX();
int y = r.getY();
int z = r.getZ();
boolean success = loadedRegions.remove(x, y, z, r);
if (success) {
r.getManager().getExecutor().haltExecutor();
Spout.getEventManager().callDelayedEvent(new RegionUnloadEvent(world, r));
}
}
});
}
/**
* Gets the region associated with the region x, y, z coordinates
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @return region, if it is loaded and exists
*/
@LiveRead
public SpoutRegion getRegion(int x, int y, int z) {
return getRegion(x, y, z, LoadGenerateOption.NO_LOAD);
}
/**
* Gets the region associated with the region x, y, z coordinates <br/>
* <p/>
* Will load or generate a region if requested.
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @param loadopt whether to load or generate the region if one does not exist
* at the coordinates
* @return region
*/
@LiveRead
public SpoutRegion getRegion(int x, int y, int z, LoadGenerateOption loadopt) {
SpoutRegion region = (SpoutRegion) loadedRegions.get(x, y, z);
if (region != null || (!loadopt.loadIfNeeded())) {
return region;
} else {
/* If not generating region, and it doesn't exist yet, we're done */
if ((!loadopt.generateIfNeeded()) && (!SpoutRegion.regionFileExists(world, x, y, z))) {
return null;
}
region = new SpoutRegion(world, x, y, z, this);
SpoutRegion current = (SpoutRegion) loadedRegions.putIfAbsent(x, y, z, region);
if (current != null) {
+ ((SpoutScheduler)Spout.getScheduler()).removeAsyncExecutor(region.getManager().getExecutor());
return current;
} else {
if (!region.getManager().getExecutor().startExecutor()) {
throw new IllegalStateException("Unable to start region executor");
}
TaskManager tm = Spout.getEngine().getParallelTaskManager();
SpoutParallelTaskManager ptm = (SpoutParallelTaskManager)tm;
ptm.registerRegion(region);
TaskManager tmWorld = world.getParallelTaskManager();
SpoutParallelTaskManager ptmWorld = (SpoutParallelTaskManager)tmWorld;
ptmWorld.registerRegion(region);
Spout.getEventManager().callDelayedEvent(new RegionLoadEvent(world, region));
return region;
}
}
}
/**
* True if there is a region loaded at the region x, y, z coordinates
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coordinate
* @return true if there is a region loaded
*/
@LiveRead
public boolean hasRegion(int x, int y, int z) {
return loadedRegions.get(x, y, z) != null;
}
/**
* Gets an unmodifiable collection of all loaded regions.
* @return collection of all regions
*/
public Collection<Region> getRegions() {
return Collections.unmodifiableCollection(loadedRegions.valueCollection());
}
@Override
public Iterator<Region> iterator() {
return getRegions().iterator();
}
}
| true | true | public SpoutRegion getRegion(int x, int y, int z, LoadGenerateOption loadopt) {
SpoutRegion region = (SpoutRegion) loadedRegions.get(x, y, z);
if (region != null || (!loadopt.loadIfNeeded())) {
return region;
} else {
/* If not generating region, and it doesn't exist yet, we're done */
if ((!loadopt.generateIfNeeded()) && (!SpoutRegion.regionFileExists(world, x, y, z))) {
return null;
}
region = new SpoutRegion(world, x, y, z, this);
SpoutRegion current = (SpoutRegion) loadedRegions.putIfAbsent(x, y, z, region);
if (current != null) {
return current;
} else {
if (!region.getManager().getExecutor().startExecutor()) {
throw new IllegalStateException("Unable to start region executor");
}
TaskManager tm = Spout.getEngine().getParallelTaskManager();
SpoutParallelTaskManager ptm = (SpoutParallelTaskManager)tm;
ptm.registerRegion(region);
TaskManager tmWorld = world.getParallelTaskManager();
SpoutParallelTaskManager ptmWorld = (SpoutParallelTaskManager)tmWorld;
ptmWorld.registerRegion(region);
Spout.getEventManager().callDelayedEvent(new RegionLoadEvent(world, region));
return region;
}
}
}
| public SpoutRegion getRegion(int x, int y, int z, LoadGenerateOption loadopt) {
SpoutRegion region = (SpoutRegion) loadedRegions.get(x, y, z);
if (region != null || (!loadopt.loadIfNeeded())) {
return region;
} else {
/* If not generating region, and it doesn't exist yet, we're done */
if ((!loadopt.generateIfNeeded()) && (!SpoutRegion.regionFileExists(world, x, y, z))) {
return null;
}
region = new SpoutRegion(world, x, y, z, this);
SpoutRegion current = (SpoutRegion) loadedRegions.putIfAbsent(x, y, z, region);
if (current != null) {
((SpoutScheduler)Spout.getScheduler()).removeAsyncExecutor(region.getManager().getExecutor());
return current;
} else {
if (!region.getManager().getExecutor().startExecutor()) {
throw new IllegalStateException("Unable to start region executor");
}
TaskManager tm = Spout.getEngine().getParallelTaskManager();
SpoutParallelTaskManager ptm = (SpoutParallelTaskManager)tm;
ptm.registerRegion(region);
TaskManager tmWorld = world.getParallelTaskManager();
SpoutParallelTaskManager ptmWorld = (SpoutParallelTaskManager)tmWorld;
ptmWorld.registerRegion(region);
Spout.getEventManager().callDelayedEvent(new RegionLoadEvent(world, region));
return region;
}
}
}
|
diff --git a/src/dogfight_remake/main/Camera.java b/src/dogfight_remake/main/Camera.java
index c3fd994..9561869 100644
--- a/src/dogfight_remake/main/Camera.java
+++ b/src/dogfight_remake/main/Camera.java
@@ -1,234 +1,234 @@
package dogfight_remake.main;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.tiled.TiledMapPlus;
public class Camera {
/** the map used for our scene */
public TiledMapPlus map;
/** the number of tiles in x-direction (width) */
public int numTilesX;
/** the number of tiles in y-direction (height) */
public int numTilesY;
/** the height of the map in pixel */
public int mapHeight;
/** the width of the map in pixel */
public int mapWidth;
/** the width of one tile of the map in pixel */
public int tileWidth;
/** the height of one tile of the map in pixel */
public int tileHeight;
public GameContainer gc;
/** the x-position of our "camera" in pixel */
public float cameraX;
/** the y-position of our "camera" in pixel */
public float cameraY;
/**
* Create a new camera
*
* @param gc
* the GameContainer, used for getting the size of the GameCanvas
* @param map
* the TiledMap used for the current scene
*/
public Camera(GameContainer gc, TiledMapPlus map) {
this.map = map;
this.numTilesX = map.getWidth();
this.numTilesY = map.getHeight();
this.tileWidth = map.getTileWidth();
this.tileHeight = map.getTileHeight();
this.mapHeight = this.numTilesY * this.tileHeight;
this.mapWidth = this.numTilesX * this.tileWidth;
this.gc = gc;
}
/**
* "locks" the camera on the given coordinates. The camera tries to keep the
* location in it's center.
*
* @param x
* the real x-coordinate (in pixel) which should be centered on
* the screen
* @param y
* the real y-coordinate (in pixel) which should be centered on
* the screen
*/
public void centerOn(float x, float y, int id) {
// try to set the given position as center of the camera by default
if (Var.singlePlayer) {
cameraX = x - gc.getWidth() * 0.5f;
cameraY = y - gc.getHeight() * 0.5f;
// if the camera is at the right or left edge lock it to prevent a
// black bar
if (cameraX < 0)
cameraX = 0;
if (cameraX + gc.getWidth() > mapWidth)
cameraX = mapWidth - gc.getWidth();
// if the camera is at the top or bottom edge lock it to prevent a
// black bar
if (cameraY < 0) {
cameraY = 0;
}
if (cameraY + gc.getHeight() > mapHeight) {
cameraY = mapHeight - gc.getHeight();
}
} else if (!Var.singlePlayer) {
if (Var.vertical_split) {
cameraY = y - gc.getHeight() * 0.5f;
if (id == 1) {
cameraX = x - gc.getWidth() * 0.25f;
} else if (id == 2) {
cameraX = x - gc.getWidth() * 0.75f;
}
// if the camera is at the right or left edge lock it to prevent
// black bar
if (cameraX < 0 && id == 1) {
cameraX = 0;
} else if (cameraX < -gc.getScreenWidth() / 2 && id == 2) {
cameraX = -gc.getScreenWidth() / 2;
}
if (cameraX + gc.getWidth() * 0.5f > mapWidth && id == 1) {
cameraX = mapWidth - gc.getWidth() * 0.5f;
} else if (cameraX + gc.getWidth() > mapWidth && id == 2) {
cameraX = mapWidth - gc.getWidth();
}
// if the camera is at the top or bottom edge lock it to prevent
// black bar
if (cameraY < 0)
cameraY = 0;
if (cameraY + gc.getHeight() > mapHeight) {
cameraY = mapHeight - gc.getHeight();
}
} else if (!Var.vertical_split) {
cameraX = x - gc.getWidth() * 0.5f;
if (id == 1) {
cameraY = y - gc.getHeight() * 0.25f;
} else if (id == 2) {
cameraY = y - gc.getHeight() * 0.75f;
}
// if the camera is at the right or left edge lock it to prevent
// black bar
if (cameraX < 0)
cameraX = 0;
if (cameraX + gc.getWidth() > mapWidth)
cameraX = mapWidth - gc.getWidth();
// if the camera is at the top or bottom edge lock it to prevent
// black bar
if (cameraY < 0 && id == 1) {
cameraY = 0;
- } else if (cameraY < -gc.getScreenHeight() / 2 && id == 2) {
- cameraY = -gc.getScreenHeight() / 2 + 10;
+ } else if (cameraY < -gc.getHeight() / 2 && id == 2) {
+ cameraY = -gc.getHeight() / 2 + 10;
}
if (cameraY + gc.getHeight() / 2 > mapHeight && id == 1) {
cameraY = mapHeight - gc.getHeight() / 2;
} else if (cameraY + gc.getHeight() > mapHeight && id == 2) {
cameraY = mapHeight - gc.getHeight();
}
}
}
}
/**
* "locks" the camera on the center of the given Rectangle. The camera tries
* to keep the location in it's center.
*
* @param x
* the x-coordinate (in pixel) of the top-left corner of the
* rectangle
* @param y
* the y-coordinate (in pixel) of the top-left corner of the
* rectangle
* @param height
* the height (in pixel) of the rectangle
* @param width
* the width (in pixel) of the rectangle
*/
public void centerOn(float x, float y, float height, float width, int id) {
this.centerOn(x + width / 2, y + height / 2, id);
}
/**
* "locks the camera on the center of the given Shape. The camera tries to
* keep the location in it's center.
*
* @param shape
* the Shape which should be centered on the screen
*/
public void centerOn(Shape shape, int id) {
this.centerOn(shape.getCenterX(), shape.getCenterY(), id);
}
/**
* draws the part of the map which is currently focussed by the camera on
* the screen
*/
public void drawMap() {
this.drawMap(0, 0);
}
/**
* draws the part of the map which is currently focussed by the camera on
* the screen.<br>
* You need to draw something over the offset, to prevent the edge of the
* map to be displayed below it<br>
* Has to be called before Camera.translateGraphics() !
*
* @param offsetX
* the x-coordinate (in pixel) where the camera should start
* drawing the map at
* @param offsetY
* the y-coordinate (in pixel) where the camera should start,
* drawing the map at
*/
public void drawMap(int offsetX, int offsetY) {
// calculate the offset to the next tile (needed by TiledMap.render())
int tileOffsetX = (int) -(cameraX % tileWidth);
int tileOffsetY = (int) -(cameraY % tileHeight);
// calculate the index of the leftmost tile that is being displayed
int tileIndexX = (int) (cameraX / tileWidth);
int tileIndexY = (int) (cameraY / tileHeight);
// finally draw the section of the map on the screen
map.render(tileOffsetX + offsetX, tileOffsetY + offsetY, tileIndexX,
tileIndexY, (gc.getWidth() - tileOffsetX) / tileWidth + 1,
(gc.getHeight() - tileOffsetY) / tileHeight + 1, 1, false);
}
/**
* Translates the Graphics-context to the coordinates of the map - now
* everything can be drawn with it's NATURAL coordinates.
*/
public void translateGraphics() {
gc.getGraphics().translate(-cameraX, -cameraY);
}
/**
* Reverses the Graphics-translation of Camera.translatesGraphics(). Call
* this before drawing HUD-elements or the like
*/
public void untranslateGraphics() {
gc.getGraphics().translate(cameraX, cameraY);
}
}
| true | true | public void centerOn(float x, float y, int id) {
// try to set the given position as center of the camera by default
if (Var.singlePlayer) {
cameraX = x - gc.getWidth() * 0.5f;
cameraY = y - gc.getHeight() * 0.5f;
// if the camera is at the right or left edge lock it to prevent a
// black bar
if (cameraX < 0)
cameraX = 0;
if (cameraX + gc.getWidth() > mapWidth)
cameraX = mapWidth - gc.getWidth();
// if the camera is at the top or bottom edge lock it to prevent a
// black bar
if (cameraY < 0) {
cameraY = 0;
}
if (cameraY + gc.getHeight() > mapHeight) {
cameraY = mapHeight - gc.getHeight();
}
} else if (!Var.singlePlayer) {
if (Var.vertical_split) {
cameraY = y - gc.getHeight() * 0.5f;
if (id == 1) {
cameraX = x - gc.getWidth() * 0.25f;
} else if (id == 2) {
cameraX = x - gc.getWidth() * 0.75f;
}
// if the camera is at the right or left edge lock it to prevent
// black bar
if (cameraX < 0 && id == 1) {
cameraX = 0;
} else if (cameraX < -gc.getScreenWidth() / 2 && id == 2) {
cameraX = -gc.getScreenWidth() / 2;
}
if (cameraX + gc.getWidth() * 0.5f > mapWidth && id == 1) {
cameraX = mapWidth - gc.getWidth() * 0.5f;
} else if (cameraX + gc.getWidth() > mapWidth && id == 2) {
cameraX = mapWidth - gc.getWidth();
}
// if the camera is at the top or bottom edge lock it to prevent
// black bar
if (cameraY < 0)
cameraY = 0;
if (cameraY + gc.getHeight() > mapHeight) {
cameraY = mapHeight - gc.getHeight();
}
} else if (!Var.vertical_split) {
cameraX = x - gc.getWidth() * 0.5f;
if (id == 1) {
cameraY = y - gc.getHeight() * 0.25f;
} else if (id == 2) {
cameraY = y - gc.getHeight() * 0.75f;
}
// if the camera is at the right or left edge lock it to prevent
// black bar
if (cameraX < 0)
cameraX = 0;
if (cameraX + gc.getWidth() > mapWidth)
cameraX = mapWidth - gc.getWidth();
// if the camera is at the top or bottom edge lock it to prevent
// black bar
if (cameraY < 0 && id == 1) {
cameraY = 0;
} else if (cameraY < -gc.getScreenHeight() / 2 && id == 2) {
cameraY = -gc.getScreenHeight() / 2 + 10;
}
if (cameraY + gc.getHeight() / 2 > mapHeight && id == 1) {
cameraY = mapHeight - gc.getHeight() / 2;
} else if (cameraY + gc.getHeight() > mapHeight && id == 2) {
cameraY = mapHeight - gc.getHeight();
}
}
}
}
| public void centerOn(float x, float y, int id) {
// try to set the given position as center of the camera by default
if (Var.singlePlayer) {
cameraX = x - gc.getWidth() * 0.5f;
cameraY = y - gc.getHeight() * 0.5f;
// if the camera is at the right or left edge lock it to prevent a
// black bar
if (cameraX < 0)
cameraX = 0;
if (cameraX + gc.getWidth() > mapWidth)
cameraX = mapWidth - gc.getWidth();
// if the camera is at the top or bottom edge lock it to prevent a
// black bar
if (cameraY < 0) {
cameraY = 0;
}
if (cameraY + gc.getHeight() > mapHeight) {
cameraY = mapHeight - gc.getHeight();
}
} else if (!Var.singlePlayer) {
if (Var.vertical_split) {
cameraY = y - gc.getHeight() * 0.5f;
if (id == 1) {
cameraX = x - gc.getWidth() * 0.25f;
} else if (id == 2) {
cameraX = x - gc.getWidth() * 0.75f;
}
// if the camera is at the right or left edge lock it to prevent
// black bar
if (cameraX < 0 && id == 1) {
cameraX = 0;
} else if (cameraX < -gc.getScreenWidth() / 2 && id == 2) {
cameraX = -gc.getScreenWidth() / 2;
}
if (cameraX + gc.getWidth() * 0.5f > mapWidth && id == 1) {
cameraX = mapWidth - gc.getWidth() * 0.5f;
} else if (cameraX + gc.getWidth() > mapWidth && id == 2) {
cameraX = mapWidth - gc.getWidth();
}
// if the camera is at the top or bottom edge lock it to prevent
// black bar
if (cameraY < 0)
cameraY = 0;
if (cameraY + gc.getHeight() > mapHeight) {
cameraY = mapHeight - gc.getHeight();
}
} else if (!Var.vertical_split) {
cameraX = x - gc.getWidth() * 0.5f;
if (id == 1) {
cameraY = y - gc.getHeight() * 0.25f;
} else if (id == 2) {
cameraY = y - gc.getHeight() * 0.75f;
}
// if the camera is at the right or left edge lock it to prevent
// black bar
if (cameraX < 0)
cameraX = 0;
if (cameraX + gc.getWidth() > mapWidth)
cameraX = mapWidth - gc.getWidth();
// if the camera is at the top or bottom edge lock it to prevent
// black bar
if (cameraY < 0 && id == 1) {
cameraY = 0;
} else if (cameraY < -gc.getHeight() / 2 && id == 2) {
cameraY = -gc.getHeight() / 2 + 10;
}
if (cameraY + gc.getHeight() / 2 > mapHeight && id == 1) {
cameraY = mapHeight - gc.getHeight() / 2;
} else if (cameraY + gc.getHeight() > mapHeight && id == 2) {
cameraY = mapHeight - gc.getHeight();
}
}
}
}
|
diff --git a/src/main/java/me/limebyte/battlenight/core/util/Util.java b/src/main/java/me/limebyte/battlenight/core/util/Util.java
index 1fac399..71b131a 100644
--- a/src/main/java/me/limebyte/battlenight/core/util/Util.java
+++ b/src/main/java/me/limebyte/battlenight/core/util/Util.java
@@ -1,51 +1,51 @@
package me.limebyte.battlenight.core.util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public class Util {
////////////////////
// Locations //
////////////////////
private static final String LOC_SEP = ", ";
public static String locationToString(Location loc) {
String w = loc.getWorld().getName();
double x = loc.getBlockX() + 0.5;
double y = loc.getBlockY();
double z = loc.getBlockZ() + 0.5;
float yaw = loc.getYaw();
float pitch = loc.getPitch();
return w + "(" + x + LOC_SEP + y + LOC_SEP + z + LOC_SEP + yaw + LOC_SEP + pitch + ")";
}
public static Location locationFromString(String s) {
- String[] parts = s.split("(");
+ String[] parts = s.split("\\(");
World w = Bukkit.getServer().getWorld(parts[0]);
String[] coords = parts[1].substring(0, parts[1].length() - 1).split(LOC_SEP);
double x = Double.parseDouble(coords[0]);
double y = Double.parseDouble(coords[1]);
double z = Double.parseDouble(coords[2]);
float yaw = Float.parseFloat(coords[3]);
float pitch = Float.parseFloat(coords[4]);
return new Location(w, x, y, z, yaw, pitch);
}
////////////////////
// Items //
////////////////////
public static void clearInventory(Player player) {
PlayerInventory inv = player.getInventory();
inv.clear();
inv.setArmorContents(new ItemStack[inv.getArmorContents().length]);
}
}
| true | true | public static Location locationFromString(String s) {
String[] parts = s.split("(");
World w = Bukkit.getServer().getWorld(parts[0]);
String[] coords = parts[1].substring(0, parts[1].length() - 1).split(LOC_SEP);
double x = Double.parseDouble(coords[0]);
double y = Double.parseDouble(coords[1]);
double z = Double.parseDouble(coords[2]);
float yaw = Float.parseFloat(coords[3]);
float pitch = Float.parseFloat(coords[4]);
return new Location(w, x, y, z, yaw, pitch);
}
| public static Location locationFromString(String s) {
String[] parts = s.split("\\(");
World w = Bukkit.getServer().getWorld(parts[0]);
String[] coords = parts[1].substring(0, parts[1].length() - 1).split(LOC_SEP);
double x = Double.parseDouble(coords[0]);
double y = Double.parseDouble(coords[1]);
double z = Double.parseDouble(coords[2]);
float yaw = Float.parseFloat(coords[3]);
float pitch = Float.parseFloat(coords[4]);
return new Location(w, x, y, z, yaw, pitch);
}
|
diff --git a/src/main/java/org/elasticsearch/shell/BasicShell.java b/src/main/java/org/elasticsearch/shell/BasicShell.java
index bf2bd8c..4cfc4bc 100644
--- a/src/main/java/org/elasticsearch/shell/BasicShell.java
+++ b/src/main/java/org/elasticsearch/shell/BasicShell.java
@@ -1,177 +1,177 @@
/*
* Licensed to Luca Cavanna (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.shell;
import org.elasticsearch.shell.client.ClientFactory;
import org.elasticsearch.shell.console.Console;
import org.elasticsearch.shell.scheduler.Scheduler;
import org.elasticsearch.shell.script.ScriptExecutor;
import org.elasticsearch.shell.source.CompilableSource;
import org.elasticsearch.shell.source.CompilableSourceReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Basic shell implementation: it reads a compilable source and executes it
*
* @author Luca Cavanna
*/
public class BasicShell<ShellNativeClient> implements Shell {
private static final Logger logger = LoggerFactory.getLogger(BasicShell.class);
protected final Console<PrintStream> console;
protected final CompilableSourceReader compilableSourceReader;
protected final ScriptExecutor scriptExecutor;
protected final Unwrapper unwrapper;
protected final ShellScope<?> shellScope;
protected final ClientFactory<ShellNativeClient> clientFactory;
protected final Scheduler scheduler;
protected final AtomicBoolean closed = new AtomicBoolean(false);
/**
* Creates a new <code>BasicShell</code>
*
* @param console the console used to read commands and prints the results
* @param compilableSourceReader reader that receives a potential script and determines whether
* it really is a compilable script or eventually waits for more input
* @param scriptExecutor executor used to execute a compilable source
* @param unwrapper unwraps a script object and converts it to its Java representation
* @param shellScope the generic shell scope
* @param scheduler the scheduler that handles all the scheduled actions
*/
public BasicShell(Console<PrintStream> console, CompilableSourceReader compilableSourceReader,
ScriptExecutor scriptExecutor, Unwrapper unwrapper, ShellScope<?> shellScope,
ClientFactory<ShellNativeClient> clientFactory, Scheduler scheduler) {
this.console = console;
this.compilableSourceReader = compilableSourceReader;
this.scriptExecutor = scriptExecutor;
this.unwrapper = unwrapper;
this.shellScope = shellScope;
this.clientFactory = clientFactory;
this.scheduler = scheduler;
}
@Override
public void run() {
init();
try {
doRun();
} finally {
close();
}
}
protected void doRun() {
printWelcomeMessage();
tryRegisterDefaultClient();
while (true) {
CompilableSource source = null;
try {
source = compilableSourceReader.read();
} catch (Exception e) {
logger.error(e.getMessage(), e);
- e.printStackTrace(console.out());
+ console.println("Error while checking the input: " + e.toString());
}
if (source != null) {
Object jsResult = scriptExecutor.execute(source);
Object javaResult = unwrap(jsResult);
if (javaResult instanceof ExitSignal) {
shutdown();
return;
}
if (javaResult != null) {
console.println(javaToString(javaResult));
}
}
}
}
/**
* Initializes the shell: nothing to do here but can be overriden
*/
void init() {
}
/**
* Close the shell: nothing to do here but can be overriden
*/
void close() {
}
protected void printWelcomeMessage() {
//TODO nicer welcome message, version etc.
console.println("Welcome to the elasticshell");
console.println("----------------------------------");
}
protected void tryRegisterDefaultClient() {
ShellNativeClient shellNativeClient = clientFactory.newTransportClient();
if (shellNativeClient != null) {
registerClient(shellNativeClient);
}
}
protected void registerClient(ShellNativeClient shellNativeClient) {
shellScope.registerJavaObject("es", shellNativeClient);
console.println(shellNativeClient.toString() + " registered with name es");
}
/**
* Converts a javascript object returned by the shell to its Java representation
* @param scriptObject the javascript object to convert
* @return the Java representation of the input javascript object
*/
protected Object unwrap(Object scriptObject) {
return unwrapper.unwrap(scriptObject);
}
/**
* Converts a Java object to its textual representation that can be shown as a result of a script execution
* @param javaObject the Java object to convert to its textual representation
* @return the textual representation of the input Java object
*/
protected String javaToString(Object javaObject) {
return javaObject.toString();
}
@Override
public void shutdown() {
if (closed.compareAndSet(false, true)) {
if (scheduler != null) {
logger.debug("Shutting down the scheduler");
scheduler.shutdown();
}
shellScope.close();
console.println();
console.println("bye");
}
}
}
| true | true | protected void doRun() {
printWelcomeMessage();
tryRegisterDefaultClient();
while (true) {
CompilableSource source = null;
try {
source = compilableSourceReader.read();
} catch (Exception e) {
logger.error(e.getMessage(), e);
e.printStackTrace(console.out());
}
if (source != null) {
Object jsResult = scriptExecutor.execute(source);
Object javaResult = unwrap(jsResult);
if (javaResult instanceof ExitSignal) {
shutdown();
return;
}
if (javaResult != null) {
console.println(javaToString(javaResult));
}
}
}
}
| protected void doRun() {
printWelcomeMessage();
tryRegisterDefaultClient();
while (true) {
CompilableSource source = null;
try {
source = compilableSourceReader.read();
} catch (Exception e) {
logger.error(e.getMessage(), e);
console.println("Error while checking the input: " + e.toString());
}
if (source != null) {
Object jsResult = scriptExecutor.execute(source);
Object javaResult = unwrap(jsResult);
if (javaResult instanceof ExitSignal) {
shutdown();
return;
}
if (javaResult != null) {
console.println(javaToString(javaResult));
}
}
}
}
|
diff --git a/src/org/apache/xerces/dom/DOMConfigurationImpl.java b/src/org/apache/xerces/dom/DOMConfigurationImpl.java
index bd0f83688..b02a35bf0 100644
--- a/src/org/apache/xerces/dom/DOMConfigurationImpl.java
+++ b/src/org/apache/xerces/dom/DOMConfigurationImpl.java
@@ -1,1203 +1,1203 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.dom;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Vector;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMErrorHandler;
import org.w3c.dom.DOMStringList;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.dv.DTDDVFactory;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.impl.validation.ValidationManager;
import org.apache.xerces.util.DOMEntityResolverWrapper;
import org.apache.xerces.util.DOMErrorHandlerWrapper;
import org.apache.xerces.util.MessageFormatter;
import org.apache.xerces.util.ParserConfigurationSettings;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.xni.XMLDTDContentModelHandler;
import org.apache.xerces.xni.XMLDTDHandler;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.w3c.dom.DOMException;
import org.w3c.dom.ls.LSResourceResolver;
/**
* Xerces implementation of DOMConfiguration that maintains a table of recognized parameters.
*
* @xerces.internal
*
* @author Elena Litani, IBM
* @author Neeraj Bajaj, Sun Microsystems.
* @version $Id$
*/
public class DOMConfigurationImpl extends ParserConfigurationSettings
implements XMLParserConfiguration, DOMConfiguration {
//
// Constants
//
protected static final String XML11_DATATYPE_VALIDATOR_FACTORY =
"org.apache.xerces.impl.dv.dtd.XML11DTDDVFactoryImpl";
// feature identifiers
/** Feature identifier: validation. */
protected static final String XERCES_VALIDATION =
Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE;
/** Feature identifier: namespaces. */
protected static final String XERCES_NAMESPACES =
Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
protected static final String SCHEMA =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE;
protected static final String SCHEMA_FULL_CHECKING =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING;
protected static final String DYNAMIC_VALIDATION =
Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE;
protected static final String NORMALIZE_DATA =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE;
/** Feature identifier: send element default value via characters() */
protected static final String SCHEMA_ELEMENT_DEFAULT =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT;
/** sending psvi in the pipeline */
protected static final String SEND_PSVI =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI;
/** Feature: generate synthetic annotations */
protected static final String GENERATE_SYNTHETIC_ANNOTATIONS =
Constants.XERCES_FEATURE_PREFIX + Constants.GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE;
/** Feature identifier: validate annotations */
protected static final String VALIDATE_ANNOTATIONS =
Constants.XERCES_FEATURE_PREFIX + Constants.VALIDATE_ANNOTATIONS_FEATURE;
/** Feature identifier: honour all schemaLocations */
protected static final String HONOUR_ALL_SCHEMALOCATIONS =
Constants.XERCES_FEATURE_PREFIX + Constants.HONOUR_ALL_SCHEMALOCATIONS_FEATURE;
/** Feature identifier: use grammar pool only */
protected static final String USE_GRAMMAR_POOL_ONLY =
Constants.XERCES_FEATURE_PREFIX + Constants.USE_GRAMMAR_POOL_ONLY_FEATURE;
/** Feature identifier: load external DTD. */
protected static final String DISALLOW_DOCTYPE_DECL_FEATURE =
Constants.XERCES_FEATURE_PREFIX + Constants.DISALLOW_DOCTYPE_DECL_FEATURE;
/** Feature identifier: balance syntax trees. */
protected static final String BALANCE_SYNTAX_TREES =
Constants.XERCES_FEATURE_PREFIX + Constants.BALANCE_SYNTAX_TREES;
/** Feature identifier: warn on duplicate attribute definition. */
protected static final String WARN_ON_DUPLICATE_ATTDEF =
Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ATTDEF_FEATURE;
// property identifiers
/** Property identifier: entity manager. */
protected static final String ENTITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: xml string. */
protected static final String XML_STRING =
Constants.SAX_PROPERTY_PREFIX + Constants.XML_STRING_PROPERTY;
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property id: Grammar pool*/
protected static final String GRAMMAR_POOL =
Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
/** Property identifier: error handler. */
protected static final String ERROR_HANDLER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY;
/** Property identifier: entity resolver. */
protected static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
/** Property identifier: JAXP schema language / DOM schema-type. */
protected static final String JAXP_SCHEMA_LANGUAGE =
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE;
/** Property identifier: JAXP schema source/ DOM schema-location. */
protected static final String JAXP_SCHEMA_SOURCE =
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE;
/** Property identifier: DTD validator. */
protected final static String DTD_VALIDATOR_PROPERTY =
Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_VALIDATOR_PROPERTY;
/** Property identifier: datatype validator factory. */
protected static final String DTD_VALIDATOR_FACTORY_PROPERTY =
Constants.XERCES_PROPERTY_PREFIX + Constants.DATATYPE_VALIDATOR_FACTORY_PROPERTY;
protected static final String VALIDATION_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;
/** Property identifier: schema location. */
protected static final String SCHEMA_LOCATION =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION;
/** Property identifier: no namespace schema location. */
protected static final String SCHEMA_NONS_LOCATION =
Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION;
//
// Data
//
XMLDocumentHandler fDocumentHandler;
/** Normalization features*/
protected short features = 0;
protected final static short NAMESPACES = 0x1<<0;
protected final static short DTNORMALIZATION = 0x1<<1;
protected final static short ENTITIES = 0x1<<2;
protected final static short CDATA = 0x1<<3;
protected final static short SPLITCDATA = 0x1<<4;
protected final static short COMMENTS = 0x1<<5;
protected final static short VALIDATE = 0x1<<6;
protected final static short PSVI = 0x1<<7;
protected final static short WELLFORMED = 0x1<<8;
protected final static short NSDECL = 0x1<<9;
protected final static short INFOSET_TRUE_PARAMS = NAMESPACES | COMMENTS | WELLFORMED | NSDECL;
protected final static short INFOSET_FALSE_PARAMS = ENTITIES | DTNORMALIZATION | CDATA;
protected final static short INFOSET_MASK = INFOSET_TRUE_PARAMS | INFOSET_FALSE_PARAMS;
// components
/** Symbol table. */
protected SymbolTable fSymbolTable;
/** Components. */
protected ArrayList fComponents;
protected ValidationManager fValidationManager;
/** Locale. */
protected Locale fLocale;
/** Error reporter */
protected XMLErrorReporter fErrorReporter;
protected final DOMErrorHandlerWrapper fErrorHandlerWrapper =
new DOMErrorHandlerWrapper();
/** Current Datatype validator factory. */
protected DTDDVFactory fCurrentDVFactory;
/** The XML 1.0 Datatype validator factory. */
protected DTDDVFactory fDatatypeValidatorFactory;
/** The XML 1.1 Datatype validator factory. **/
protected DTDDVFactory fXML11DatatypeFactory;
// private data
private DOMStringList fRecognizedParameters;
//
// Constructors
//
/** Default Constructor. */
protected DOMConfigurationImpl() {
this(null, null);
} // <init>()
/**
* Constructs a parser configuration using the specified symbol table.
*
* @param symbolTable The symbol table to use.
*/
protected DOMConfigurationImpl(SymbolTable symbolTable) {
this(symbolTable, null);
} // <init>(SymbolTable)
/**
* Constructs a parser configuration using the specified symbol table
* and parent settings.
*
* @param symbolTable The symbol table to use.
* @param parentSettings The parent settings.
*/
protected DOMConfigurationImpl(SymbolTable symbolTable,
XMLComponentManager parentSettings) {
super(parentSettings);
// create storage for recognized features and properties
fRecognizedFeatures = new ArrayList();
fRecognizedProperties = new ArrayList();
// create table for features and properties
fFeatures = new HashMap();
fProperties = new HashMap();
// add default recognized features
final String[] recognizedFeatures = {
XERCES_VALIDATION,
XERCES_NAMESPACES,
SCHEMA,
SCHEMA_FULL_CHECKING,
DYNAMIC_VALIDATION,
NORMALIZE_DATA,
SCHEMA_ELEMENT_DEFAULT,
SEND_PSVI,
GENERATE_SYNTHETIC_ANNOTATIONS,
VALIDATE_ANNOTATIONS,
HONOUR_ALL_SCHEMALOCATIONS,
USE_GRAMMAR_POOL_ONLY,
DISALLOW_DOCTYPE_DECL_FEATURE,
BALANCE_SYNTAX_TREES,
WARN_ON_DUPLICATE_ATTDEF,
PARSER_SETTINGS
};
addRecognizedFeatures(recognizedFeatures);
// set state for default features
setFeature(XERCES_VALIDATION, false);
setFeature(SCHEMA, false);
setFeature(SCHEMA_FULL_CHECKING, false);
setFeature(DYNAMIC_VALIDATION, false);
setFeature(NORMALIZE_DATA, false);
setFeature(SCHEMA_ELEMENT_DEFAULT, false);
setFeature(XERCES_NAMESPACES, true);
setFeature(SEND_PSVI, true);
setFeature(GENERATE_SYNTHETIC_ANNOTATIONS, false);
setFeature(VALIDATE_ANNOTATIONS, false);
setFeature(HONOUR_ALL_SCHEMALOCATIONS, false);
setFeature(USE_GRAMMAR_POOL_ONLY, false);
setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, false);
setFeature(BALANCE_SYNTAX_TREES, false);
setFeature(WARN_ON_DUPLICATE_ATTDEF, false);
setFeature(PARSER_SETTINGS, true);
// add default recognized properties
final String[] recognizedProperties = {
XML_STRING,
SYMBOL_TABLE,
ERROR_HANDLER,
ENTITY_RESOLVER,
ERROR_REPORTER,
ENTITY_MANAGER,
VALIDATION_MANAGER,
GRAMMAR_POOL,
JAXP_SCHEMA_SOURCE,
JAXP_SCHEMA_LANGUAGE,
SCHEMA_LOCATION,
SCHEMA_NONS_LOCATION,
DTD_VALIDATOR_PROPERTY,
DTD_VALIDATOR_FACTORY_PROPERTY
};
addRecognizedProperties(recognizedProperties);
// set default values for normalization features
features |= NAMESPACES;
features |= ENTITIES;
features |= COMMENTS;
features |= CDATA;
features |= SPLITCDATA;
features |= WELLFORMED;
features |= NSDECL;
if (symbolTable == null) {
symbolTable = new SymbolTable();
}
fSymbolTable = symbolTable;
fComponents = new ArrayList();
setProperty(SYMBOL_TABLE, fSymbolTable);
fErrorReporter = new XMLErrorReporter();
setProperty(ERROR_REPORTER, fErrorReporter);
addComponent(fErrorReporter);
fDatatypeValidatorFactory = DTDDVFactory.getInstance();
fXML11DatatypeFactory = DTDDVFactory.getInstance(XML11_DATATYPE_VALIDATOR_FACTORY);
fCurrentDVFactory = fDatatypeValidatorFactory;
setProperty(DTD_VALIDATOR_FACTORY_PROPERTY, fCurrentDVFactory);
XMLEntityManager manager = new XMLEntityManager();
setProperty(ENTITY_MANAGER, manager);
addComponent(manager);
fValidationManager = createValidationManager();
setProperty(VALIDATION_MANAGER, fValidationManager);
// add message formatters
if (fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN) == null) {
XMLMessageFormatter xmft = new XMLMessageFormatter();
fErrorReporter.putMessageFormatter(XMLMessageFormatter.XML_DOMAIN, xmft);
fErrorReporter.putMessageFormatter(XMLMessageFormatter.XMLNS_DOMAIN, xmft);
}
// REVISIT: try to include XML Schema formatter.
// This is a hack to allow DTD configuration to be build.
//
if (fErrorReporter.getMessageFormatter("http://www.w3.org/TR/xml-schema-1") == null) {
MessageFormatter xmft = null;
try {
xmft = (MessageFormatter)(
ObjectFactory.newInstance("org.apache.xerces.impl.xs.XSMessageFormatter",
ObjectFactory.findClassLoader(), true));
} catch (Exception exception){
}
if (xmft != null) {
fErrorReporter.putMessageFormatter("http://www.w3.org/TR/xml-schema-1", xmft);
}
}
// set locale
try {
setLocale(Locale.getDefault());
}
catch (XNIException e) {
// do nothing
// REVISIT: What is the right thing to do? -Ac
}
} // <init>(SymbolTable)
//
// XMLParserConfiguration methods
//
/**
* Parse an XML document.
* <p>
* The parser can use this method to instruct this configuration
* to begin parsing an XML document from any valid input source
* (a character stream, a byte stream, or a URI).
* <p>
* Parsers may not invoke this method while a parse is in progress.
* Once a parse is complete, the parser may then parse another XML
* document.
* <p>
* This method is synchronous: it will not return until parsing
* has ended. If a client application wants to terminate
* parsing early, it should throw an exception.
*
* @param inputSource The input source for the top-level of the
* XML document.
*
* @exception XNIException Any XNI exception, possibly wrapping
* another exception.
* @exception IOException An IO exception from the parser, possibly
* from a byte stream or character stream
* supplied by the parser.
*/
public void parse(XMLInputSource inputSource)
throws XNIException, IOException{
// no-op
}
/**
* Sets the document handler on the last component in the pipeline
* to receive information about the document.
*
* @param documentHandler The document handler.
*/
public void setDocumentHandler(XMLDocumentHandler documentHandler) {
fDocumentHandler = documentHandler;
} // setDocumentHandler(XMLDocumentHandler)
/** Returns the registered document handler. */
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
} // getDocumentHandler():XMLDocumentHandler
/**
* Sets the DTD handler.
*
* @param dtdHandler The DTD handler.
*/
public void setDTDHandler(XMLDTDHandler dtdHandler) {
//no-op
} // setDTDHandler(XMLDTDHandler)
/** Returns the registered DTD handler. */
public XMLDTDHandler getDTDHandler() {
return null;
} // getDTDHandler():XMLDTDHandler
/**
* Sets the DTD content model handler.
*
* @param handler The DTD content model handler.
*/
public void setDTDContentModelHandler(XMLDTDContentModelHandler handler) {
//no-op
} // setDTDContentModelHandler(XMLDTDContentModelHandler)
/** Returns the registered DTD content model handler. */
public XMLDTDContentModelHandler getDTDContentModelHandler() {
return null;
} // getDTDContentModelHandler():XMLDTDContentModelHandler
/**
* Sets the resolver used to resolve external entities. The EntityResolver
* interface supports resolution of public and system identifiers.
*
* @param resolver The new entity resolver. Passing a null value will
* uninstall the currently installed resolver.
*/
public void setEntityResolver(XMLEntityResolver resolver) {
fProperties.put(ENTITY_RESOLVER, resolver);
} // setEntityResolver(XMLEntityResolver)
/**
* Return the current entity resolver.
*
* @return The current entity resolver, or null if none
* has been registered.
* @see #setEntityResolver
*/
public XMLEntityResolver getEntityResolver() {
return (XMLEntityResolver)fProperties.get(ENTITY_RESOLVER);
} // getEntityResolver():XMLEntityResolver
/**
* Allow an application to register an error event handler.
*
* <p>If the application does not register an error handler, all
* error events reported by the SAX parser will be silently
* ignored; however, normal processing may not continue. It is
* highly recommended that all SAX applications implement an
* error handler to avoid unexpected bugs.</p>
*
* <p>Applications may register a new or different handler in the
* middle of a parse, and the SAX parser must begin using the new
* handler immediately.</p>
*
* @param errorHandler The error handler.
* @exception java.lang.NullPointerException If the handler
* argument is null.
* @see #getErrorHandler
*/
public void setErrorHandler(XMLErrorHandler errorHandler) {
if (errorHandler != null) {
fProperties.put(ERROR_HANDLER, errorHandler);
}
} // setErrorHandler(XMLErrorHandler)
/**
* Return the current error handler.
*
* @return The current error handler, or null if none
* has been registered.
* @see #setErrorHandler
*/
public XMLErrorHandler getErrorHandler() {
return (XMLErrorHandler)fProperties.get(ERROR_HANDLER);
} // getErrorHandler():XMLErrorHandler
/**
* Returns the state of a feature.
*
* @param featureId The feature identifier.
* @return true if the feature is supported
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
public boolean getFeature(String featureId)
throws XMLConfigurationException {
if (featureId.equals(PARSER_SETTINGS)) {
return true;
}
return super.getFeature(featureId);
}
/**
* Set the state of a feature.
*
* Set the state of any feature in a SAX2 parser. The parser
* might not recognize the feature, and if it does recognize
* it, it might not be able to fulfill the request.
*
* @param featureId The unique identifier (URI) of the feature.
* @param state The requested state of the feature (true or false).
*
* @exception org.apache.xerces.xni.parser.XMLConfigurationException If the
* requested feature is not known.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
// save state if noone "objects"
super.setFeature(featureId, state);
} // setFeature(String,boolean)
/**
* setProperty
*
* @param propertyId
* @param value
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
// store value if noone "objects"
super.setProperty(propertyId, value);
} // setProperty(String,Object)
/**
* Set the locale to use for messages.
*
* @param locale The locale object to use for localization of messages.
*
* @exception XNIException Thrown if the parser does not support the
* specified locale.
*/
public void setLocale(Locale locale) throws XNIException {
fLocale = locale;
fErrorReporter.setLocale(locale);
} // setLocale(Locale)
/** Returns the locale. */
public Locale getLocale() {
return fLocale;
} // getLocale():Locale
/**
* DOM Level 3 WD - Experimental.
* setParameter
*/
public void setParameter(String name, Object value) throws DOMException {
boolean found = true;
// REVISIT: Recognizes DOM L3 default features only.
// Does not yet recognize Xerces features.
if(value instanceof Boolean){
boolean state = ((Boolean)value).booleanValue();
if (name.equalsIgnoreCase(Constants.DOM_COMMENTS)) {
features = (short) (state ? features | COMMENTS : features & ~COMMENTS);
}
else if (name.equalsIgnoreCase(Constants.DOM_DATATYPE_NORMALIZATION)) {
setFeature(NORMALIZE_DATA, state);
features =
(short) (state ? features | DTNORMALIZATION : features & ~DTNORMALIZATION);
if (state) {
features = (short) (features | VALIDATE);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACES)) {
features = (short) (state ? features | NAMESPACES : features & ~NAMESPACES);
}
else if (name.equalsIgnoreCase(Constants.DOM_CDATA_SECTIONS)) {
features = (short) (state ? features | CDATA : features & ~CDATA);
}
else if (name.equalsIgnoreCase(Constants.DOM_ENTITIES)) {
features = (short) (state ? features | ENTITIES : features & ~ENTITIES);
}
else if (name.equalsIgnoreCase(Constants.DOM_SPLIT_CDATA)) {
features = (short) (state ? features | SPLITCDATA : features & ~SPLITCDATA);
}
else if (name.equalsIgnoreCase(Constants.DOM_VALIDATE)) {
features = (short) (state ? features | VALIDATE : features & ~VALIDATE);
}
else if (name.equalsIgnoreCase(Constants.DOM_WELLFORMED)) {
features = (short) (state ? features | WELLFORMED : features & ~WELLFORMED );
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACE_DECLARATIONS)) {
features = (short) (state ? features | NSDECL : features & ~NSDECL);
}
else if (name.equalsIgnoreCase(Constants.DOM_INFOSET)) {
// Setting to false has no effect.
if (state) {
features = (short) (features | INFOSET_TRUE_PARAMS);
features = (short) (features & ~INFOSET_FALSE_PARAMS);
setFeature(NORMALIZE_DATA, false);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS)
|| name.equalsIgnoreCase(Constants.DOM_CANONICAL_FORM)
|| name.equalsIgnoreCase(Constants.DOM_VALIDATE_IF_SCHEMA)
|| name.equalsIgnoreCase(Constants.DOM_CHECK_CHAR_NORMALIZATION)
) {
if (state) { // true is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if ( name.equalsIgnoreCase(Constants.DOM_ELEMENT_CONTENT_WHITESPACE)) {
if (!state) { // false is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if (name.equalsIgnoreCase(SEND_PSVI) ){
// REVISIT: turning augmentation of PSVI is not support,
// because in this case we won't be able to retrieve element
// default value.
if (!state) { // false is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_PSVI)){
features = (short) (state ? features | PSVI : features & ~PSVI);
}
else {
found = false;
/*
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_FOUND",
new Object[] { name });
throw new DOMException(DOMException.NOT_FOUND_ERR, msg);
*/
}
}
if (!found || !(value instanceof Boolean)) { // set properties
found = true;
if (name.equalsIgnoreCase(Constants.DOM_ERROR_HANDLER)) {
if (value instanceof DOMErrorHandler || value == null) {
fErrorHandlerWrapper.setErrorHandler((DOMErrorHandler)value);
setErrorHandler(fErrorHandlerWrapper);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_RESOURCE_RESOLVER)) {
if (value instanceof LSResourceResolver || value == null) {
try {
setEntityResolver(new DOMEntityResolverWrapper((LSResourceResolver) value));
}
catch (XMLConfigurationException e) {}
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_LOCATION)) {
if (value instanceof String || value == null) {
try {
// map DOM schema-location to JAXP schemaSource property
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE,
value);
}
catch (XMLConfigurationException e) {}
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_TYPE)) {
if (value instanceof String || value == null) {
try {
if (value == null) {
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
null);
}
else if (value.equals(Constants.NS_XMLSCHEMA)) {
// REVISIT: when add support to DTD validation
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
Constants.NS_XMLSCHEMA);
}
else if (value.equals(Constants.NS_DTD)) {
// Added support for revalidation against DTDs
setProperty(Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
Constants.NS_DTD);
}
}
catch (XMLConfigurationException e) {}
}
else {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(ENTITY_RESOLVER)) {
if (value instanceof XMLEntityResolver || value == null) {
try {
setEntityResolver((XMLEntityResolver) value);
}
catch (XMLConfigurationException e) {}
}
else {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(SYMBOL_TABLE)){
// Xerces Symbol Table
if (value instanceof SymbolTable){
setProperty(SYMBOL_TABLE, value);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase (GRAMMAR_POOL)){
- if (value instanceof XMLGrammarPool){
+ if (value instanceof XMLGrammarPool || value == null) {
setProperty(GRAMMAR_POOL, value);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else {
// REVISIT: check if this is a boolean parameter -- type mismatch should be thrown.
//parameter is not recognized
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_FOUND",
new Object[] { name });
throw new DOMException(DOMException.NOT_FOUND_ERR, msg);
}
}
}
/**
* DOM Level 3 WD - Experimental.
* getParameter
*/
public Object getParameter(String name) throws DOMException {
// REVISIT: Recognizes DOM L3 default features only.
// Does not yet recognize Xerces features.
if (name.equalsIgnoreCase(Constants.DOM_COMMENTS)) {
return ((features & COMMENTS) != 0) ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACES)) {
return (features & NAMESPACES) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_DATATYPE_NORMALIZATION)) {
// REVISIT: datatype-normalization only takes effect if validation is on
return (features & DTNORMALIZATION) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_CDATA_SECTIONS)) {
return (features & CDATA) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_ENTITIES)) {
return (features & ENTITIES) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_SPLIT_CDATA)) {
return (features & SPLITCDATA) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_VALIDATE)) {
return (features & VALIDATE) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_WELLFORMED)) {
return (features & WELLFORMED) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACE_DECLARATIONS)) {
return (features & NSDECL) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_INFOSET)) {
return (features & INFOSET_MASK) == INFOSET_TRUE_PARAMS ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS)
|| name.equalsIgnoreCase(Constants.DOM_CANONICAL_FORM)
|| name.equalsIgnoreCase(Constants.DOM_VALIDATE_IF_SCHEMA)
|| name.equalsIgnoreCase(Constants.DOM_CHECK_CHAR_NORMALIZATION)
) {
return Boolean.FALSE;
}
else if (name.equalsIgnoreCase(SEND_PSVI)) {
return Boolean.TRUE;
}
else if (name.equalsIgnoreCase(Constants.DOM_PSVI)) {
return (features & PSVI) != 0 ? Boolean.TRUE : Boolean.FALSE;
}
else if (name.equalsIgnoreCase(Constants.DOM_ELEMENT_CONTENT_WHITESPACE)) {
return Boolean.TRUE;
}
else if (name.equalsIgnoreCase(Constants.DOM_ERROR_HANDLER)) {
return fErrorHandlerWrapper.getErrorHandler();
}
else if (name.equalsIgnoreCase(Constants.DOM_RESOURCE_RESOLVER)) {
XMLEntityResolver entityResolver = getEntityResolver();
if (entityResolver != null && entityResolver instanceof DOMEntityResolverWrapper) {
return ((DOMEntityResolverWrapper) entityResolver).getEntityResolver();
}
return null;
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_TYPE)) {
return getProperty(Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE);
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_LOCATION)) {
return getProperty(Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE);
}
else if (name.equalsIgnoreCase(ENTITY_RESOLVER)) {
return getEntityResolver();
}
else if (name.equalsIgnoreCase(SYMBOL_TABLE)){
return getProperty(SYMBOL_TABLE);
}
else if (name.equalsIgnoreCase(GRAMMAR_POOL)){
return getProperty(GRAMMAR_POOL);
}
else {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_FOUND",
new Object[] { name });
throw new DOMException(DOMException.NOT_FOUND_ERR, msg);
}
}
/**
* DOM Level 3 WD - Experimental.
* Check if setting a parameter to a specific value is supported.
*
* @param name The name of the parameter to check.
*
* @param value An object. if null, the returned value is true.
*
* @return true if the parameter could be successfully set to the
* specified value, or false if the parameter is not recognized or
* the requested value is not supported. This does not change the
* current value of the parameter itself.
*/
public boolean canSetParameter(String name, Object value) {
if (value == null){
//if null, the returned value is true.
//REVISIT: I dont like this --- even for unrecognized parameter it would
//return 'true'. I think it should return false in that case.
// Application will be surprised to find that setParameter throws not
//recognized exception when canSetParameter returns 'true' Then what is the use
//of having canSetParameter ??? - nb.
return true ;
}
if( value instanceof Boolean ){
//features whose parameter value can be set either 'true' or 'false'
// or they accept any boolean value -- so we just need to check that
// its a boolean value..
if (name.equalsIgnoreCase(Constants.DOM_COMMENTS)
|| name.equalsIgnoreCase(Constants.DOM_DATATYPE_NORMALIZATION)
|| name.equalsIgnoreCase(Constants.DOM_CDATA_SECTIONS)
|| name.equalsIgnoreCase(Constants.DOM_ENTITIES)
|| name.equalsIgnoreCase(Constants.DOM_SPLIT_CDATA)
|| name.equalsIgnoreCase(Constants.DOM_NAMESPACES)
|| name.equalsIgnoreCase(Constants.DOM_VALIDATE)
|| name.equalsIgnoreCase(Constants.DOM_WELLFORMED)
|| name.equalsIgnoreCase(Constants.DOM_INFOSET)
|| name.equalsIgnoreCase(Constants.DOM_NAMESPACE_DECLARATIONS)
) {
return true;
}//features whose parameter value can not be set to 'true'
else if (
name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS)
|| name.equalsIgnoreCase(Constants.DOM_CANONICAL_FORM)
|| name.equalsIgnoreCase(Constants.DOM_VALIDATE_IF_SCHEMA)
|| name.equalsIgnoreCase(Constants.DOM_CHECK_CHAR_NORMALIZATION)
) {
return (value.equals(Boolean.TRUE)) ? false : true;
}//features whose parameter value can not be set to 'false'
else if( name.equalsIgnoreCase(Constants.DOM_ELEMENT_CONTENT_WHITESPACE)
|| name.equalsIgnoreCase(SEND_PSVI)
) {
return (value.equals(Boolean.TRUE)) ? true : false;
}// if name is not among the above listed above -- its not recognized. return false
else {
return false ;
}
}
else if (name.equalsIgnoreCase(Constants.DOM_ERROR_HANDLER)) {
return (value instanceof DOMErrorHandler) ? true : false ;
}
else if (name.equalsIgnoreCase(Constants.DOM_RESOURCE_RESOLVER)) {
return (value instanceof LSResourceResolver) ? true : false ;
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_LOCATION)) {
return (value instanceof String) ? true : false ;
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_TYPE)) {
// REVISIT: should null value be supported?
//as of now we are only supporting W3C XML Schema
return ( (value instanceof String) && value.equals(Constants.NS_XMLSCHEMA) ) ? true : false ;
}
else if (name.equalsIgnoreCase(SYMBOL_TABLE)){
// Xerces Symbol Table
return (value instanceof SymbolTable) ? true : false ;
}
else if (name.equalsIgnoreCase (GRAMMAR_POOL)){
return (value instanceof XMLGrammarPool) ? true : false ;
}
else {
//false if the parameter is not recognized or the requested value is not supported.
return false ;
}
} //canSetParameter
/**
* DOM Level 3 CR - Experimental.
*
* The list of the parameters supported by this
* <code>DOMConfiguration</code> object and for which at least one value
* can be set by the application. Note that this list can also contain
* parameter names defined outside this specification.
*/
public DOMStringList getParameterNames() {
if (fRecognizedParameters == null){
Vector parameters = new Vector();
//Add DOM recognized parameters
//REVISIT: Would have been nice to have a list of
//recognized paramters.
parameters.add(Constants.DOM_COMMENTS);
parameters.add(Constants.DOM_DATATYPE_NORMALIZATION);
parameters.add(Constants.DOM_CDATA_SECTIONS);
parameters.add(Constants.DOM_ENTITIES);
parameters.add(Constants.DOM_SPLIT_CDATA);
parameters.add(Constants.DOM_NAMESPACES);
parameters.add(Constants.DOM_VALIDATE);
parameters.add(Constants.DOM_INFOSET);
parameters.add(Constants.DOM_NORMALIZE_CHARACTERS);
parameters.add(Constants.DOM_CANONICAL_FORM);
parameters.add(Constants.DOM_VALIDATE_IF_SCHEMA);
parameters.add(Constants.DOM_CHECK_CHAR_NORMALIZATION);
parameters.add(Constants.DOM_WELLFORMED);
parameters.add(Constants.DOM_NAMESPACE_DECLARATIONS);
parameters.add(Constants.DOM_ELEMENT_CONTENT_WHITESPACE);
parameters.add(Constants.DOM_ERROR_HANDLER);
parameters.add(Constants.DOM_SCHEMA_TYPE);
parameters.add(Constants.DOM_SCHEMA_LOCATION);
parameters.add(Constants.DOM_RESOURCE_RESOLVER);
//Add recognized xerces features and properties
parameters.add(GRAMMAR_POOL);
parameters.add(SYMBOL_TABLE);
parameters.add(SEND_PSVI);
fRecognizedParameters = new DOMStringListImpl(parameters);
}
return fRecognizedParameters;
}//getParameterNames
//
// Protected methods
//
/**
* reset all components before parsing
*/
protected void reset() throws XNIException {
if (fValidationManager != null)
fValidationManager.reset();
int count = fComponents.size();
for (int i = 0; i < count; i++) {
XMLComponent c = (XMLComponent) fComponents.get(i);
c.reset(this);
}
} // reset()
/**
* Check a property. If the property is known and supported, this method
* simply returns. Otherwise, the appropriate exception is thrown.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @exception org.apache.xerces.xni.parser.XMLConfigurationException If the
* requested feature is not known or supported.
*/
protected void checkProperty(String propertyId)
throws XMLConfigurationException {
// special cases
if (propertyId.startsWith(Constants.SAX_PROPERTY_PREFIX)) {
final int suffixLength = propertyId.length() - Constants.SAX_PROPERTY_PREFIX.length();
//
// http://xml.org/sax/properties/xml-string
// Value type: String
// Access: read-only
// Get the literal string of characters associated with the
// current event. If the parser recognises and supports this
// property but is not currently parsing text, it should return
// null (this is a good way to check for availability before the
// parse begins).
//
if (suffixLength == Constants.XML_STRING_PROPERTY.length() &&
propertyId.endsWith(Constants.XML_STRING_PROPERTY)) {
// REVISIT - we should probably ask xml-dev for a precise
// definition of what this is actually supposed to return, and
// in exactly which circumstances.
short type = XMLConfigurationException.NOT_SUPPORTED;
throw new XMLConfigurationException(type, propertyId);
}
}
// check property
super.checkProperty(propertyId);
} // checkProperty(String)
protected void addComponent(XMLComponent component) {
// don't add a component more than once
if (fComponents.contains(component)) {
return;
}
fComponents.add(component);
// register component's recognized features
String[] recognizedFeatures = component.getRecognizedFeatures();
addRecognizedFeatures(recognizedFeatures);
// register component's recognized properties
String[] recognizedProperties = component.getRecognizedProperties();
addRecognizedProperties(recognizedProperties);
} // addComponent(XMLComponent)
protected ValidationManager createValidationManager(){
return new ValidationManager();
}
protected final void setDTDValidatorFactory(String version) {
if ("1.1".equals(version)) {
if (fCurrentDVFactory != fXML11DatatypeFactory) {
fCurrentDVFactory = fXML11DatatypeFactory;
setProperty(DTD_VALIDATOR_FACTORY_PROPERTY, fCurrentDVFactory);
}
}
else if (fCurrentDVFactory != fDatatypeValidatorFactory) {
fCurrentDVFactory = fDatatypeValidatorFactory;
setProperty(DTD_VALIDATOR_FACTORY_PROPERTY, fCurrentDVFactory);
}
}
} // class XMLParser
| true | true | public void setParameter(String name, Object value) throws DOMException {
boolean found = true;
// REVISIT: Recognizes DOM L3 default features only.
// Does not yet recognize Xerces features.
if(value instanceof Boolean){
boolean state = ((Boolean)value).booleanValue();
if (name.equalsIgnoreCase(Constants.DOM_COMMENTS)) {
features = (short) (state ? features | COMMENTS : features & ~COMMENTS);
}
else if (name.equalsIgnoreCase(Constants.DOM_DATATYPE_NORMALIZATION)) {
setFeature(NORMALIZE_DATA, state);
features =
(short) (state ? features | DTNORMALIZATION : features & ~DTNORMALIZATION);
if (state) {
features = (short) (features | VALIDATE);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACES)) {
features = (short) (state ? features | NAMESPACES : features & ~NAMESPACES);
}
else if (name.equalsIgnoreCase(Constants.DOM_CDATA_SECTIONS)) {
features = (short) (state ? features | CDATA : features & ~CDATA);
}
else if (name.equalsIgnoreCase(Constants.DOM_ENTITIES)) {
features = (short) (state ? features | ENTITIES : features & ~ENTITIES);
}
else if (name.equalsIgnoreCase(Constants.DOM_SPLIT_CDATA)) {
features = (short) (state ? features | SPLITCDATA : features & ~SPLITCDATA);
}
else if (name.equalsIgnoreCase(Constants.DOM_VALIDATE)) {
features = (short) (state ? features | VALIDATE : features & ~VALIDATE);
}
else if (name.equalsIgnoreCase(Constants.DOM_WELLFORMED)) {
features = (short) (state ? features | WELLFORMED : features & ~WELLFORMED );
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACE_DECLARATIONS)) {
features = (short) (state ? features | NSDECL : features & ~NSDECL);
}
else if (name.equalsIgnoreCase(Constants.DOM_INFOSET)) {
// Setting to false has no effect.
if (state) {
features = (short) (features | INFOSET_TRUE_PARAMS);
features = (short) (features & ~INFOSET_FALSE_PARAMS);
setFeature(NORMALIZE_DATA, false);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS)
|| name.equalsIgnoreCase(Constants.DOM_CANONICAL_FORM)
|| name.equalsIgnoreCase(Constants.DOM_VALIDATE_IF_SCHEMA)
|| name.equalsIgnoreCase(Constants.DOM_CHECK_CHAR_NORMALIZATION)
) {
if (state) { // true is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if ( name.equalsIgnoreCase(Constants.DOM_ELEMENT_CONTENT_WHITESPACE)) {
if (!state) { // false is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if (name.equalsIgnoreCase(SEND_PSVI) ){
// REVISIT: turning augmentation of PSVI is not support,
// because in this case we won't be able to retrieve element
// default value.
if (!state) { // false is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_PSVI)){
features = (short) (state ? features | PSVI : features & ~PSVI);
}
else {
found = false;
/*
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_FOUND",
new Object[] { name });
throw new DOMException(DOMException.NOT_FOUND_ERR, msg);
*/
}
}
if (!found || !(value instanceof Boolean)) { // set properties
found = true;
if (name.equalsIgnoreCase(Constants.DOM_ERROR_HANDLER)) {
if (value instanceof DOMErrorHandler || value == null) {
fErrorHandlerWrapper.setErrorHandler((DOMErrorHandler)value);
setErrorHandler(fErrorHandlerWrapper);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_RESOURCE_RESOLVER)) {
if (value instanceof LSResourceResolver || value == null) {
try {
setEntityResolver(new DOMEntityResolverWrapper((LSResourceResolver) value));
}
catch (XMLConfigurationException e) {}
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_LOCATION)) {
if (value instanceof String || value == null) {
try {
// map DOM schema-location to JAXP schemaSource property
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE,
value);
}
catch (XMLConfigurationException e) {}
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_TYPE)) {
if (value instanceof String || value == null) {
try {
if (value == null) {
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
null);
}
else if (value.equals(Constants.NS_XMLSCHEMA)) {
// REVISIT: when add support to DTD validation
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
Constants.NS_XMLSCHEMA);
}
else if (value.equals(Constants.NS_DTD)) {
// Added support for revalidation against DTDs
setProperty(Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
Constants.NS_DTD);
}
}
catch (XMLConfigurationException e) {}
}
else {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(ENTITY_RESOLVER)) {
if (value instanceof XMLEntityResolver || value == null) {
try {
setEntityResolver((XMLEntityResolver) value);
}
catch (XMLConfigurationException e) {}
}
else {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(SYMBOL_TABLE)){
// Xerces Symbol Table
if (value instanceof SymbolTable){
setProperty(SYMBOL_TABLE, value);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase (GRAMMAR_POOL)){
if (value instanceof XMLGrammarPool){
setProperty(GRAMMAR_POOL, value);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else {
// REVISIT: check if this is a boolean parameter -- type mismatch should be thrown.
//parameter is not recognized
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_FOUND",
new Object[] { name });
throw new DOMException(DOMException.NOT_FOUND_ERR, msg);
}
}
}
| public void setParameter(String name, Object value) throws DOMException {
boolean found = true;
// REVISIT: Recognizes DOM L3 default features only.
// Does not yet recognize Xerces features.
if(value instanceof Boolean){
boolean state = ((Boolean)value).booleanValue();
if (name.equalsIgnoreCase(Constants.DOM_COMMENTS)) {
features = (short) (state ? features | COMMENTS : features & ~COMMENTS);
}
else if (name.equalsIgnoreCase(Constants.DOM_DATATYPE_NORMALIZATION)) {
setFeature(NORMALIZE_DATA, state);
features =
(short) (state ? features | DTNORMALIZATION : features & ~DTNORMALIZATION);
if (state) {
features = (short) (features | VALIDATE);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACES)) {
features = (short) (state ? features | NAMESPACES : features & ~NAMESPACES);
}
else if (name.equalsIgnoreCase(Constants.DOM_CDATA_SECTIONS)) {
features = (short) (state ? features | CDATA : features & ~CDATA);
}
else if (name.equalsIgnoreCase(Constants.DOM_ENTITIES)) {
features = (short) (state ? features | ENTITIES : features & ~ENTITIES);
}
else if (name.equalsIgnoreCase(Constants.DOM_SPLIT_CDATA)) {
features = (short) (state ? features | SPLITCDATA : features & ~SPLITCDATA);
}
else if (name.equalsIgnoreCase(Constants.DOM_VALIDATE)) {
features = (short) (state ? features | VALIDATE : features & ~VALIDATE);
}
else if (name.equalsIgnoreCase(Constants.DOM_WELLFORMED)) {
features = (short) (state ? features | WELLFORMED : features & ~WELLFORMED );
}
else if (name.equalsIgnoreCase(Constants.DOM_NAMESPACE_DECLARATIONS)) {
features = (short) (state ? features | NSDECL : features & ~NSDECL);
}
else if (name.equalsIgnoreCase(Constants.DOM_INFOSET)) {
// Setting to false has no effect.
if (state) {
features = (short) (features | INFOSET_TRUE_PARAMS);
features = (short) (features & ~INFOSET_FALSE_PARAMS);
setFeature(NORMALIZE_DATA, false);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_NORMALIZE_CHARACTERS)
|| name.equalsIgnoreCase(Constants.DOM_CANONICAL_FORM)
|| name.equalsIgnoreCase(Constants.DOM_VALIDATE_IF_SCHEMA)
|| name.equalsIgnoreCase(Constants.DOM_CHECK_CHAR_NORMALIZATION)
) {
if (state) { // true is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if ( name.equalsIgnoreCase(Constants.DOM_ELEMENT_CONTENT_WHITESPACE)) {
if (!state) { // false is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if (name.equalsIgnoreCase(SEND_PSVI) ){
// REVISIT: turning augmentation of PSVI is not support,
// because in this case we won't be able to retrieve element
// default value.
if (!state) { // false is not supported
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_SUPPORTED",
new Object[] { name });
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_PSVI)){
features = (short) (state ? features | PSVI : features & ~PSVI);
}
else {
found = false;
/*
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_FOUND",
new Object[] { name });
throw new DOMException(DOMException.NOT_FOUND_ERR, msg);
*/
}
}
if (!found || !(value instanceof Boolean)) { // set properties
found = true;
if (name.equalsIgnoreCase(Constants.DOM_ERROR_HANDLER)) {
if (value instanceof DOMErrorHandler || value == null) {
fErrorHandlerWrapper.setErrorHandler((DOMErrorHandler)value);
setErrorHandler(fErrorHandlerWrapper);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_RESOURCE_RESOLVER)) {
if (value instanceof LSResourceResolver || value == null) {
try {
setEntityResolver(new DOMEntityResolverWrapper((LSResourceResolver) value));
}
catch (XMLConfigurationException e) {}
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_LOCATION)) {
if (value instanceof String || value == null) {
try {
// map DOM schema-location to JAXP schemaSource property
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE,
value);
}
catch (XMLConfigurationException e) {}
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(Constants.DOM_SCHEMA_TYPE)) {
if (value instanceof String || value == null) {
try {
if (value == null) {
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
null);
}
else if (value.equals(Constants.NS_XMLSCHEMA)) {
// REVISIT: when add support to DTD validation
setProperty(
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
Constants.NS_XMLSCHEMA);
}
else if (value.equals(Constants.NS_DTD)) {
// Added support for revalidation against DTDs
setProperty(Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE,
Constants.NS_DTD);
}
}
catch (XMLConfigurationException e) {}
}
else {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(ENTITY_RESOLVER)) {
if (value instanceof XMLEntityResolver || value == null) {
try {
setEntityResolver((XMLEntityResolver) value);
}
catch (XMLConfigurationException e) {}
}
else {
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase(SYMBOL_TABLE)){
// Xerces Symbol Table
if (value instanceof SymbolTable){
setProperty(SYMBOL_TABLE, value);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else if (name.equalsIgnoreCase (GRAMMAR_POOL)){
if (value instanceof XMLGrammarPool || value == null) {
setProperty(GRAMMAR_POOL, value);
}
else {
// REVISIT: type mismatch
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"TYPE_MISMATCH_ERR",
new Object[] { name });
throw new DOMException(DOMException.TYPE_MISMATCH_ERR, msg);
}
}
else {
// REVISIT: check if this is a boolean parameter -- type mismatch should be thrown.
//parameter is not recognized
String msg =
DOMMessageFormatter.formatMessage(
DOMMessageFormatter.DOM_DOMAIN,
"FEATURE_NOT_FOUND",
new Object[] { name });
throw new DOMException(DOMException.NOT_FOUND_ERR, msg);
}
}
}
|
diff --git a/viewer3d/src/org/jcae/viewer3d/View.java b/viewer3d/src/org/jcae/viewer3d/View.java
index be474d47..a3b99434 100644
--- a/viewer3d/src/org/jcae/viewer3d/View.java
+++ b/viewer3d/src/org/jcae/viewer3d/View.java
@@ -1,1236 +1,1239 @@
/*
* Project Info: http://jcae.sourceforge.net
*
* 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 2.1 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* (C) Copyright 2005, by EADS CRC
*/
package org.jcae.viewer3d;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;
import java.util.Map.Entry;
import javax.media.j3d.*;
import javax.swing.JDialog;
import javax.swing.JTextPane;
import javax.vecmath.*;
import org.jcae.viewer3d.cad.ViewableCAD;
import org.jdesktop.j3d.utils.behaviors.vp.AxisBehavior;
import com.sun.j3d.utils.behaviors.vp.OrbitBehavior;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.universe.PlatformGeometry;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.universe.Viewer;
import com.sun.j3d.utils.universe.ViewingPlatform;
/**
* An AWT component wich display Viewable in a Java3D canvas.
* This class is responsible for handling picking and refresh events.
* The expected navigation behavior is the one of the OrbitBehavior of Java3D.
* Multiple selection is available using ctrl+Left click.
* @author Jerome Robert
* @todo all methods must be implemented. public methods may be added.
*/
public class View extends Canvas3D implements PositionListener
{
/** Cheat codes to change polygon offset on CAD */
private class PAKeyListener extends KeyAdapter
{
float offset=1.0f;
float offsetRel=1.0f;
public void keyPressed(KeyEvent e)
{
boolean found=true;
switch(e.getKeyChar())
{
case ']': offset *= 2; break;
case '[': offset /= 2; break;
case '}': offsetRel *= 2; break;
case '{': offsetRel /= 2; break;
default: found=false;
}
if(found)
{
ViewableCAD.polygonAttrFront.setPolygonOffset(offset);
ViewableCAD.polygonAttrBack.setPolygonOffset(offset);
ViewableCAD.polygonAttrNone.setPolygonOffset(offset);
ViewableCAD.polygonAttrFront.setPolygonOffsetFactor(offsetRel);
ViewableCAD.polygonAttrBack.setPolygonOffsetFactor(offsetRel);
ViewableCAD.polygonAttrNone.setPolygonOffsetFactor(offsetRel);
System.out.println("polygon offset: "+offset+" polygon offset factor: "+offsetRel);
}
}
}
final public static float FrontClipDistanceFactor=0.005f;
final public static float BackClipDistanceFactor=5f;
static JTextPane textPane;
private Switch originAxisSwitch=new Switch(Switch.CHILD_NONE);
private Switch fixedAxisSwitch=new Switch(Switch.CHILD_NONE);
private TransformGroup fixedAxisTransformGroup=new TransformGroup();
private TransformGroup originAxisTransformGroup=new TransformGroup();
private PickResult lastPickResult;
private View navigationMaster;
private List positionListeners=Collections.synchronizedList(new ArrayList());
private transient BufferedImage snapShot;
private transient Object snapShotLock=new Object();
private transient boolean takeSnapShot;
private transient ScreenshotListener screenshotListener;
static private SimpleUniverse sharedUniverse;
private SimpleUniverse universe;
static private Map viewableToViewSpecificGroup=Collections.synchronizedMap(new HashMap());
private ViewingPlatform viewingPlatform;
private BranchGroup axisBranchGroup=new BranchGroup();
private Viewable currentViewable;
protected OrbitBehavior orbit= new ViewBehavior(this);
private AxisBehavior axisBehavior;
ModelClip modelClip;
private boolean isModelClip=false;
private BranchGroup widgetsBranchGroup;
private BranchGroup unClipWidgetsBranchGroup;
private ClipBox clipBox=null;
private PrintWriter writer=null;
/**
* From https://java3d.dev.java.net/issues/show_bug.cgi?id=89
* Finds the preferred <code>GraphicsConfiguration</code> object
* for the system. This object can then be used to create the
* Canvas3D objet for this system.
* @param window the window in which the Canvas3D will reside
*
* @return The best <code>GraphicsConfiguration</code> object for
* the system.
*/
private static GraphicsConfiguration getPreferredConfiguration(Window window)
{
if(window==null)
return SimpleUniverse.getPreferredConfiguration();
GraphicsDevice device = window.getGraphicsConfiguration().getDevice();
GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();
String stereo;
// Check if the user has set the Java 3D stereo option.
// Getting the system properties causes appletviewer to fail with a
// security exception without a try/catch.
stereo = (String) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return System.getProperty("j3d.stereo");
}
});
// update template based on properties.
if (stereo != null) {
if (stereo.equals("REQUIRED"))
template.setStereo(GraphicsConfigTemplate.REQUIRED);
else if (stereo.equals("PREFERRED"))
template.setStereo(GraphicsConfigTemplate.PREFERRED);
}
// Return the GraphicsConfiguration that best fits our needs.
return device.getBestConfiguration(template);
}
/**
* See https://java3d.dev.java.net/issues/show_bug.cgi?id=89
* @deprecated Will cause a "java.lang.IllegalArgumentException: adding a
* container to a container on a different GraphicsDevice" in dual screen
* mode.
*/
public View()
{
this(null, false, true);
}
/**
* See https://java3d.dev.java.net/issues/show_bug.cgi?id=89
* @deprecated Will cause a "java.lang.IllegalArgumentException: adding a
* container to a container on a different GraphicsDevice" in dual screen
* mode.
*/
public View(boolean offscreen)
{
this(null, offscreen, true);
}
/**
* See https://java3d.dev.java.net/issues/show_bug.cgi?id=89
* @deprecated Will cause a "java.lang.IllegalArgumentException: adding a
* container to a container on a different GraphicsDevice" in dual screen
* mode.
*/
public View(boolean offscreen, boolean isSharedUniverse)
{
this(null, offscreen, isSharedUniverse);
}
public View(Window window)
{
this(window, false, true);
}
public View(Window window, boolean offscreen)
{
this(window, offscreen, true);
}
public View(Window window, boolean offscreen, boolean isSharedUniverse)
{
super(getPreferredConfiguration(window), offscreen);
if(offscreen)
{
getScreen3D().setPhysicalScreenWidth(0.0254/90.0 * 1600);
getScreen3D().setPhysicalScreenHeight(0.0254/90.0 * 1200);
}
if(isSharedUniverse)
{
if(sharedUniverse==null)
{
sharedUniverse=new SimpleUniverse(this);
universe=View.sharedUniverse;
viewingPlatform=universe.getViewingPlatform();
universe.addBranchGraph(
createLights(new BoundingSphere(new Point3d(),Double.MAX_VALUE)));
}
else
{
universe=View.sharedUniverse;
viewingPlatform=createViewingPlatform();
sharedUniverse.getLocale().addBranchGraph(viewingPlatform);
}
}
else
{
universe=new SimpleUniverse(this);
viewingPlatform=universe.getViewingPlatform();
universe.addBranchGraph(createLights(new BoundingSphere(new Point3d(),Double.MAX_VALUE)));
}
orbit.setCapability(Node.ALLOW_BOUNDS_WRITE);
viewingPlatform.setViewPlatformBehavior(orbit);
originAxisSwitch.setCapability(Switch.ALLOW_SWITCH_READ);
originAxisSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
fixedAxisSwitch.setCapability(Switch.ALLOW_SWITCH_READ);
fixedAxisSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
fixedAxisTransformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
// Create the origin axis
createAxis(originAxisTransformGroup);
originAxisSwitch.addChild(originAxisTransformGroup);
ViewSpecificGroup vsp=new ViewSpecificGroup();
vsp.addView(getView());
vsp.addChild(originAxisSwitch);
axisBranchGroup.addChild(vsp);
universe.addBranchGraph(axisBranchGroup);
createClipBranchGroup();
createWidgetsBranchGroup();
createUnClipWidgetsBranchGroup();
// Create the fixed axis
final TransformGroup tg=new TransformGroup();
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
Transform3D t3d=new Transform3D();
t3d.set(new Vector3d(-4, -4, -40));
createAxis(fixedAxisTransformGroup);
tg.setTransform(t3d);
tg.addChild(fixedAxisTransformGroup);
fixedAxisSwitch.addChild(tg);
PlatformGeometry pg=new PlatformGeometry();
vsp=new ViewSpecificGroup();
vsp.addView(getView());
vsp.addChild(fixedAxisSwitch);
pg.addChild(vsp);
axisBehavior=new AxisBehavior(fixedAxisTransformGroup,
viewingPlatform.getViewPlatformTransform());
pg.addChild(axisBehavior);
viewingPlatform.setPlatformGeometry(pg);
addComponentListener(new ComponentAdapter()
{
private Transform3D myT3d=new Transform3D();
public void componentResized(ComponentEvent e)
{
- tg.getTransform(myT3d);
- myT3d.set(new Vector3d(-4, -4*((float)getHeight())/getWidth(), -40));
- tg.setTransform(myT3d);
+ if(getWidth()!=0)
+ {
+ tg.getTransform(myT3d);
+ myT3d.set(new Vector3d(-4, -4*((float)getHeight())/getWidth(), -40));
+ tg.setTransform(myT3d);
+ }
}
});
getView().setFieldOfView(Math.PI/12);
getView().setFrontClipPolicy(javax.media.j3d.View.PHYSICAL_EYE);
getView().setBackClipPolicy(javax.media.j3d.View.PHYSICAL_EYE);
zoomTo(0,0,0,1.0f);
addKeyListener(new PAKeyListener());
}
private void createWidgetsBranchGroup(){
widgetsBranchGroup=new BranchGroup();
widgetsBranchGroup.setCapability(Group.ALLOW_CHILDREN_EXTEND);
widgetsBranchGroup.setCapability(Node.ALLOW_BOUNDS_READ);
widgetsBranchGroup.setCapability(Group.ALLOW_CHILDREN_WRITE);
widgetsBranchGroup.setCapability(Group.ALLOW_CHILDREN_READ);
BranchGroup parent=new BranchGroup();
parent.setCapability(Group.ALLOW_CHILDREN_EXTEND);
parent.setCapability(BranchGroup.ALLOW_DETACH);
parent.setCapability(Node.ALLOW_BOUNDS_READ);
parent.setCapability(Group.ALLOW_CHILDREN_WRITE);
ViewSpecificGroup vsg=new ViewSpecificGroup();
vsg.setCapability(ViewSpecificGroup.ALLOW_VIEW_WRITE);
vsg.setCapability(ViewSpecificGroup.ALLOW_VIEW_READ);
vsg.setCapability(Node.ALLOW_BOUNDS_READ);
vsg.setUserData(parent);
vsg.addChild(widgetsBranchGroup);
parent.addChild(vsg);
universe.getLocale().addBranchGraph(parent);
vsg.addView(getView());
}
private void createUnClipWidgetsBranchGroup(){
unClipWidgetsBranchGroup=new BranchGroup();
unClipWidgetsBranchGroup.setCapability(Group.ALLOW_CHILDREN_EXTEND);
unClipWidgetsBranchGroup.setCapability(Node.ALLOW_BOUNDS_READ);
unClipWidgetsBranchGroup.setCapability(Group.ALLOW_CHILDREN_WRITE);
unClipWidgetsBranchGroup.setCapability(Group.ALLOW_CHILDREN_READ);
BranchGroup parent=new BranchGroup();
parent.setCapability(Group.ALLOW_CHILDREN_EXTEND);
parent.setCapability(BranchGroup.ALLOW_DETACH);
parent.setCapability(Node.ALLOW_BOUNDS_READ);
parent.setCapability(Group.ALLOW_CHILDREN_WRITE);
ViewSpecificGroup vsg=new ViewSpecificGroup();
vsg.setCapability(ViewSpecificGroup.ALLOW_VIEW_WRITE);
vsg.setCapability(ViewSpecificGroup.ALLOW_VIEW_READ);
vsg.setCapability(Node.ALLOW_BOUNDS_READ);
vsg.setUserData(parent);
vsg.addChild(unClipWidgetsBranchGroup);
parent.addChild(vsg);
universe.getLocale().addBranchGraph(parent);
vsg.addView(getView());
}
private void createClipBranchGroup(){
BranchGroup clipBranchGroup=new BranchGroup();
clipBranchGroup.setCapability(Group.ALLOW_CHILDREN_EXTEND);
clipBranchGroup.setCapability(Node.ALLOW_BOUNDS_READ);
clipBranchGroup.setCapability(Group.ALLOW_CHILDREN_WRITE);
clipBranchGroup.setCapability(Group.ALLOW_CHILDREN_READ);
modelClip=new ModelClip();
modelClip.setEnables(new boolean[]{false, false, false, false, false, false});
modelClip.setCapability(ModelClip.ALLOW_ENABLE_READ);
modelClip.setCapability(ModelClip.ALLOW_ENABLE_WRITE);
modelClip.setCapability(ModelClip.ALLOW_PLANE_READ);
modelClip.setCapability(ModelClip.ALLOW_PLANE_WRITE);
modelClip.setCapability(ModelClip.ALLOW_SCOPE_READ);
modelClip.setCapability(ModelClip.ALLOW_SCOPE_WRITE);
modelClip.setCapability(ModelClip.ALLOW_INFLUENCING_BOUNDS_WRITE);
clipBranchGroup.addChild(modelClip);
universe.getLocale().addBranchGraph(clipBranchGroup);
}
/* (non-Javadoc)
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable
{
Viewable[] vs=getViewables();
for(int i=0; i<vs.length; i++)
{
remove(vs[i]);
}
universe.getLocale().removeBranchGraph(axisBranchGroup);
modelClip.removeAllScopes();
universe.getLocale().removeBranchGraph((BranchGroup)modelClip.getParent());
BranchGroup parent=(BranchGroup)widgetsBranchGroup.getParent().getParent();
universe.getLocale().removeBranchGraph(parent);
parent=(BranchGroup)unClipWidgetsBranchGroup.getParent().getParent();
universe.getLocale().removeBranchGraph(parent);
}
/** set a PrintWriter for the viewer messages*/
public void setPrintWriter(PrintWriter writer){
this.writer=writer;
}
/** print a line in the PrintWriter*/
public void println(String line){
if(writer!=null)
writer.println(line);
}
public TransformGroup getOriginAxisTransformGroup()
{
return originAxisTransformGroup;
}
/**
* @return
*/
private ViewingPlatform createViewingPlatform()
{
ViewingPlatform vp=new ViewingPlatform();
vp.setUniverse(universe);
Viewer viewer=new Viewer(this);
viewer.setViewingPlatform(vp);
return vp;
}
/** Add a Viewable to the current view */
public void add(Viewable viewable)
{
ViewSpecificGroup vsg=(ViewSpecificGroup) viewableToViewSpecificGroup.get(viewable);
if(vsg==null)
{
Node node=viewable.getJ3DNode();
BranchGroup parent=new BranchGroup();
parent.setCapability(Group.ALLOW_CHILDREN_EXTEND);
parent.setCapability(BranchGroup.ALLOW_DETACH);
parent.setCapability(Node.ALLOW_BOUNDS_READ);
parent.setCapability(Group.ALLOW_CHILDREN_WRITE);
vsg=new ViewSpecificGroup();
vsg.setCapability(ViewSpecificGroup.ALLOW_VIEW_WRITE);
vsg.setCapability(ViewSpecificGroup.ALLOW_VIEW_READ);
vsg.setCapability(Node.ALLOW_BOUNDS_READ);
vsg.setUserData(parent);
viewableToViewSpecificGroup.put(viewable, vsg);
vsg.addChild(node);
parent.addChild(vsg);
universe.getLocale().addBranchGraph(parent);
}
vsg.addView(getView());
if(currentViewable==null)
currentViewable=viewable;
if(isModelClip){
modelClip.addScope(getBranchGroup(viewable));
}
}
/**
* Allow to had a custom branchgroup to the view
* @param branchGroup
*/
public void addBranchGroup(BranchGroup branchGroup)
{
branchGroup.setCapability(BranchGroup.ALLOW_DETACH);
universe.getLocale().addBranchGraph(branchGroup);
}
/**
* add a widget BranchGroup
* @param branchGroup
*/
public void addWidgetBranchGroup(BranchGroup branchGroup)
{
branchGroup.setCapability(BranchGroup.ALLOW_DETACH);
widgetsBranchGroup.addChild(branchGroup);
}
/**
* remove the specified widget BranchGroup
* @param branchGroup
*/
public void removeWidgetBranchGroup(BranchGroup branchGroup){
widgetsBranchGroup.removeChild(branchGroup);
}
/**
* add a widget BranchGroup not clip by the clipModel
* @param branchGroup
*/
public void addUnClipWidgetBranchGroup(BranchGroup branchGroup)
{
branchGroup.setCapability(BranchGroup.ALLOW_DETACH);
unClipWidgetsBranchGroup.addChild(branchGroup);
}
/**
* remove the specified widget BranchGroup not clip by the clipModel
* @param branchGroup
*/
public void removeUnClipWidgetBranchGroup(BranchGroup branchGroup){
unClipWidgetsBranchGroup.removeChild(branchGroup);
}
private void setModelClip(ModelClip newModelClip){
removeModelClip();
initModelClipScope(modelClip);
for(int i=0;i<6;i++){
if(newModelClip.getEnable(i)){
Vector4d plane=new Vector4d();
newModelClip.getPlane(i,plane);
modelClip.setPlane(i,plane);
modelClip.setEnable(i,true);
}
}
modelClip.setInfluencingBounds(new BoundingSphere(new Point3d(),Double.MAX_VALUE));
isModelClip=true;
}
private void initModelClipScope(ModelClip modelClip) {
Viewable[] viewables=getViewables();
for(int i=0;i<viewables.length;i++)
modelClip.addScope(getBranchGroup(viewables[i]));
modelClip.addScope(widgetsBranchGroup);
}
/**
* remove the ModelClip of the view
*/
public void removeModelClip(){
modelClip.setEnables(new boolean[]{false, false, false, false, false, false});
modelClip.removeAllScopes();
isModelClip=false;
if(clipBox!=null)
removeUnClipWidgetBranchGroup(clipBox.getShape());
clipBox=null;
}
/** create the modelclip with the specified planes and remove the previous modelclip
* Warning : all shared viewables will be clipped in other views !!
* */
public void setClipPlanes(Vector4d[] planes){
ModelClip modelClip=new ModelClip();
modelClip.setEnables(new boolean[]{false, false, false, false, false, false});
for(int ii=0;ii<planes.length;ii++){
modelClip.setPlane(ii,planes[ii]);
modelClip.setEnable(ii,true);
}
modelClip.setInfluencingBounds(new BoundingSphere(new Point3d(),Double.MAX_VALUE));
setModelClip(modelClip);
}
/** create a clip Box and remove the previous modelclip
* Warning : all shared viewables will be clipped in other views !!
* */
public void setClipBox(ClipBox box) {
setClipPlanes(box.getClipBoxPlanes());
addUnClipWidgetBranchGroup(box.getShape());
clipBox=box;
}
/**returns true if the point is in the modelclip*/
public boolean isInModelClip(Point3d pt){
if(!isModelClip) return true;
Vector4d plane=new Vector4d();
double[] ptValues=new double[4];
pt.get(ptValues);
ptValues[3]=1;
Vector4d p=new Vector4d(ptValues);
for(int i=0;i<6;i++){
if(!modelClip.getEnable(i)) continue;
modelClip.getPlane(i,plane);
if(plane.dot(p)>0) return false;
}
return true;
}
/**
* @param view
*/
public void addPositionListener(PositionListener listener)
{
positionListeners.add(listener);
}
private Node createAxis(TransformGroup transformGroup)
{
float[] f=new float[] {
0, 0, 0, 1, 0, 0, // x line
0.9f, 0.1f, 0, 1, 0, 0, // x arrow 1
0.9f, -0.1f, 0, 1, 0, 0, // x arrow 2
0.9f, 0, 0.1f, 1, 0, 0, // x arrow 3
0.9f, 0, -0.1f, 1, 0, 0, // x arrow 1
0, 0, 0, 0, 1, 0, // y line
0.1f, 0.9f, 0, 0, 1, 0, // y arrow 1
-0.1f, 0.9f, 0, 0, 1, 0, // y arrow 2
0, 0.9f, 0.1f, 0, 1, 0, // y arrow 3
0, 0.9f, -0.1f, 0, 1, 0, // y arrow 4
0, 0, 0, 0, 0, 1, // z line
0.1f, 0, 0.9f, 0, 0, 1, // z arrow 1
-0.1f, 0, 0.9f, 0, 0, 1, // z arrow 2
0, 0.1f, 0.9f, 0, 0, 1, // z arrow 3
0, -0.1f, 0.9f, 0, 0, 1 // z arrow 4
};
LineArray la = new LineArray(f.length/3,
GeometryArray.COORDINATES);
la.setCoordinates(0, f);
Appearance a = new Appearance();
Color3f color=new Color3f(0.5f, 0.5f, 0.7f);
ColoringAttributes ca = new ColoringAttributes(color,
ColoringAttributes.FASTEST);
a.setColoringAttributes(ca);
Shape3D s3d = new Shape3D(la);
s3d.setAppearance(a);
transformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
transformGroup.addChild(s3d);
transformGroup.addChild(new RasterTextLabel("x", Color.WHITE, 1.1f, 0, 0));
transformGroup.addChild(new RasterTextLabel("y", Color.WHITE, 0, 1.1f, 0));
transformGroup.addChild(new RasterTextLabel("z", Color.WHITE, 0, 0, 1.1f));
transformGroup.setCapability(Node.ALLOW_BOUNDS_READ);
return transformGroup;
}
private Node createLabel(String label, float x, float y, float z, Color color, Font font)
{
//Compute the size of the string
/*BufferedImage image=new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d=(Graphics2D) image.getGraphics();
Rectangle2D dim=font.getStringBounds(label, g2d.getFontRenderContext());
System.out.println(dim);*/
//Create the image
BufferedImage image=new BufferedImage(8, 15, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g2d=(Graphics2D) image.getGraphics();
g2d.setFont(font);
g2d.drawString(label, 0, 11);
/*try
{
ImageIO.write(image, "png", new File("/tmp/raster"+label+".png"));
} catch (IOException e)
{
e.printStackTrace();
}*/
float[] data=new float[image.getWidth()*image.getHeight()];
Arrays.fill(data, 1.0f);
DepthComponentFloat dcf=new DepthComponentFloat(image.getWidth(), image.getHeight());
dcf.setDepthData(data);
Raster ras = new Raster();
ras.setSize(image.getWidth(), image.getHeight());
ras.setImage(new ImageComponent2D(ImageComponent.FORMAT_RGBA, image));
ras.setPosition(new Point3f(x,y,z));
ras.setDepthComponent(dcf);
Dimension dim=new Dimension();
ras.getSize(dim);
System.out.println(dim);
Shape3D s3d=new Shape3D();
TransparencyAttributes ta = new TransparencyAttributes(
TransparencyAttributes.BLENDED, 0 );
Appearance app=new Appearance();
app.setTransparencyAttributes(ta);
s3d.addGeometry(ras);
s3d.setAppearance(app);
return s3d;
}
private BranchGroup createLights(Bounds bounds)
{
BranchGroup gp=new BranchGroup();
// Set up the ambient light
Color3f ambientColor = new Color3f(0.1f, 0.1f, 0.1f);
AmbientLight ambientLightNode = new AmbientLight(ambientColor);
ambientLightNode.setInfluencingBounds(bounds);
gp.addChild(ambientLightNode);
// Set up the directional lights
Color3f light1Color = new Color3f(1.0f, 1.0f, 0.9f);
Vector3f light1Direction = new Vector3f(1.0f, 1.0f, 1.0f);
DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction);
light1.setInfluencingBounds(bounds);
gp.addChild(light1);
Color3f light2Color = new Color3f(1.0f, 1.0f, 1.0f);
Vector3f light2Direction = new Vector3f(-1.0f, -1.0f, -1.0f);
DirectionalLight light2 = new DirectionalLight(light2Color, light2Direction);
light2.setInfluencingBounds(bounds);
light2.setCapability(Light.ALLOW_INFLUENCING_BOUNDS_WRITE);
light2.setCapability(Light.ALLOW_INFLUENCING_BOUNDS_READ);
gp.addChild(light2);
return gp;
}
private void displayTransform3d(Transform3D transform)
{
if(textPane==null)
{
JDialog d=new JDialog();
textPane=new JTextPane();
d.setContentPane(textPane);
d.setVisible(true);
}
String cr=System.getProperty("line.separator");
String s="scale="+transform.getScale()+cr;
Matrix3f m=new Matrix3f();
Vector3f v=new Vector3f();
transform.get(m);
transform.get(v);
s+="rotation="+m+cr;
s+="translation="+v+cr;
textPane.setText(s);
}
protected void firePositionChanged()
{
Iterator it=positionListeners.iterator();
while(it.hasNext())
{
PositionListener p=(PositionListener)it.next();
p.positionChanged();
}
}
/** Fit the view to show the specified viewable */
public void fit(Viewable viewable)
{
BoundingSphere b= (BoundingSphere)getBranchGroup(viewable).getBounds();
Point3d c=new Point3d();
b.getCenter(c);
zoomTo((float)c.x,(float)c.y,(float)c.z,(float)b.getRadius());
}
/** Fit the view to show all the Viewable */
public void fitAll()
{
BoundingSphere bs=getBound();
if(bs.getRadius()<=0)
bs=new BoundingSphere();
Point3d c=new Point3d();
bs.getCenter(c);
zoomTo((float)c.x,(float)c.y,(float)c.z,(float)bs.getRadius());
}
/** restore the Front clip distance to see all the Viewable */
public void restoreFrontClipDistance(){
BoundingSphere bs=getBound();
if(bs.getRadius()<=0)
bs=new BoundingSphere();
getView().setFrontClipDistance(FrontClipDistanceFactor*(float)bs.getRadius());
}
public void setFrontClipDistance(double d){
getView().setFrontClipDistance(d);
}
public double getFrontClipDistance(){
return getView().getFrontClipDistance();
}
public double getBackClipDistance(){
return getView().getBackClipDistance();
}
public void setBackClipDistance(double d){
getView().setBackClipDistance(d);
}
protected BoundingSphere getBound()
{
Iterator it=viewableToViewSpecificGroup.values().iterator();
ArrayList bounds=new ArrayList();
while(it.hasNext())
{
ViewSpecificGroup bg=(ViewSpecificGroup) it.next();
if(bg.indexOfView(getView())!=-1)
{
Bounds b=bg.getBounds();
bounds.add(b);
}
}
if(isOriginAxisVisible())
bounds.add(originAxisTransformGroup.getBounds());
BoundingSphere bs;
if(bounds.size()>0)
{
bs=(BoundingSphere) bounds.get(0);
bs.combine((Bounds[]) bounds.toArray(new Bounds[bounds.size()]));
}
else
bs=new BoundingSphere();
return bs;
}
/**
* Get the cloned branchgroup of a viewable for this view.
* The viewables may used it to modify a branchgroup whithout rebuilding
* it entirely.
* @param view
* @return
*
*/
protected BranchGroup getBranchGroup(Viewable viewable)
{
ViewSpecificGroup vsp=(ViewSpecificGroup) viewableToViewSpecificGroup.get(viewable);
if(vsp==null) return null;
return (BranchGroup)vsp.getUserData();
}
/** Return viewables shown in this view */
public Viewable[] getViewables()
{
ArrayList toReturn=new ArrayList();
Iterator it=viewableToViewSpecificGroup.entrySet().iterator();
while(it.hasNext())
{
Map.Entry e=(Entry) it.next();
Viewable v=(Viewable) e.getKey();
ViewSpecificGroup vsg=(ViewSpecificGroup) e.getValue();
if(vsg.indexOfView(getView())!=-1)
{
toReturn.add(v);
}
}
return (Viewable[])toReturn.toArray(new Viewable[toReturn.size()]);
}
public Viewable getCurrentViewable()
{
return currentViewable;
}
public ViewingPlatform getViewingPlatform()
{
return viewingPlatform;
}
public void setCurrentViewable(Viewable v)
{
currentViewable=v;
}
/** Move the view to the specified position */
public void move(Transform3D position)
{
viewingPlatform.getViewPlatformTransform().setTransform(position);
}
/**
* Implement PositionListener.
* This listener is fired when the navigation master move.
*/
public void positionChanged()
{
move(navigationMaster.where());
}
/**
* Overloaded for to be able to take snapshots and draw overlays
* (selection rectangle)
* @see takeSnapshot
*/
public void postSwap()
{
super.postSwap();
try
{
if (takeSnapShot)
{
snapShot = getImage();
takeSnapShot = false;
synchronized(snapShotLock)
{
snapShotLock.notifyAll();
}
if(screenshotListener!=null)
screenshotListener.shot(snapShot);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
/**
* Return an Image representing the current Canvas3D
* This method is not synchronized with the Java3D rendering.
* It used by takeSnapShopt method (which add synchronization),
* and for the rendering of the rectangle selection.
*/
protected BufferedImage getImage()
{
Dimension dim=getSize();
GraphicsContext3D ctx = getGraphicsContext3D();
Raster ras=new Raster();
ras.setSize(dim);
ras.setImage(new ImageComponent2D(ImageComponent.FORMAT_RGB,dim.width, dim.height));
ctx.readRaster(ras);
// Now strip out the image info
return ras.getImage().getImage();
}
/** Remove a viewable from this view */
public void remove(Viewable viewable)
{
ViewSpecificGroup vsg=(ViewSpecificGroup) viewableToViewSpecificGroup.get(viewable);
if(vsg!=null)
{
vsg.removeView(getView());
if(vsg.numViews()==0)
{
if(isModelClip){
modelClip.removeScope(getBranchGroup(viewable));
}
universe.getLocale().removeBranchGraph(getBranchGroup(viewable));
viewableToViewSpecificGroup.remove(viewable);
vsg.removeAllChildren();
}
}
if(currentViewable==viewable)
{
Viewable[] vs=getViewables();
if(vs.length>0)
currentViewable=vs[0];
else
currentViewable=null;
}
}
/** inform if the view contains the viewable*/
public boolean contains(Viewable viewable){
ViewSpecificGroup vsg=(ViewSpecificGroup) viewableToViewSpecificGroup.get(viewable);
if(vsg==null) return false;
Enumeration e=vsg.getAllViews();
while(e.hasMoreElements())
if(e.nextElement()==this.getView()) return true;
return false;
}
/** Create a navigation link with the specified view.
* This will ensure that the current view show the same Position as the
* specified view.
* @param view the master view, null mean no master.
*/
public void setNavigationMaster(View view)
{
navigationMaster=view;
view.addPositionListener(this);
}
/**
* Set the list of Viewables to which picking events will be dispatched.
* The Viewable objects not in this list will not be pickable.
* @param viewables
*/
public void setPickableViewables(Collection viewables)
{
//TODO
}
/**
* Set the picking mode:
* <ul>
* <li>0, for single click picking</li>
* <li>1, for rectangular selection picking</li>
* <li>2, for polygonal selection picking</li>
* </ul>
* @param mode
*/
public void setPickingMode(short mode)
{
//TODO
}
/**
* Display 3D x-y-z cartesian, at the center of the view.
* These axis are visible whenever the 3D origin cannot be seen.
* Axis are identified with strings "x","y" and "z".
* The size of the axis do not depends on the zoom level.
* @param show
*/
public void setFixedAxisVisible(boolean show)
{
if(show)
fixedAxisSwitch.setWhichChild(0);
else
fixedAxisSwitch.setWhichChild(Switch.CHILD_NONE);
}
/**
* Display 3D x-y-z cartesian at the 3D origin of the model.
* Axis are identified with strings "x","y" and "z".
* The size of the axis do not depends on the zoom level.
* @param show
*/
public void setOriginAxisVisible(boolean show)
{
if(show)
originAxisSwitch.setWhichChild(0);
else
originAxisSwitch.setWhichChild(Switch.CHILD_NONE);
}
public boolean isOriginAxisVisible()
{
return originAxisSwitch.getWhichChild()==0;
}
/**
* Take a snapshot of the current view
* Do not use this for offscreen rendering. See "On-screen Rendering vs. Off-screen Rendering" in
* Canvas3D javadoc. This method should be wrapped in a SwingUtilities.invokeXXXX statements.
* @deprecated Use takeScreenshot Not thread safe. In some configuration a deadlock could
* occure.
*/
// snapShotLock.wait(); must not be run in an AWT thread because
// it would block the AWT event thread. Then AWT would never notify the
// J3D rendering thread and snapShotLock.wait() would never return
public BufferedImage takeSnapshot()
{
takeSnapShot=true;
synchronized(snapShotLock)
{
try
{
snapShotLock.wait();
} catch(InterruptedException ex)
{
ex.printStackTrace();
return new BufferedImage(0, 0, BufferedImage.TYPE_BYTE_INDEXED);
}
}
return snapShot;
}
/**
* Take a snapshot of the current view
* Do not use this for offscreen rendering. See "On-screen Rendering vs. Off-screen Rendering" in
* Canvas3D javadoc.
*/
public void takeScreenshot(ScreenshotListener listener)
{
screenshotListener=listener;
takeSnapShot=true;
getView().repaint();
}
/**
* Take a snapshot of the current view in Off-screen mode
* Do not use this for on-screen rendering. See "On-screen Rendering vs. Off-screen Rendering" in
* Canvas3D javadoc.
*/
public BufferedImage takeSnapshot(int w, int h)
{
getScreen3D().setSize(w,h);
BufferedImage image=new BufferedImage(w,h, ImageComponent.FORMAT_RGB);
setOffScreenBuffer(new ImageComponent2D(ImageComponent.FORMAT_RGB, image));
renderOffScreenBuffer();
waitForOffScreenRendering();
return getOffScreenBuffer().getImage();
}
/** Return the current position of the view */
public Transform3D where()
{
Transform3D t3d=new Transform3D();
viewingPlatform.getViewPlatformTransform().getTransform(t3d);
return t3d;
}
/** Modify the view to best see what is include a given sphere
* @param x x coordinate of the center of the sphere
* @param y y coordinate of the center of the sphere
* @param z z coordinate of the center of the sphere
* @param radius radius of the sphere
*/
public void zoomTo(float x, float y, float z, float radius)
{
Point3d c=new Point3d(x,y,z);
BoundingSphere b=new BoundingSphere(c,radius);
orbit.setBounds(b);
orbit.setRotationCenter(c);
orbit.setZoomFactor(b.getRadius());
orbit.setTransFactors(b.getRadius()/10,b.getRadius()/10);
orbit.setRotFactors(0.5, 0.5);
orbit.setSchedulingBounds(new BoundingSphere(c,b.getRadius()*100));
axisBehavior.setSchedulingBounds(orbit.getSchedulingBounds());
getView().setFrontClipDistance(FrontClipDistanceFactor*radius);
getView().setBackClipDistance(BackClipDistanceFactor*radius);
//getView().setWindowResizePolicy(javax.media.j3d.View.VIRTUAL_WORLD);
Transform3D t3d = new Transform3D();
viewingPlatform.getViewPlatformTransform().getTransform(t3d);
//calculate the translation vector for a identity rotation matrix
float focal=(float) Math.tan(getView().getFieldOfView()/2);
Vector3f correction=new Vector3f(0f, 0f, radius/focal);
t3d.setTranslation(new Vector3f());
//rotate the translation vector
t3d.transform(correction);
correction.add(new Vector3f(x,y,z));
t3d.setTranslation(correction);
viewingPlatform.getViewPlatformTransform().setTransform(t3d);
//orbit.setViewingPlatform(viewingPlatform);
}
public double[] getRotationCenter()
{
Point3d p3d=new Point3d();
orbit.getRotationCenter(p3d);
double[] toReturn=new double[3];
p3d.get(toReturn);
return toReturn;
}
public void setRotationCenter(double x, double y, double z)
{
orbit.setRotationCenter(new Point3d(x, y, z));
}
public void setChangeRotationCenter(boolean status)
{
this.requestFocus();
((ViewBehavior)orbit).setChangeRotationCenter(true);
}
/** set the current mouse mode : see ViewBehavior*/
public void setMouseMode(int mode){
this.requestFocus();
((ViewBehavior)orbit).setMouseMode(mode);
}
private int getMouseMode(){
return ((ViewBehavior)orbit).getMouseMode();
}
public final static byte TOP =0;
public final static byte BOTTOM =1;
public final static byte LEFT =2;
public final static byte RIGHT =3;
public final static byte FRONT =4;
public final static byte BACK =5;
/** TOP, BOTTOM, LEFT, RIGHT, FRONT, BACK */
public void setOrientation(byte orientation)
{
Point3d eye=null;
Vector3d up=new Vector3d(0,1,0);
switch(orientation)
{
case TOP:
eye=new Point3d(0, 1, 0);
up=new Vector3d(0,0,-1);
break;
case BOTTOM:
eye=new Point3d(0, -1, 0);
up=new Vector3d(0,0,1);
break;
case LEFT:
eye=new Point3d(-1, 0, 0);
break;
case RIGHT:
eye=new Point3d(1, 0, 0);
break;
case FRONT:
eye=new Point3d(0, 0, 1);
break;
case BACK:
eye=new Point3d(0, 0, -1);
break;
default:
throw new IllegalArgumentException();
}
BoundingSphere bs=getBound();
Transform3D t3d=new Transform3D();
Point3d center=new Point3d();
bs.getCenter(center);
float focal=(float) Math.tan(getView().getFieldOfView()/2);
eye.scale(bs.getRadius()/focal);
t3d.lookAt(eye, center, up);
t3d.invert();
move(t3d);
}
protected void fireViewableChanged(Viewable viewable){
BranchGroup bg=getBranchGroup(viewable);
if(modelClip.indexOfScope(bg)>0)
modelClip.removeScope(bg);
modelClip.addScope(bg);
}
public static void viewableChanged(Viewable viewable){
ViewSpecificGroup vsg=(ViewSpecificGroup) viewableToViewSpecificGroup.get(viewable);
if(vsg!=null){
Enumeration e=vsg.getAllViews();
while(e.hasMoreElements()){
Object o=e.nextElement();
if( o instanceof javax.media.j3d.View){
Enumeration ee=((javax.media.j3d.View)o).getAllCanvas3Ds();
while(ee.hasMoreElements()){
Object oo=ee.nextElement();
if( oo instanceof View){
((View)oo).fireViewableChanged(viewable);
}
}
}
}
}
}
public static void stopRenderer(Viewable viewable){
ViewSpecificGroup vsg=(ViewSpecificGroup) viewableToViewSpecificGroup.get(viewable);
if(vsg!=null){
Enumeration e=vsg.getAllViews();
while(e.hasMoreElements()){
Object o=e.nextElement();
if( o instanceof javax.media.j3d.View){
Enumeration ee=((javax.media.j3d.View)o).getAllCanvas3Ds();
while(ee.hasMoreElements()){
Object oo=ee.nextElement();
if( oo instanceof View){
((View)oo).stopRenderer();
}
}
}
}
}
}
public static void startRenderer(Viewable viewable){
ViewSpecificGroup vsg=(ViewSpecificGroup) viewableToViewSpecificGroup.get(viewable);
if(vsg!=null){
Enumeration e=vsg.getAllViews();
while(e.hasMoreElements()){
Object o=e.nextElement();
if( o instanceof javax.media.j3d.View){
Enumeration ee=((javax.media.j3d.View)o).getAllCanvas3Ds();
while(ee.hasMoreElements()){
Object oo=ee.nextElement();
if( oo instanceof View){
((View)oo).startRenderer();
}
}
}
}
}
}
}
| true | true | public View(Window window, boolean offscreen, boolean isSharedUniverse)
{
super(getPreferredConfiguration(window), offscreen);
if(offscreen)
{
getScreen3D().setPhysicalScreenWidth(0.0254/90.0 * 1600);
getScreen3D().setPhysicalScreenHeight(0.0254/90.0 * 1200);
}
if(isSharedUniverse)
{
if(sharedUniverse==null)
{
sharedUniverse=new SimpleUniverse(this);
universe=View.sharedUniverse;
viewingPlatform=universe.getViewingPlatform();
universe.addBranchGraph(
createLights(new BoundingSphere(new Point3d(),Double.MAX_VALUE)));
}
else
{
universe=View.sharedUniverse;
viewingPlatform=createViewingPlatform();
sharedUniverse.getLocale().addBranchGraph(viewingPlatform);
}
}
else
{
universe=new SimpleUniverse(this);
viewingPlatform=universe.getViewingPlatform();
universe.addBranchGraph(createLights(new BoundingSphere(new Point3d(),Double.MAX_VALUE)));
}
orbit.setCapability(Node.ALLOW_BOUNDS_WRITE);
viewingPlatform.setViewPlatformBehavior(orbit);
originAxisSwitch.setCapability(Switch.ALLOW_SWITCH_READ);
originAxisSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
fixedAxisSwitch.setCapability(Switch.ALLOW_SWITCH_READ);
fixedAxisSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
fixedAxisTransformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
// Create the origin axis
createAxis(originAxisTransformGroup);
originAxisSwitch.addChild(originAxisTransformGroup);
ViewSpecificGroup vsp=new ViewSpecificGroup();
vsp.addView(getView());
vsp.addChild(originAxisSwitch);
axisBranchGroup.addChild(vsp);
universe.addBranchGraph(axisBranchGroup);
createClipBranchGroup();
createWidgetsBranchGroup();
createUnClipWidgetsBranchGroup();
// Create the fixed axis
final TransformGroup tg=new TransformGroup();
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
Transform3D t3d=new Transform3D();
t3d.set(new Vector3d(-4, -4, -40));
createAxis(fixedAxisTransformGroup);
tg.setTransform(t3d);
tg.addChild(fixedAxisTransformGroup);
fixedAxisSwitch.addChild(tg);
PlatformGeometry pg=new PlatformGeometry();
vsp=new ViewSpecificGroup();
vsp.addView(getView());
vsp.addChild(fixedAxisSwitch);
pg.addChild(vsp);
axisBehavior=new AxisBehavior(fixedAxisTransformGroup,
viewingPlatform.getViewPlatformTransform());
pg.addChild(axisBehavior);
viewingPlatform.setPlatformGeometry(pg);
addComponentListener(new ComponentAdapter()
{
private Transform3D myT3d=new Transform3D();
public void componentResized(ComponentEvent e)
{
tg.getTransform(myT3d);
myT3d.set(new Vector3d(-4, -4*((float)getHeight())/getWidth(), -40));
tg.setTransform(myT3d);
}
});
getView().setFieldOfView(Math.PI/12);
getView().setFrontClipPolicy(javax.media.j3d.View.PHYSICAL_EYE);
getView().setBackClipPolicy(javax.media.j3d.View.PHYSICAL_EYE);
zoomTo(0,0,0,1.0f);
addKeyListener(new PAKeyListener());
}
| public View(Window window, boolean offscreen, boolean isSharedUniverse)
{
super(getPreferredConfiguration(window), offscreen);
if(offscreen)
{
getScreen3D().setPhysicalScreenWidth(0.0254/90.0 * 1600);
getScreen3D().setPhysicalScreenHeight(0.0254/90.0 * 1200);
}
if(isSharedUniverse)
{
if(sharedUniverse==null)
{
sharedUniverse=new SimpleUniverse(this);
universe=View.sharedUniverse;
viewingPlatform=universe.getViewingPlatform();
universe.addBranchGraph(
createLights(new BoundingSphere(new Point3d(),Double.MAX_VALUE)));
}
else
{
universe=View.sharedUniverse;
viewingPlatform=createViewingPlatform();
sharedUniverse.getLocale().addBranchGraph(viewingPlatform);
}
}
else
{
universe=new SimpleUniverse(this);
viewingPlatform=universe.getViewingPlatform();
universe.addBranchGraph(createLights(new BoundingSphere(new Point3d(),Double.MAX_VALUE)));
}
orbit.setCapability(Node.ALLOW_BOUNDS_WRITE);
viewingPlatform.setViewPlatformBehavior(orbit);
originAxisSwitch.setCapability(Switch.ALLOW_SWITCH_READ);
originAxisSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
fixedAxisSwitch.setCapability(Switch.ALLOW_SWITCH_READ);
fixedAxisSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
fixedAxisTransformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
// Create the origin axis
createAxis(originAxisTransformGroup);
originAxisSwitch.addChild(originAxisTransformGroup);
ViewSpecificGroup vsp=new ViewSpecificGroup();
vsp.addView(getView());
vsp.addChild(originAxisSwitch);
axisBranchGroup.addChild(vsp);
universe.addBranchGraph(axisBranchGroup);
createClipBranchGroup();
createWidgetsBranchGroup();
createUnClipWidgetsBranchGroup();
// Create the fixed axis
final TransformGroup tg=new TransformGroup();
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
Transform3D t3d=new Transform3D();
t3d.set(new Vector3d(-4, -4, -40));
createAxis(fixedAxisTransformGroup);
tg.setTransform(t3d);
tg.addChild(fixedAxisTransformGroup);
fixedAxisSwitch.addChild(tg);
PlatformGeometry pg=new PlatformGeometry();
vsp=new ViewSpecificGroup();
vsp.addView(getView());
vsp.addChild(fixedAxisSwitch);
pg.addChild(vsp);
axisBehavior=new AxisBehavior(fixedAxisTransformGroup,
viewingPlatform.getViewPlatformTransform());
pg.addChild(axisBehavior);
viewingPlatform.setPlatformGeometry(pg);
addComponentListener(new ComponentAdapter()
{
private Transform3D myT3d=new Transform3D();
public void componentResized(ComponentEvent e)
{
if(getWidth()!=0)
{
tg.getTransform(myT3d);
myT3d.set(new Vector3d(-4, -4*((float)getHeight())/getWidth(), -40));
tg.setTransform(myT3d);
}
}
});
getView().setFieldOfView(Math.PI/12);
getView().setFrontClipPolicy(javax.media.j3d.View.PHYSICAL_EYE);
getView().setBackClipPolicy(javax.media.j3d.View.PHYSICAL_EYE);
zoomTo(0,0,0,1.0f);
addKeyListener(new PAKeyListener());
}
|
diff --git a/mysql-mds/src/main/java/org/bestgrid/mds/SQLQueryClient.java b/mysql-mds/src/main/java/org/bestgrid/mds/SQLQueryClient.java
index b93e4f6..c20e583 100644
--- a/mysql-mds/src/main/java/org/bestgrid/mds/SQLQueryClient.java
+++ b/mysql-mds/src/main/java/org/bestgrid/mds/SQLQueryClient.java
@@ -1,1129 +1,1129 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.bestgrid.mds;
import grisu.control.info.GridResourceBackendImpl;
import grisu.jcommons.constants.Constants;
import grisu.jcommons.constants.JobSubmissionProperty;
import grisu.jcommons.interfaces.GridInfoInterface;
import grisu.jcommons.interfaces.GridResource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import au.edu.sapac.grid.mds.QueryClient;
/**
*
* @author yhal003
*/
public class SQLQueryClient implements GridInfoInterface {
public final String VOLATILE="volatile";
static final Logger myLogger = Logger.getLogger(SQLQueryClient.class
.getName());
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://mysql-bg.ceres.auckland.ac.nz/mds_test",
"grisu_read", "password");
QueryClient qClient = new QueryClient("/tmp");
SQLQueryClient sClient = new SQLQueryClient(con);
HashMap<JobSubmissionProperty, String> props = new HashMap<JobSubmissionProperty, String>();
props.put(JobSubmissionProperty.APPLICATIONNAME, Constants.GENERIC_APPLICATION_NAME);
props.put(JobSubmissionProperty.APPLICATIONVERSION, Constants.NO_VERSION_INDICATOR_STRING);
props.put(JobSubmissionProperty.WALLTIME_IN_MINUTES, "4000");
System.out.println("Check R...");
List<GridResource> resources = sClient.findAllResourcesM(props,
"/ARCS/Monash", true);
for (GridResource r : resources) {
System.out.println("R site: " + r.getSiteName());
}
printResults(
qClient.getApplicationNamesThatProvideExecutable("javac"),
"Query Client method 1");
printResults(
sClient.getApplicationNamesThatProvideExecutable("javac"),
"SQL Client method 1");
// appears broken
// printResults(qClient.getClusterNamesAtSite("canterbury.ac.nz"),"Query Client method 2");
printResults(sClient.getClusterNamesAtSite("Canterbury"),
"SQL Client method 2");
// broken too, maybe...
// printResults(qClient.getClustersForCodeAtSite("canterbury.ac.nz","Java","1.4.2"),"Query Client method 3");
printResults(sClient.getClustersForCodeAtSite("Canterbury", "Java",
"1.4.2"), "SQL Client method 3");
printResults(qClient.getCodesAtSite("Canterbury"),
"Query Client method 4");
printResults(sClient.getCodesAtSite("Canterbury"),
"SQL Client method 4");
printResults(qClient.getCodesOnGrid(), "Query Client method 5");
printResults(sClient.getCodesOnGrid(), "SQL Client method 5");
printResults(qClient.getContactStringOfQueueAtSite("eRSA",
"hydra@hydra"), "Query Client method 6");
printResults(sClient.getContactStringOfQueueAtSite("eRSA",
"hydra@hydra"), "SQL Client method 6");
printResults(qClient.getDataDir("Auckland", "ng2.auckland.ac.nz",
"/ARCS/BeSTGRID"), "Query Client method 7");
printResults(sClient.getDataDir("Auckland", "ng2.auckland.ac.nz",
"/ARCS/BeSTGRID"), "SQL Client method 7");
printResults(
new String[] { qClient.getDefaultStorageElementForQueueAtSite(
"Canterbury", "grid_aix") },
"Query Client method 8");
printResults(
new String[] { sClient.getDefaultStorageElementForQueueAtSite(
"Canterbury", "grid_aix") }, "SQL Client method 8");
printResults(
qClient.getExeNameOfCodeAtSite("Auckland", "Java", "1.6"),
"Query Client method 9");
printResults(
sClient.getExeNameOfCodeAtSite("Auckland", "Java", "1.6"),
"SQL Client method 9");
printResults(qClient.getExeNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6"), "Query Client method 10");
printResults(sClient.getExeNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6"), "SQL Client method 10");
printResults(qClient.getGridFTPServersAtSite("Auckland"),
"Query Client method 11");
printResults(sClient.getGridFTPServersAtSite("Auckland"),
"SQL Client method 11");
printResults(qClient.getGridFTPServersForQueueAtSite("Auckland",
"[email protected]"),
"Query Client method 12");
printResults(sClient.getGridFTPServersForQueueAtSite("Auckland",
"[email protected]"),
"SQL Client method 12");
printResults(qClient.getGridFTPServersForStorageElementAtSite(
"Auckland", "ngdata.ceres.auckland.ac.nz"),
"Query Client method 13");
printResults(sClient.getGridFTPServersForStorageElementAtSite(
"Auckland", "ngdata.ceres.auckland.ac.nz"),
"SQL Client method 13");
// also broken
// printResults(qClient.getGridFTPServersOnGrid(),"Query Client method 14");
printResults(sClient.getGridFTPServersOnGrid(),
"SQL Client method 14");
printResults(new String[] { qClient.getJobManagerOfQueueAtSite(
"Auckland", "[email protected]") },
"Query Client method 15");
printResults(new String[] { sClient.getJobManagerOfQueueAtSite(
"Auckland", "[email protected]") },
"SQL Client method 15");
// not sure what we are supposed to do here
// System.out.println(qClient.getJobTypeOfCodeAtSite("Auckland",
// "Java", "1.6"));
printResults(new String[] { qClient.getLRMSTypeOfQueueAtSite(
"Auckland", "[email protected]") },
"Query Client method 17");
printResults(new String[] { sClient.getLRMSTypeOfQueueAtSite(
"Auckland", "[email protected]") },
"SQL Client method 17");
printResults(
new String[] { qClient
.getModuleNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6") }, "Query Client method 18");
printResults(
new String[] { sClient
.getModuleNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6") }, "SQL Client method 18");
printResults(qClient.getQueueNamesAtSite("Canterbury"),
"Query Client method 19");
printResults(sClient.getQueueNamesAtSite("Canterbury"),
"SQL Client method 19");
printResults(
qClient.getQueueNamesAtSite("Canterbury", "/ARCS/NGAdmin"),
"Query Client method 20");
printResults(
sClient.getQueueNamesAtSite("Canterbury", "/ARCS/NGAdmin"),
"SQL Client method 20");
// broken too!
// printResults(qClient.getQueueNamesForClusterAtSite("Canterbury","ng1.canterbury.ac.nz"),"Query Client method 21");
printResults(sClient.getQueueNamesForClusterAtSite("Canterbury",
"ng1.canterbury.ac.nz"), "SQL Client method 21");
printResults(
qClient.getQueueNamesForCodeAtSite("Canterbury", "Java"),
"Query Client method 22");
printResults(
sClient.getQueueNamesForCodeAtSite("Canterbury", "Java"),
"SQL Client method 22");
printResults(qClient.getQueueNamesForCodeAtSite("Canterbury",
"Java", "1.4.2"), "Query Client method 23");
printResults(sClient.getQueueNamesForCodeAtSite("Canterbury",
"Java", "1.4.2"), "SQL Client method 23");
printResults(
new String[] { qClient.getSiteForHost("cognac.ivec.org") },
"Query Client method 24");
printResults(
new String[] { sClient.getSiteForHost("cognac.ivec.org") },
"SQL Client method 24");
printResults(qClient.getSitesOnGrid(), "Query Client method 25");
printResults(sClient.getSitesOnGrid(), "SQL Client method 25");
printResults(qClient.getSitesWithAVersionOfACode("Java", "1.6"),
"Query Client method 26");
printResults(sClient.getSitesWithAVersionOfACode("Java", "1.6"),
"SQL Client method 26");
printResults(qClient.getSitesWithCode("Java"),
"Query Client method 27");
printResults(sClient.getSitesWithCode("Java"),
"SQL Client method 27");
printResults(
new String[] { qClient
.getStorageElementForGridFTPServer("gsiftp://ng2.esscc.uq.edu.au:2811") },
"Query Client method 28");
printResults(
new String[] { sClient
.getStorageElementForGridFTPServer("gsiftp://ng2.esscc.uq.edu.au:2811") },
"SQL Client method 28");
printResults(qClient.getStorageElementsForSite("HPSC"),
"Query Client method 29");
printResults(sClient.getStorageElementsForSite("HPSC"),
"SQL Client method 29");
printResults(qClient.getVersionsOfCodeAtSite("Auckland", "Java"),
"Query Client method 30");
printResults(sClient.getVersionsOfCodeAtSite("Auckland", "Java"),
"SQL Client method 30");
printResults(
qClient.getVersionsOfCodeForQueueAndContactString(
"grid_aix",
"https://ng2hpc.canterbury.ac.nz:8443/wsrf/services/ManagedJobFactoryService",
"Java"), "Query Client method 31");
printResults(
sClient.getVersionsOfCodeForQueueAndContactString(
"grid_aix",
"https://ng2hpc.canterbury.ac.nz:8443/wsrf/services/ManagedJobFactoryService",
"Java"), "SQL Client method 31");
printResults(qClient.getVersionsOfCodeOnGrid("beast"),
"Query Client method 32");
printResults(sClient.getVersionsOfCodeOnGrid("beast"),
"SQL Client method 32");
printResults(
new String[] { ""
+ qClient.isParallelAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"Query Client method 33");
printResults(
new String[] { ""
+ sClient.isParallelAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"SQL Client method 33");
// and this one is broken as well so it seems...
printResults(
new String[] { ""
+ qClient.isSerialAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"Query Client method 34");
printResults(
new String[] { ""
+ sClient.isSerialAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"SQL Client method 34");
printResults(qClient.getSitesForVO("/ARCS/BeSTGRID"),
"Query Client method 35");
printResults(sClient.getSitesForVO("/ARCS/BeSTGRID"),
"SQL Client method 35");
Map<String, String[]> data = sClient
.calculateDataLocationsForVO("/ARCS/BeSTGRID");
for (String key : data.keySet()) {
System.out.println("key is : " + key);
String[] values = data.get(key);
for (String value : values) {
System.out.println(value);
}
}
printResults(qClient.getGridFTPServersForQueueAtSite("Canterbury",
"gt5test"), "qclient getGridFTPServersForQueueAtSite");
printResults(sClient.getGridFTPServersForQueueAtSite("Canterbury",
"gt5test"), "sclient getGridFTPServersForQueueAtSite");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-bestgrid", "/ARCS/BeSTGRID"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-bestgrid /ARCS/BeSTGRID");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/yhal003", "/ARCS/BeSTGRID/Local"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/yhal003 /ARCS/BeSTGRID/Local");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-sbs", "/ARCS/BeSTGRID/Drug_discovery/SBS-Structural_Biology"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-sbs /ARCS/BeSTGRID/Drug_discovery/SBS-Structural_Biology");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-acsrc", "/ARCS/BeSTGRID/Drug_discovery/ACSRC"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-acsrc /ARCS/BeSTGRID/Drug_discovery/ACSRC");
Map<JobSubmissionProperty,String> jobProperties = new HashMap<JobSubmissionProperty,String>();
jobProperties.put(JobSubmissionProperty.APPLICATIONNAME,"mech-uoa");
//jobProperties.put(JobSubmissionProperty.APPLICATIONVERSION, "1.5");
//jobProperties.put(JobSubmissionProperty.NO_CPUS, "1");
resources = sClient.findAllResourcesM(jobProperties, "/nz/NeSI",false);
for (GridResource r: resources){
System.out.println(r.getQueueName());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void printResults(String[] results, String label) {
System.out.println(label);
for (String result : results) {
System.out.println(result);
}
}
private static void printResults(boolean result, String label){
printResults( new String[] {new Boolean(result).toString()},label);
}
private Connection con;
private String databaseUrl, user, password;
public SQLQueryClient(Connection con) {
this.con = con;
}
public SQLQueryClient(String databaseUrl, String user, String password) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.databaseUrl = databaseUrl;
this.user = user;
this.password = password;
this.con = DriverManager.getConnection(databaseUrl, user, password);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public Map<String, String[]> calculateDataLocationsForVO(String fqan) {
// getDataDir(String site, String storageElement, String FQAN)
HashMap<String, String[]> map = new HashMap<String, String[]>();
String query = "select sa.path,ap.endpoint from StorageElements se,StorageAreas sa,AccessProtocols ap, storageAreaACLs sacls "
+ " WHERE ap.storageElement_id = se.id AND sa.storageElement_id = se.id AND sacls.storageArea_id = sa.id and sacls.vo =?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
String[][] results = runQuery(s, "path", "endpoint");
String[] paths = results[0];
String[] endpoints = results[1];
for (int i = 0; i < endpoints.length; i++) {
map.put(endpoints[i], new String[] { paths[i] });
}
return map;
}
public List<GridResource> findAllResourcesM(
Map<JobSubmissionProperty, String> jobProperties, String fqan,
boolean exclude) {
List<GridResource> results = new LinkedList<GridResource>();
String query = "SELECT acls.vo fqan, contactString, gramVersion," +
" jobManager, ce.name queue, maxWalltime, v.freeJobSlots, " +
"v.runningJobs, v.waitingJobs, v.totalJobs, s.name site, " +
"lattitude, longitude, sp.name sname ,sp.version sversion" +
" FROM" +
" Sites s, SubClusters sc, Clusters c, ComputeElements ce, voViews v, " +
"voViewACLs acls, SoftwarePackages sp " +
"WHERE " +
"acls.voView_id = v.id and ce.cluster_id =c.id and " +
"c.site_id = s.id and c.id = sc.cluster_id and " +
"v.ce_id = ce.id and sp.subcluster_id = sc.id and acls.vo=?";
int wallTimeRequirement = -1;
try {
wallTimeRequirement = Integer.parseInt(jobProperties
.get(JobSubmissionProperty.WALLTIME_IN_MINUTES));
} catch (Exception e) {
}
int totalCPURequirement = -1;
try {
totalCPURequirement = Integer.parseInt(jobProperties
.get(JobSubmissionProperty.NO_CPUS));
} catch (Exception e) {
}
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
String[][] resources = runQuery(s, new String[] { "queue",
"contactString", "gramVersion", "jobManager", "freeJobSlots",
"runningJobs", "waitingJobs", "totalJobs", "site", "lattitude",
"longitude", "maxWalltime","sname","sversion" });
for (String[] resource : resources) {
// check if application name matches
String applicationName = jobProperties.get(JobSubmissionProperty.APPLICATIONNAME);
if (StringUtils.isNotBlank(applicationName)
&& !Constants.GENERIC_APPLICATION_NAME
.equals(applicationName)
&& !resource[12].equals(applicationName)) {
continue;
}
// check if application version matches
String applicationVersion = jobProperties.get(JobSubmissionProperty.APPLICATIONVERSION);
if (StringUtils.isNotBlank(applicationVersion)
&& !Constants.NO_VERSION_INDICATOR_STRING.equals(applicationVersion)
&& !resource[13].equals(applicationVersion)){
continue;
}
GridResourceBackendImpl gr = new GridResourceBackendImpl();
gr.setQueueName(resource[0]);
gr.setContactString(resource[1]);
gr.setGRAMVersion(resource[2]);
gr.setJobManager(resource[3]);
gr.setFreeJobSlots(Integer.parseInt(resource[4]));
int maxWalltime = Integer.parseInt(resource[11]);
if (exclude
&& ((gr.getFreeJobSlots() < totalCPURequirement) || (maxWalltime < wallTimeRequirement))) {
continue;
}
gr.setRunningJobs(Integer.parseInt(resource[5]));
gr.setWaitingJobs(Integer.parseInt(resource[6]));
gr.setTotalJobs(Integer.parseInt(resource[7]));
gr.setSiteName(resource[8]);
gr.setSiteLatitude(Double.parseDouble(resource[9]));
gr.setSiteLongitude(Double.parseDouble(resource[10]));
gr.setApplicationName(applicationName);
gr.addAvailableApplicationVersion(applicationVersion);
String[] exes = getExecutables(gr.getSiteName(),gr.getQueueName(),applicationName,applicationVersion);
Set<String> executables = new HashSet<String>();
for (String exe : exes) {
executables.add(exe);
}
if (executables.size() == 0){
executables.add(Constants.GENERIC_APPLICATION_NAME);
}
gr.setAllExecutables(executables);
results.add(gr);
}
return results;
}
private String[] getExecutables(String siteName, String queue, String appName, String appVersion){
if (appName == null && appVersion == null){
return new String[] {};
}
String query = "select exe.name exeName from Sites s, Clusters c,SubClusters sc"
+ ",ComputeElements ce, SoftwarePackages sp, SoftwareExecutables exe "
+ "where s.id = c.site_id and c.id= sc.cluster_id and sp.subcluster_id = sc.id "
+ "and exe.package_id = sp.id AND ce.cluster_id = c.id AND "
+ "s.name =? and ce.name =? AND (sp.name=? OR ? = ?) AND (sp.version=? OR ? = ?)";
PreparedStatement s = getStatement(query);
setString(s, 1, siteName);
setString(s, 2,queue);
setString(s, 3, appName);
setString(s, 4, appName);
setString(s, 5, Constants.GENERIC_APPLICATION_NAME);
setString(s, 6, appVersion);
setString(s, 7, appVersion);
setString(s, 8, Constants.NO_VERSION_INDICATOR_STRING);
return runQuery(s, "exeName");
}
public Map<String, String> getAllComputeHosts() {
Map<String, String> results = new HashMap<String, String>();
String query = "select DISTINCT s.name as site, "
+ " SUBSTRING_INDEX(TRIM(LEADING 'https://' FROM ce.contactString),':',1) hostname "
+ "FROM Sites s ,Clusters c,ComputeElements ce WHERE s.id = c.site_id and c.id = ce.cluster_id;";
PreparedStatement s = getStatement(query);
String[][] hostnames = runQuery(s, new String[] { "site", "hostname" });
for (String[] hostname : hostnames) {
results.put(hostname[1], hostname[0]);
}
return results;
}
public Map<String, String> getAllDataHosts() {
Map<String, String> results = new HashMap<String, String>();
String query = "SELECT DISTINCT s.name as site,"
+ "SUBSTRING_INDEX(TRIM(LEADING 'gsiftp://' FROM endpoint),':',1) as hostname "
+ "FROM Sites s,StorageElements se,StorageAreas sa, AccessProtocols p "
+ "WHERE s.id = se.site_id AND se.id = sa.storageElement_ID AND se.id=p.storageElement_ID";
PreparedStatement s = getStatement(query);
String[][] hostnames = runQuery(s, new String[] { "site", "hostname" });
for (String[] hostname : hostnames) {
results.put(hostname[1], hostname[0]);
}
return results;
}
// only partially implemented
public GridResource[] getAllGridResources() {
String query = "select contactString,gramVersion,jobManager,ce.name,"
+ "freeJobSlots,runningJobs,waitingJobs,totalJobs,s.name,"
+ "lattitude,longitude "
+ "from Sites s,Clusters c ,ComputeElements ce where "
+ "ce.cluster_id = c.id and c.site_id = s.id";
PreparedStatement s = getStatement(query);
String[][] results = runQuery(s, new String[] { "contactString",
"gramVersion", "jobManager", "ce.name", "freeJobSlots",
"runningJobs", "waitingJobs", "totalJobs", "s.name",
"lattitude", "longitude" });
GridResource[] grs = new GridResource[results.length];
for (int i = 0; i < results.length; i++) {
GridResourceBackendImpl gr = new GridResourceBackendImpl();
gr.setContactString(results[i][0]);
gr.setGRAMVersion(results[i][1]);
gr.setJobManager(results[i][2]);
gr.setQueueName(results[i][3]);
grs[i] = gr;
}
return grs;
}
public String[] getApplicationNamesThatProvideExecutable(String executable) {
String query = "SELECT DISTINCT BINARY sp.name as name FROM SoftwareExecutables AS "
+ " se,SoftwarePackages AS sp WHERE se.package_id = sp.id AND "
+ " se.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, executable);
return runQuery(s, "name");
}
public String[] getClusterNamesAtSite(String site) {
String query = "SELECT c.name as name FROM Sites AS s ,Clusters AS c WHERE s.id = c.site_id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getClustersForCodeAtSite(String site, String code,
String version) {
String query = " SELECT c.uniqueID FROM Sites AS s ,Clusters AS c, SubClusters AS "
+ " sc,SoftwarePackages as p where s.id = c.site_id AND sc.cluster_id = c.id "
+ " AND p.subcluster_id = sc.id AND s.name=? AND "
+ " p.name=? AND p.version = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "uniqueID");
}
public String[] getCodesAtSite(String site) {
String query = "SELECT DISTINCT p.name FROM Sites AS s ,Clusters AS c, SubClusters AS "
+ " sc,SoftwarePackages AS p WHERE s.id = c.site_id AND sc.cluster_id = "
+ " c.id AND s.name=? AND p.subcluster_id = sc.id;";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getCodesOnGrid() {
String query = "SELECT DISTINCT BINARY name AS NAME FROM SoftwarePackages";
PreparedStatement s = getStatement(query);
return runQuery(s, "name");
}
public String[] getCodesOnGridForVO(String fqan) {
- String query = "select distinct binary sp.name from SubClusters sc, ComputeElements ce, voViews v, voViewACLs acls, SoftwarePackages sp"
+ String query = "select distinct binary sp.name as name from SubClusters sc, ComputeElements ce, voViews v, voViewACLs acls, SoftwarePackages sp"
+ " WHERE sc.cluster_id = ce.cluster_id AND v.ce_id = ce.id "
+ "AND acls.voView_id = v.id AND sp.subcluster_id = sc.id AND acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "name");
}
public String[] getContactStringOfQueueAtSite(String site, String queue) {
String query = " SELECT contactString FROM ComputeElements ce,Clusters c,Sites s WHERE "
+ "c.site_id = s.id AND ce.cluster_id = c.id AND s.name = ? AND ce.name =? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "contactString");
}
public String[] getDataDir(String site, String storageElement, String FQAN) {
String query = " SELECT StorageAreas.path FROM "
+ " Sites,StorageElements,StorageAreas,storageAreaACLs WHERE "
+ " Sites.id=StorageElements.site_id AND StorageElements.id = "
+ " StorageAreas.storageElement_id AND StorageAreas.id = "
+ " storageAreaACLs.storageArea_id AND Sites.name=? "
+ "AND vo=? AND StorageElements.uniqueID =?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 3, storageElement);
setString(s, 2, FQAN);
return runQuery(s, "path");
}
public String getDefaultStorageElementForQueueAtSite(String site,
String queue) {
String query = "SELECT se.uniqueID FROM Sites AS s,StorageElements AS "
+ " se,ComputeElements AS ce WHERE s.id = se.site_id AND s.id = se.site_id "
+ " AND ce.defaultSE_id = se.id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
String[] elements = runQuery(s, "uniqueID");
if ((elements == null) || (elements.length == 0)) {
return null;
} else {
return elements[0];
}
}
public String[] getExeNameOfCodeAtSite(String site, String code,
String version) {
String query = "SELECT exec.name FROM Sites AS s ,Clusters AS c,SubClusters AS "
+ " sc,SoftwarePackages AS sp,SoftwareExecutables AS exec WHERE s.id = "
+ " c.site_id AND c.id = sc.cluster_id AND sc.id = sp.subcluster_id AND "
+ " exec.package_id = sp.id AND s.name=? AND "
+ " sp.name=? AND sp.version=? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "name");
}
public String[] getExeNameOfCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "SELECT exec.name FROM Sites AS s ,ComputeElements AS ce,Clusters AS "
+ " c ,SubClusters AS sc,SoftwarePackages AS sp,SoftwareExecutables AS "
+ " exec WHERE c.id = ce.cluster_id AND s.id = c.site_id AND c.id = "
+ " sc.cluster_id AND sc.id = sp.subcluster_id AND exec.package_id = "
+ " sp.id AND ce.name=? AND "
+ " ce.hostname=? AND sp.name=? AND sp.version=?";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, queue);
setString(s, 2, hostname);
setString(s, 3, code);
setString(s, 4, version);
return runQuery(s, "name");
}
public String[] getGridFTPServersAtSite(String site) {
String query = "SELECT DISTINCT endpoint FROM Sites AS s ,StorageElements AS "
+ " se,StorageAreas AS sa, AccessProtocols AS p WHERE s.id = se.site_id "
+ " AND se.id = sa.storageElement_ID AND se.id=p.storageElement_ID AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersForQueueAtSite(String site, String queue) {
String query = "SELECT DISTINCT endpoint FROM Sites s ,Clusters c,StorageElements "
+ " se,StorageAreas sa, AccessProtocols p,ComputeElements ce "
+ " WHERE s.id = se.site_id AND s.id = c.site_id AND ce.cluster_id = c.id AND se.id = "
+ "sa.storageElement_ID AND ce.defaultSE_id = se.id AND se.id=p.storageElement_ID AND "
+ " s.name=? AND ce.name = ? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersForStorageElementAtSite(String site,
String storageElement) {
String query = "select distinct endpoint from Sites s, Clusters c ,StorageElements "
+ " se,StorageAreas sa, AccessProtocols p,ComputeElements ce "
+ " WHERE s.id = se.site_id AND s.id = c.site_id AND c.id = ce.cluster_id AND se.id = "
+ " sa.storageElement_ID AND se.id=p.storageElement_ID AND "
+ " s.name=? AND se.uniqueID =?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, storageElement);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersOnGrid() {
String query = "select AccessProtocols.endpoint from StorageElements,AccessProtocols "
+ " where StorageElements.id = AccessProtocols.storageElement_id";
PreparedStatement s = getStatement(query);
return runQuery(s, "endpoint");
}
public String getJobManagerOfQueueAtSite(String site, String queue) {
String query = "select ce.jobManager from Sites s,Clusters c,ComputeElements ce WHERE s.id "
+ " = c.site_id AND c.id = ce.cluster_id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "jobManager")[0];
}
// not sure what this means
public String getJobTypeOfCodeAtSite(String site, String code,
String version) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getLRMSTypeOfQueueAtSite(String site, String queue) {
String query = "SELECT ce.lRMSType FROM Sites s,Clusters c,ComputeElements ce WHERE s.id = "
+ " c.site_id AND c.id = ce.cluster_id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "lRMSType")[0];
}
public String getModuleNameOfCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "SELECT sp.module FROM Sites AS s ,ComputeElements AS ce,Clusters AS "
+ " c ,SubClusters AS sc,SoftwarePackages AS sp "
+ " WHERE s.id = c.site_id AND c.id = ce.cluster_id AND c.id = "
+ " sc.cluster_id AND sc.id = sp.subcluster_id AND ce.name=? AND "
+ " ce.hostname=? AND sp.name=? AND sp.version=?";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, queue);
setString(s, 2, hostname);
setString(s, 3, code);
setString(s, 4, version);
String[] module = runQuery(s, "module");
if ((module == null) || (module.length == 0)) {
return null;
} else {
return module[0];
}
}
public String[] getQueueNamesAtSite(String site) {
String query = " SELECT ce.name FROM Sites s,Clusters c "
+ ",ComputeElements ce WHERE s.id = c.site_id AND c.id = ce.cluster_id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getQueueNamesAtSite(String site, String fqan) {
String query = "select ce.name from voViews v,Sites s,Clusters c,ComputeElements ce,voViewACLs "
+ " acls where s.id = c.site_id and c.id = ce.cluster_id and v.ce_id=ce.id AND v.id = "
+ " acls.voView_id AND s.name=? and vo = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, fqan);
return runQuery(s, "name");
}
public String[] getQueueNamesForClusterAtSite(String site, String cluster) {
String query = "select ce.name from Sites s,ComputeElements ce,Clusters as c where "
+ "s.id = c.site_id and c.id = ce.cluster_id AND s.name=? and c.name = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, cluster);
return runQuery(s, "name");
}
public String[] getQueueNamesForCodeAtSite(String site, String code) {
String query = "select ce.name from Sites as s ,ComputeElements as ce,Clusters as "
+ " c,SubClusters as sc,SoftwarePackages as sp WHERE s.id = c.site_id AND "
+ " c.id = ce.cluster_id AND c.id = sc.cluster_id AND sc.id = "
+ " sp.subcluster_id AND s.name=? AND sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
return runQuery(s, "name");
}
public String[] getQueueNamesForCodeAtSite(String site, String code,
String version) {
String query = "select ce.name from Sites as s ,ComputeElements as ce,Clusters as "
+ " c,SubClusters as sc,SoftwarePackages as sp WHERE s.id = c.site_id AND "
+ " c.id = ce.cluster_id AND c.id = sc.cluster_id AND sc.id = "
+ " sp.subcluster_id AND s.name=? AND sp.name=? AND sp.version=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "name");
}
public String getSiteForHost(String host) {
String query = "SELECT DISTINCT s.name from Sites s, Clusters c, ComputeElements ce where s.id "
+ " = c.site_id AND c.id = ce.cluster_id and ce.hostname=?";
PreparedStatement s = getStatement(query);
setString(s, 1, host);
String[] sites = runQuery(s, "name");
if ((sites == null) || (sites.length == 0)) {
return null;
} else {
return sites[0];
}
}
public String[] getSitesForVO(String fqan) {
String query = " select distinct s.name from Sites s,Clusters c, ComputeElements ce"
+ ",voViews v,voViewACLs acls WHERE s.id=c.site_id and c.id = ce.cluster_id "
+ "AND ce.id = v.ce_id and acls.voView_id=v.id AND acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "name");
}
public String[] getSitesOnGrid() {
String query = "select s.name from Sites s";
PreparedStatement s = getStatement(query);
return runQuery(s, "name");
}
public String[] getSitesWithAVersionOfACode(String code, String version) {
String query = "select distinct s.name from Sites s,Clusters c,SubClusters sc, "
+ " SoftwarePackages sp where s.id = c.site_id and c.id = sc.cluster_id "
+ " AND sp.subcluster_id = sc.id and sp.name=? and sp.version = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
return runQuery(s, "name");
}
public String[] getSitesWithCode(String code) {
String query = "select distinct s.name from Sites s,Clusters c,SubClusters sc, "
+ " SoftwarePackages sp where s.id = c.site_id and c.id = sc.cluster_id "
+ " AND sp.subcluster_id = sc.id and sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
return runQuery(s, "name");
}
private PreparedStatement getStatement(String query) {
try {
if (!con.isValid(1)) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(this.databaseUrl, this.user,
this.password);
}
PreparedStatement s = con.prepareStatement(query);
return s;
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public String getStorageElementForGridFTPServer(String gridFtp) {
String query = "select se.uniqueID from StorageElements se, AccessProtocols p WHERE "
+ " p.storageElement_id=se.id AND endpoint=?";
PreparedStatement s = getStatement(query);
setString(s, 1, gridFtp);
String[] ses = runQuery(s, "uniqueID");
if ((ses == null) || (ses.length == 0)) {
return null;
} else {
return ses[0];
}
}
public String[] getStorageElementsForSite(String site) {
String query = "select se.uniqueID from Sites s,StorageElements se WHERE se.site_id=s.id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "uniqueID");
}
public String[] getStorageElementsForVO(String fqan) {
String query = "select distinct se.uniqueID from Sites s, StorageElements se,"
+ "StorageAreas sa, storageAreaACLs sacls WHERE s.id = se.site_id and sa."
+ "storageElement_id = se.id AND sacls.storageArea_id = sa.id and sacls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "uniqueID");
}
private String getSubmissionHostName(String submissionLocation) {
int dot = submissionLocation.indexOf(":") + 1;
return submissionLocation.substring(dot);
}
private String getSubmissionQueue(String submissionLocation) {
int dot = submissionLocation.indexOf(":");
if (dot == -1) {
return "";
}
return submissionLocation.substring(0, dot);
}
public String[] getVersionsOfCodeAtSite(String site, String code) {
String query = "SELECT DISTINCT sp.version FROM Sites s,Clusters c,SubClusters "
+ " sc,SoftwarePackages sp WHERE s.id = c.site_id AND c.id = sc.cluster_id "
+ " AND sc.id = sp.subcluster_id AND s.name=? AND sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeForQueueAndContactString(String queueName,
String hostName, String code) {
String query = "select distinct sp.version from Clusters c,ComputeElements "
+ " ce,SubClusters sc,SoftwarePackages sp WHERE c.id = ce.cluster_id AND "
+ " c.id = sc.cluster_id AND sc.id = sp.subcluster_id AND sp.name=? "
+ "AND ce.hostName=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, hostName);
setString(s, 3, queueName);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeOnGrid(String code) {
String query = "select distinct version from SoftwarePackages sp where sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeOnGridForVO(String code, String fqan) {
String query = "select distinct sp.version from Clusters c, SubClusters sc, SoftwarePackages sp,"
+ " ComputeElements ce, voViews v, voViewACLs acls WHERE c.id = sc.cluster_id AND c.id ="
+ " ce.cluster_id AND sp.subcluster_id = sc.id AND ce.id = v.ce_id AND acls.voView_id ="
+ " v.id AND sp.name =? and acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, fqan);
return runQuery(s, "version");
}
public boolean isParallelAvailForCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "select 1 from ComputeElements ce,SubClusters sc,SoftwarePackages "
+ " sp,SoftwareExecutables exec where ce.cluster_id = sc.cluster_id AND "
+ " sp.subcluster_id = sc.id AND exec.package_id = sp.id AND "
+ " sp.name=? AND sp.version=? AND "
+ " ce.hostname=? AND ce.name=? AND " + " isParallel=1";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
setString(s, 3, hostname);
setString(s, 4, queue);
String[] result = runQuery(s, "1");
return !((result == null) || (result.length == 0));
}
public boolean isSerialAvailForCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "select 1 from ComputeElements ce,SubClusters sc,SoftwarePackages "
+ " sp,SoftwareExecutables exec where ce.cluster_id = sc.cluster_id AND "
+ " sp.subcluster_id = sc.id AND exec.package_id = sp.id AND "
+ " sp.name=? AND sp.version=? AND "
+ " ce.hostname=? AND ce.name=? AND " + " isSerial=1";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
setString(s, 3, hostname);
setString(s, 4, queue);
String[] result = runQuery(s, "1");
return !((result == null) || (result.length == 0));
}
public boolean isVolatile(String endpoint, String path, String fqan){
PreparedStatement s;
Pattern complete = Pattern.compile("gsiftp://.+:[0-9]+");
Pattern portOnly = Pattern.compile(".+:[0-9]+");
Pattern protocolOnly = Pattern.compile("gsiftp://.+");
if (complete.matcher(endpoint).matches()) {
// do nothing, endpoint has valid value
}
else if (portOnly.matcher(endpoint).matches()){
endpoint = "gsiftp://" + endpoint;
}
else if (protocolOnly.matcher(endpoint).matches()){
endpoint += ":2811";
}
else {
endpoint = "gsiftp://" + endpoint + ":2811";
}
String query = "select sa.type from AccessProtocols ap, StorageElements s, StorageAreas sa" +
",storageAreaACLs acls WHERE sa.id = acls.storageArea_id AND s.id = sa.storageElement_id AND " +
"ap.storageElement_id = s.id AND acls.vo = ? AND ap.endPoint=? AND (sa.path = ? OR sa.path LIKE ?)";
s = getStatement(query);
setString(s,1,fqan);
setString(s,2,endpoint);
setString(s,3,path);
setString(s,4,path + "[%]");
String[] result = runQuery(s,"type");
if (result.length > 0 ){
return result[0].equals(VOLATILE);
}
query = "select sa.type from AccessProtocols ap, StorageElements s, StorageAreas sa" +
",storageAreaACLs acls WHERE sa.id = acls.storageArea_id AND s.id = sa.storageElement_id AND " +
"ap.storageElement_id = s.id AND acls.vo = ? AND ap.endPoint=? AND (sa.path = '${GLOBUS_USER_HOME}' or " +
" sa.path = '/~/' or sa.path LIKE '.%' )";
s = getStatement(query);
setString(s,1,fqan);
setString(s,2,endpoint);
result = runQuery(s,"type");
if (result.length > 0 ){
return result[0].equals(VOLATILE);
}
return true;
}
private String[] runQuery(PreparedStatement s, String output) {
try {
myLogger.debug(s.toString());
HashSet<String> resultSet = new HashSet<String>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
resultSet.add(rs.getString(output));
}
return resultSet.toArray(new String[] {});
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private String[][] runQuery(PreparedStatement s, String output1,
String output2) {
try {
myLogger.debug(s.toString());
LinkedList<String> resultSet1 = new LinkedList<String>();
LinkedList<String> resultSet2 = new LinkedList<String>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
resultSet1.add(rs.getString(output1));
resultSet2.add(rs.getString(output2));
}
return new String[][] { resultSet1.toArray(new String[] {}),
resultSet2.toArray(new String[] {}) };
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private String[][] runQuery(PreparedStatement s, String[] outputs) {
try {
myLogger.debug(s.toString());
LinkedList<String[]> resultSet = new LinkedList<String[]>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
String[] outputValues = new String[outputs.length];
for (int i = 0; i < outputs.length; i++) {
outputValues[i] = rs.getString(outputs[i]);
}
resultSet.add(outputValues);
}
return resultSet.toArray(new String[][] {});
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private void setString(PreparedStatement s, int i, String string) {
try {
s.setString(i, string);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
| true | true | public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://mysql-bg.ceres.auckland.ac.nz/mds_test",
"grisu_read", "password");
QueryClient qClient = new QueryClient("/tmp");
SQLQueryClient sClient = new SQLQueryClient(con);
HashMap<JobSubmissionProperty, String> props = new HashMap<JobSubmissionProperty, String>();
props.put(JobSubmissionProperty.APPLICATIONNAME, Constants.GENERIC_APPLICATION_NAME);
props.put(JobSubmissionProperty.APPLICATIONVERSION, Constants.NO_VERSION_INDICATOR_STRING);
props.put(JobSubmissionProperty.WALLTIME_IN_MINUTES, "4000");
System.out.println("Check R...");
List<GridResource> resources = sClient.findAllResourcesM(props,
"/ARCS/Monash", true);
for (GridResource r : resources) {
System.out.println("R site: " + r.getSiteName());
}
printResults(
qClient.getApplicationNamesThatProvideExecutable("javac"),
"Query Client method 1");
printResults(
sClient.getApplicationNamesThatProvideExecutable("javac"),
"SQL Client method 1");
// appears broken
// printResults(qClient.getClusterNamesAtSite("canterbury.ac.nz"),"Query Client method 2");
printResults(sClient.getClusterNamesAtSite("Canterbury"),
"SQL Client method 2");
// broken too, maybe...
// printResults(qClient.getClustersForCodeAtSite("canterbury.ac.nz","Java","1.4.2"),"Query Client method 3");
printResults(sClient.getClustersForCodeAtSite("Canterbury", "Java",
"1.4.2"), "SQL Client method 3");
printResults(qClient.getCodesAtSite("Canterbury"),
"Query Client method 4");
printResults(sClient.getCodesAtSite("Canterbury"),
"SQL Client method 4");
printResults(qClient.getCodesOnGrid(), "Query Client method 5");
printResults(sClient.getCodesOnGrid(), "SQL Client method 5");
printResults(qClient.getContactStringOfQueueAtSite("eRSA",
"hydra@hydra"), "Query Client method 6");
printResults(sClient.getContactStringOfQueueAtSite("eRSA",
"hydra@hydra"), "SQL Client method 6");
printResults(qClient.getDataDir("Auckland", "ng2.auckland.ac.nz",
"/ARCS/BeSTGRID"), "Query Client method 7");
printResults(sClient.getDataDir("Auckland", "ng2.auckland.ac.nz",
"/ARCS/BeSTGRID"), "SQL Client method 7");
printResults(
new String[] { qClient.getDefaultStorageElementForQueueAtSite(
"Canterbury", "grid_aix") },
"Query Client method 8");
printResults(
new String[] { sClient.getDefaultStorageElementForQueueAtSite(
"Canterbury", "grid_aix") }, "SQL Client method 8");
printResults(
qClient.getExeNameOfCodeAtSite("Auckland", "Java", "1.6"),
"Query Client method 9");
printResults(
sClient.getExeNameOfCodeAtSite("Auckland", "Java", "1.6"),
"SQL Client method 9");
printResults(qClient.getExeNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6"), "Query Client method 10");
printResults(sClient.getExeNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6"), "SQL Client method 10");
printResults(qClient.getGridFTPServersAtSite("Auckland"),
"Query Client method 11");
printResults(sClient.getGridFTPServersAtSite("Auckland"),
"SQL Client method 11");
printResults(qClient.getGridFTPServersForQueueAtSite("Auckland",
"[email protected]"),
"Query Client method 12");
printResults(sClient.getGridFTPServersForQueueAtSite("Auckland",
"[email protected]"),
"SQL Client method 12");
printResults(qClient.getGridFTPServersForStorageElementAtSite(
"Auckland", "ngdata.ceres.auckland.ac.nz"),
"Query Client method 13");
printResults(sClient.getGridFTPServersForStorageElementAtSite(
"Auckland", "ngdata.ceres.auckland.ac.nz"),
"SQL Client method 13");
// also broken
// printResults(qClient.getGridFTPServersOnGrid(),"Query Client method 14");
printResults(sClient.getGridFTPServersOnGrid(),
"SQL Client method 14");
printResults(new String[] { qClient.getJobManagerOfQueueAtSite(
"Auckland", "[email protected]") },
"Query Client method 15");
printResults(new String[] { sClient.getJobManagerOfQueueAtSite(
"Auckland", "[email protected]") },
"SQL Client method 15");
// not sure what we are supposed to do here
// System.out.println(qClient.getJobTypeOfCodeAtSite("Auckland",
// "Java", "1.6"));
printResults(new String[] { qClient.getLRMSTypeOfQueueAtSite(
"Auckland", "[email protected]") },
"Query Client method 17");
printResults(new String[] { sClient.getLRMSTypeOfQueueAtSite(
"Auckland", "[email protected]") },
"SQL Client method 17");
printResults(
new String[] { qClient
.getModuleNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6") }, "Query Client method 18");
printResults(
new String[] { sClient
.getModuleNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6") }, "SQL Client method 18");
printResults(qClient.getQueueNamesAtSite("Canterbury"),
"Query Client method 19");
printResults(sClient.getQueueNamesAtSite("Canterbury"),
"SQL Client method 19");
printResults(
qClient.getQueueNamesAtSite("Canterbury", "/ARCS/NGAdmin"),
"Query Client method 20");
printResults(
sClient.getQueueNamesAtSite("Canterbury", "/ARCS/NGAdmin"),
"SQL Client method 20");
// broken too!
// printResults(qClient.getQueueNamesForClusterAtSite("Canterbury","ng1.canterbury.ac.nz"),"Query Client method 21");
printResults(sClient.getQueueNamesForClusterAtSite("Canterbury",
"ng1.canterbury.ac.nz"), "SQL Client method 21");
printResults(
qClient.getQueueNamesForCodeAtSite("Canterbury", "Java"),
"Query Client method 22");
printResults(
sClient.getQueueNamesForCodeAtSite("Canterbury", "Java"),
"SQL Client method 22");
printResults(qClient.getQueueNamesForCodeAtSite("Canterbury",
"Java", "1.4.2"), "Query Client method 23");
printResults(sClient.getQueueNamesForCodeAtSite("Canterbury",
"Java", "1.4.2"), "SQL Client method 23");
printResults(
new String[] { qClient.getSiteForHost("cognac.ivec.org") },
"Query Client method 24");
printResults(
new String[] { sClient.getSiteForHost("cognac.ivec.org") },
"SQL Client method 24");
printResults(qClient.getSitesOnGrid(), "Query Client method 25");
printResults(sClient.getSitesOnGrid(), "SQL Client method 25");
printResults(qClient.getSitesWithAVersionOfACode("Java", "1.6"),
"Query Client method 26");
printResults(sClient.getSitesWithAVersionOfACode("Java", "1.6"),
"SQL Client method 26");
printResults(qClient.getSitesWithCode("Java"),
"Query Client method 27");
printResults(sClient.getSitesWithCode("Java"),
"SQL Client method 27");
printResults(
new String[] { qClient
.getStorageElementForGridFTPServer("gsiftp://ng2.esscc.uq.edu.au:2811") },
"Query Client method 28");
printResults(
new String[] { sClient
.getStorageElementForGridFTPServer("gsiftp://ng2.esscc.uq.edu.au:2811") },
"SQL Client method 28");
printResults(qClient.getStorageElementsForSite("HPSC"),
"Query Client method 29");
printResults(sClient.getStorageElementsForSite("HPSC"),
"SQL Client method 29");
printResults(qClient.getVersionsOfCodeAtSite("Auckland", "Java"),
"Query Client method 30");
printResults(sClient.getVersionsOfCodeAtSite("Auckland", "Java"),
"SQL Client method 30");
printResults(
qClient.getVersionsOfCodeForQueueAndContactString(
"grid_aix",
"https://ng2hpc.canterbury.ac.nz:8443/wsrf/services/ManagedJobFactoryService",
"Java"), "Query Client method 31");
printResults(
sClient.getVersionsOfCodeForQueueAndContactString(
"grid_aix",
"https://ng2hpc.canterbury.ac.nz:8443/wsrf/services/ManagedJobFactoryService",
"Java"), "SQL Client method 31");
printResults(qClient.getVersionsOfCodeOnGrid("beast"),
"Query Client method 32");
printResults(sClient.getVersionsOfCodeOnGrid("beast"),
"SQL Client method 32");
printResults(
new String[] { ""
+ qClient.isParallelAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"Query Client method 33");
printResults(
new String[] { ""
+ sClient.isParallelAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"SQL Client method 33");
// and this one is broken as well so it seems...
printResults(
new String[] { ""
+ qClient.isSerialAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"Query Client method 34");
printResults(
new String[] { ""
+ sClient.isSerialAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"SQL Client method 34");
printResults(qClient.getSitesForVO("/ARCS/BeSTGRID"),
"Query Client method 35");
printResults(sClient.getSitesForVO("/ARCS/BeSTGRID"),
"SQL Client method 35");
Map<String, String[]> data = sClient
.calculateDataLocationsForVO("/ARCS/BeSTGRID");
for (String key : data.keySet()) {
System.out.println("key is : " + key);
String[] values = data.get(key);
for (String value : values) {
System.out.println(value);
}
}
printResults(qClient.getGridFTPServersForQueueAtSite("Canterbury",
"gt5test"), "qclient getGridFTPServersForQueueAtSite");
printResults(sClient.getGridFTPServersForQueueAtSite("Canterbury",
"gt5test"), "sclient getGridFTPServersForQueueAtSite");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-bestgrid", "/ARCS/BeSTGRID"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-bestgrid /ARCS/BeSTGRID");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/yhal003", "/ARCS/BeSTGRID/Local"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/yhal003 /ARCS/BeSTGRID/Local");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-sbs", "/ARCS/BeSTGRID/Drug_discovery/SBS-Structural_Biology"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-sbs /ARCS/BeSTGRID/Drug_discovery/SBS-Structural_Biology");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-acsrc", "/ARCS/BeSTGRID/Drug_discovery/ACSRC"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-acsrc /ARCS/BeSTGRID/Drug_discovery/ACSRC");
Map<JobSubmissionProperty,String> jobProperties = new HashMap<JobSubmissionProperty,String>();
jobProperties.put(JobSubmissionProperty.APPLICATIONNAME,"mech-uoa");
//jobProperties.put(JobSubmissionProperty.APPLICATIONVERSION, "1.5");
//jobProperties.put(JobSubmissionProperty.NO_CPUS, "1");
resources = sClient.findAllResourcesM(jobProperties, "/nz/NeSI",false);
for (GridResource r: resources){
System.out.println(r.getQueueName());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void printResults(String[] results, String label) {
System.out.println(label);
for (String result : results) {
System.out.println(result);
}
}
private static void printResults(boolean result, String label){
printResults( new String[] {new Boolean(result).toString()},label);
}
private Connection con;
private String databaseUrl, user, password;
public SQLQueryClient(Connection con) {
this.con = con;
}
public SQLQueryClient(String databaseUrl, String user, String password) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.databaseUrl = databaseUrl;
this.user = user;
this.password = password;
this.con = DriverManager.getConnection(databaseUrl, user, password);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public Map<String, String[]> calculateDataLocationsForVO(String fqan) {
// getDataDir(String site, String storageElement, String FQAN)
HashMap<String, String[]> map = new HashMap<String, String[]>();
String query = "select sa.path,ap.endpoint from StorageElements se,StorageAreas sa,AccessProtocols ap, storageAreaACLs sacls "
+ " WHERE ap.storageElement_id = se.id AND sa.storageElement_id = se.id AND sacls.storageArea_id = sa.id and sacls.vo =?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
String[][] results = runQuery(s, "path", "endpoint");
String[] paths = results[0];
String[] endpoints = results[1];
for (int i = 0; i < endpoints.length; i++) {
map.put(endpoints[i], new String[] { paths[i] });
}
return map;
}
public List<GridResource> findAllResourcesM(
Map<JobSubmissionProperty, String> jobProperties, String fqan,
boolean exclude) {
List<GridResource> results = new LinkedList<GridResource>();
String query = "SELECT acls.vo fqan, contactString, gramVersion," +
" jobManager, ce.name queue, maxWalltime, v.freeJobSlots, " +
"v.runningJobs, v.waitingJobs, v.totalJobs, s.name site, " +
"lattitude, longitude, sp.name sname ,sp.version sversion" +
" FROM" +
" Sites s, SubClusters sc, Clusters c, ComputeElements ce, voViews v, " +
"voViewACLs acls, SoftwarePackages sp " +
"WHERE " +
"acls.voView_id = v.id and ce.cluster_id =c.id and " +
"c.site_id = s.id and c.id = sc.cluster_id and " +
"v.ce_id = ce.id and sp.subcluster_id = sc.id and acls.vo=?";
int wallTimeRequirement = -1;
try {
wallTimeRequirement = Integer.parseInt(jobProperties
.get(JobSubmissionProperty.WALLTIME_IN_MINUTES));
} catch (Exception e) {
}
int totalCPURequirement = -1;
try {
totalCPURequirement = Integer.parseInt(jobProperties
.get(JobSubmissionProperty.NO_CPUS));
} catch (Exception e) {
}
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
String[][] resources = runQuery(s, new String[] { "queue",
"contactString", "gramVersion", "jobManager", "freeJobSlots",
"runningJobs", "waitingJobs", "totalJobs", "site", "lattitude",
"longitude", "maxWalltime","sname","sversion" });
for (String[] resource : resources) {
// check if application name matches
String applicationName = jobProperties.get(JobSubmissionProperty.APPLICATIONNAME);
if (StringUtils.isNotBlank(applicationName)
&& !Constants.GENERIC_APPLICATION_NAME
.equals(applicationName)
&& !resource[12].equals(applicationName)) {
continue;
}
// check if application version matches
String applicationVersion = jobProperties.get(JobSubmissionProperty.APPLICATIONVERSION);
if (StringUtils.isNotBlank(applicationVersion)
&& !Constants.NO_VERSION_INDICATOR_STRING.equals(applicationVersion)
&& !resource[13].equals(applicationVersion)){
continue;
}
GridResourceBackendImpl gr = new GridResourceBackendImpl();
gr.setQueueName(resource[0]);
gr.setContactString(resource[1]);
gr.setGRAMVersion(resource[2]);
gr.setJobManager(resource[3]);
gr.setFreeJobSlots(Integer.parseInt(resource[4]));
int maxWalltime = Integer.parseInt(resource[11]);
if (exclude
&& ((gr.getFreeJobSlots() < totalCPURequirement) || (maxWalltime < wallTimeRequirement))) {
continue;
}
gr.setRunningJobs(Integer.parseInt(resource[5]));
gr.setWaitingJobs(Integer.parseInt(resource[6]));
gr.setTotalJobs(Integer.parseInt(resource[7]));
gr.setSiteName(resource[8]);
gr.setSiteLatitude(Double.parseDouble(resource[9]));
gr.setSiteLongitude(Double.parseDouble(resource[10]));
gr.setApplicationName(applicationName);
gr.addAvailableApplicationVersion(applicationVersion);
String[] exes = getExecutables(gr.getSiteName(),gr.getQueueName(),applicationName,applicationVersion);
Set<String> executables = new HashSet<String>();
for (String exe : exes) {
executables.add(exe);
}
if (executables.size() == 0){
executables.add(Constants.GENERIC_APPLICATION_NAME);
}
gr.setAllExecutables(executables);
results.add(gr);
}
return results;
}
private String[] getExecutables(String siteName, String queue, String appName, String appVersion){
if (appName == null && appVersion == null){
return new String[] {};
}
String query = "select exe.name exeName from Sites s, Clusters c,SubClusters sc"
+ ",ComputeElements ce, SoftwarePackages sp, SoftwareExecutables exe "
+ "where s.id = c.site_id and c.id= sc.cluster_id and sp.subcluster_id = sc.id "
+ "and exe.package_id = sp.id AND ce.cluster_id = c.id AND "
+ "s.name =? and ce.name =? AND (sp.name=? OR ? = ?) AND (sp.version=? OR ? = ?)";
PreparedStatement s = getStatement(query);
setString(s, 1, siteName);
setString(s, 2,queue);
setString(s, 3, appName);
setString(s, 4, appName);
setString(s, 5, Constants.GENERIC_APPLICATION_NAME);
setString(s, 6, appVersion);
setString(s, 7, appVersion);
setString(s, 8, Constants.NO_VERSION_INDICATOR_STRING);
return runQuery(s, "exeName");
}
public Map<String, String> getAllComputeHosts() {
Map<String, String> results = new HashMap<String, String>();
String query = "select DISTINCT s.name as site, "
+ " SUBSTRING_INDEX(TRIM(LEADING 'https://' FROM ce.contactString),':',1) hostname "
+ "FROM Sites s ,Clusters c,ComputeElements ce WHERE s.id = c.site_id and c.id = ce.cluster_id;";
PreparedStatement s = getStatement(query);
String[][] hostnames = runQuery(s, new String[] { "site", "hostname" });
for (String[] hostname : hostnames) {
results.put(hostname[1], hostname[0]);
}
return results;
}
public Map<String, String> getAllDataHosts() {
Map<String, String> results = new HashMap<String, String>();
String query = "SELECT DISTINCT s.name as site,"
+ "SUBSTRING_INDEX(TRIM(LEADING 'gsiftp://' FROM endpoint),':',1) as hostname "
+ "FROM Sites s,StorageElements se,StorageAreas sa, AccessProtocols p "
+ "WHERE s.id = se.site_id AND se.id = sa.storageElement_ID AND se.id=p.storageElement_ID";
PreparedStatement s = getStatement(query);
String[][] hostnames = runQuery(s, new String[] { "site", "hostname" });
for (String[] hostname : hostnames) {
results.put(hostname[1], hostname[0]);
}
return results;
}
// only partially implemented
public GridResource[] getAllGridResources() {
String query = "select contactString,gramVersion,jobManager,ce.name,"
+ "freeJobSlots,runningJobs,waitingJobs,totalJobs,s.name,"
+ "lattitude,longitude "
+ "from Sites s,Clusters c ,ComputeElements ce where "
+ "ce.cluster_id = c.id and c.site_id = s.id";
PreparedStatement s = getStatement(query);
String[][] results = runQuery(s, new String[] { "contactString",
"gramVersion", "jobManager", "ce.name", "freeJobSlots",
"runningJobs", "waitingJobs", "totalJobs", "s.name",
"lattitude", "longitude" });
GridResource[] grs = new GridResource[results.length];
for (int i = 0; i < results.length; i++) {
GridResourceBackendImpl gr = new GridResourceBackendImpl();
gr.setContactString(results[i][0]);
gr.setGRAMVersion(results[i][1]);
gr.setJobManager(results[i][2]);
gr.setQueueName(results[i][3]);
grs[i] = gr;
}
return grs;
}
public String[] getApplicationNamesThatProvideExecutable(String executable) {
String query = "SELECT DISTINCT BINARY sp.name as name FROM SoftwareExecutables AS "
+ " se,SoftwarePackages AS sp WHERE se.package_id = sp.id AND "
+ " se.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, executable);
return runQuery(s, "name");
}
public String[] getClusterNamesAtSite(String site) {
String query = "SELECT c.name as name FROM Sites AS s ,Clusters AS c WHERE s.id = c.site_id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getClustersForCodeAtSite(String site, String code,
String version) {
String query = " SELECT c.uniqueID FROM Sites AS s ,Clusters AS c, SubClusters AS "
+ " sc,SoftwarePackages as p where s.id = c.site_id AND sc.cluster_id = c.id "
+ " AND p.subcluster_id = sc.id AND s.name=? AND "
+ " p.name=? AND p.version = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "uniqueID");
}
public String[] getCodesAtSite(String site) {
String query = "SELECT DISTINCT p.name FROM Sites AS s ,Clusters AS c, SubClusters AS "
+ " sc,SoftwarePackages AS p WHERE s.id = c.site_id AND sc.cluster_id = "
+ " c.id AND s.name=? AND p.subcluster_id = sc.id;";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getCodesOnGrid() {
String query = "SELECT DISTINCT BINARY name AS NAME FROM SoftwarePackages";
PreparedStatement s = getStatement(query);
return runQuery(s, "name");
}
public String[] getCodesOnGridForVO(String fqan) {
String query = "select distinct binary sp.name from SubClusters sc, ComputeElements ce, voViews v, voViewACLs acls, SoftwarePackages sp"
+ " WHERE sc.cluster_id = ce.cluster_id AND v.ce_id = ce.id "
+ "AND acls.voView_id = v.id AND sp.subcluster_id = sc.id AND acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "name");
}
public String[] getContactStringOfQueueAtSite(String site, String queue) {
String query = " SELECT contactString FROM ComputeElements ce,Clusters c,Sites s WHERE "
+ "c.site_id = s.id AND ce.cluster_id = c.id AND s.name = ? AND ce.name =? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "contactString");
}
public String[] getDataDir(String site, String storageElement, String FQAN) {
String query = " SELECT StorageAreas.path FROM "
+ " Sites,StorageElements,StorageAreas,storageAreaACLs WHERE "
+ " Sites.id=StorageElements.site_id AND StorageElements.id = "
+ " StorageAreas.storageElement_id AND StorageAreas.id = "
+ " storageAreaACLs.storageArea_id AND Sites.name=? "
+ "AND vo=? AND StorageElements.uniqueID =?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 3, storageElement);
setString(s, 2, FQAN);
return runQuery(s, "path");
}
public String getDefaultStorageElementForQueueAtSite(String site,
String queue) {
String query = "SELECT se.uniqueID FROM Sites AS s,StorageElements AS "
+ " se,ComputeElements AS ce WHERE s.id = se.site_id AND s.id = se.site_id "
+ " AND ce.defaultSE_id = se.id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
String[] elements = runQuery(s, "uniqueID");
if ((elements == null) || (elements.length == 0)) {
return null;
} else {
return elements[0];
}
}
public String[] getExeNameOfCodeAtSite(String site, String code,
String version) {
String query = "SELECT exec.name FROM Sites AS s ,Clusters AS c,SubClusters AS "
+ " sc,SoftwarePackages AS sp,SoftwareExecutables AS exec WHERE s.id = "
+ " c.site_id AND c.id = sc.cluster_id AND sc.id = sp.subcluster_id AND "
+ " exec.package_id = sp.id AND s.name=? AND "
+ " sp.name=? AND sp.version=? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "name");
}
public String[] getExeNameOfCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "SELECT exec.name FROM Sites AS s ,ComputeElements AS ce,Clusters AS "
+ " c ,SubClusters AS sc,SoftwarePackages AS sp,SoftwareExecutables AS "
+ " exec WHERE c.id = ce.cluster_id AND s.id = c.site_id AND c.id = "
+ " sc.cluster_id AND sc.id = sp.subcluster_id AND exec.package_id = "
+ " sp.id AND ce.name=? AND "
+ " ce.hostname=? AND sp.name=? AND sp.version=?";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, queue);
setString(s, 2, hostname);
setString(s, 3, code);
setString(s, 4, version);
return runQuery(s, "name");
}
public String[] getGridFTPServersAtSite(String site) {
String query = "SELECT DISTINCT endpoint FROM Sites AS s ,StorageElements AS "
+ " se,StorageAreas AS sa, AccessProtocols AS p WHERE s.id = se.site_id "
+ " AND se.id = sa.storageElement_ID AND se.id=p.storageElement_ID AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersForQueueAtSite(String site, String queue) {
String query = "SELECT DISTINCT endpoint FROM Sites s ,Clusters c,StorageElements "
+ " se,StorageAreas sa, AccessProtocols p,ComputeElements ce "
+ " WHERE s.id = se.site_id AND s.id = c.site_id AND ce.cluster_id = c.id AND se.id = "
+ "sa.storageElement_ID AND ce.defaultSE_id = se.id AND se.id=p.storageElement_ID AND "
+ " s.name=? AND ce.name = ? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersForStorageElementAtSite(String site,
String storageElement) {
String query = "select distinct endpoint from Sites s, Clusters c ,StorageElements "
+ " se,StorageAreas sa, AccessProtocols p,ComputeElements ce "
+ " WHERE s.id = se.site_id AND s.id = c.site_id AND c.id = ce.cluster_id AND se.id = "
+ " sa.storageElement_ID AND se.id=p.storageElement_ID AND "
+ " s.name=? AND se.uniqueID =?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, storageElement);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersOnGrid() {
String query = "select AccessProtocols.endpoint from StorageElements,AccessProtocols "
+ " where StorageElements.id = AccessProtocols.storageElement_id";
PreparedStatement s = getStatement(query);
return runQuery(s, "endpoint");
}
public String getJobManagerOfQueueAtSite(String site, String queue) {
String query = "select ce.jobManager from Sites s,Clusters c,ComputeElements ce WHERE s.id "
+ " = c.site_id AND c.id = ce.cluster_id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "jobManager")[0];
}
// not sure what this means
public String getJobTypeOfCodeAtSite(String site, String code,
String version) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getLRMSTypeOfQueueAtSite(String site, String queue) {
String query = "SELECT ce.lRMSType FROM Sites s,Clusters c,ComputeElements ce WHERE s.id = "
+ " c.site_id AND c.id = ce.cluster_id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "lRMSType")[0];
}
public String getModuleNameOfCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "SELECT sp.module FROM Sites AS s ,ComputeElements AS ce,Clusters AS "
+ " c ,SubClusters AS sc,SoftwarePackages AS sp "
+ " WHERE s.id = c.site_id AND c.id = ce.cluster_id AND c.id = "
+ " sc.cluster_id AND sc.id = sp.subcluster_id AND ce.name=? AND "
+ " ce.hostname=? AND sp.name=? AND sp.version=?";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, queue);
setString(s, 2, hostname);
setString(s, 3, code);
setString(s, 4, version);
String[] module = runQuery(s, "module");
if ((module == null) || (module.length == 0)) {
return null;
} else {
return module[0];
}
}
public String[] getQueueNamesAtSite(String site) {
String query = " SELECT ce.name FROM Sites s,Clusters c "
+ ",ComputeElements ce WHERE s.id = c.site_id AND c.id = ce.cluster_id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getQueueNamesAtSite(String site, String fqan) {
String query = "select ce.name from voViews v,Sites s,Clusters c,ComputeElements ce,voViewACLs "
+ " acls where s.id = c.site_id and c.id = ce.cluster_id and v.ce_id=ce.id AND v.id = "
+ " acls.voView_id AND s.name=? and vo = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, fqan);
return runQuery(s, "name");
}
public String[] getQueueNamesForClusterAtSite(String site, String cluster) {
String query = "select ce.name from Sites s,ComputeElements ce,Clusters as c where "
+ "s.id = c.site_id and c.id = ce.cluster_id AND s.name=? and c.name = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, cluster);
return runQuery(s, "name");
}
public String[] getQueueNamesForCodeAtSite(String site, String code) {
String query = "select ce.name from Sites as s ,ComputeElements as ce,Clusters as "
+ " c,SubClusters as sc,SoftwarePackages as sp WHERE s.id = c.site_id AND "
+ " c.id = ce.cluster_id AND c.id = sc.cluster_id AND sc.id = "
+ " sp.subcluster_id AND s.name=? AND sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
return runQuery(s, "name");
}
public String[] getQueueNamesForCodeAtSite(String site, String code,
String version) {
String query = "select ce.name from Sites as s ,ComputeElements as ce,Clusters as "
+ " c,SubClusters as sc,SoftwarePackages as sp WHERE s.id = c.site_id AND "
+ " c.id = ce.cluster_id AND c.id = sc.cluster_id AND sc.id = "
+ " sp.subcluster_id AND s.name=? AND sp.name=? AND sp.version=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "name");
}
public String getSiteForHost(String host) {
String query = "SELECT DISTINCT s.name from Sites s, Clusters c, ComputeElements ce where s.id "
+ " = c.site_id AND c.id = ce.cluster_id and ce.hostname=?";
PreparedStatement s = getStatement(query);
setString(s, 1, host);
String[] sites = runQuery(s, "name");
if ((sites == null) || (sites.length == 0)) {
return null;
} else {
return sites[0];
}
}
public String[] getSitesForVO(String fqan) {
String query = " select distinct s.name from Sites s,Clusters c, ComputeElements ce"
+ ",voViews v,voViewACLs acls WHERE s.id=c.site_id and c.id = ce.cluster_id "
+ "AND ce.id = v.ce_id and acls.voView_id=v.id AND acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "name");
}
public String[] getSitesOnGrid() {
String query = "select s.name from Sites s";
PreparedStatement s = getStatement(query);
return runQuery(s, "name");
}
public String[] getSitesWithAVersionOfACode(String code, String version) {
String query = "select distinct s.name from Sites s,Clusters c,SubClusters sc, "
+ " SoftwarePackages sp where s.id = c.site_id and c.id = sc.cluster_id "
+ " AND sp.subcluster_id = sc.id and sp.name=? and sp.version = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
return runQuery(s, "name");
}
public String[] getSitesWithCode(String code) {
String query = "select distinct s.name from Sites s,Clusters c,SubClusters sc, "
+ " SoftwarePackages sp where s.id = c.site_id and c.id = sc.cluster_id "
+ " AND sp.subcluster_id = sc.id and sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
return runQuery(s, "name");
}
private PreparedStatement getStatement(String query) {
try {
if (!con.isValid(1)) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(this.databaseUrl, this.user,
this.password);
}
PreparedStatement s = con.prepareStatement(query);
return s;
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public String getStorageElementForGridFTPServer(String gridFtp) {
String query = "select se.uniqueID from StorageElements se, AccessProtocols p WHERE "
+ " p.storageElement_id=se.id AND endpoint=?";
PreparedStatement s = getStatement(query);
setString(s, 1, gridFtp);
String[] ses = runQuery(s, "uniqueID");
if ((ses == null) || (ses.length == 0)) {
return null;
} else {
return ses[0];
}
}
public String[] getStorageElementsForSite(String site) {
String query = "select se.uniqueID from Sites s,StorageElements se WHERE se.site_id=s.id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "uniqueID");
}
public String[] getStorageElementsForVO(String fqan) {
String query = "select distinct se.uniqueID from Sites s, StorageElements se,"
+ "StorageAreas sa, storageAreaACLs sacls WHERE s.id = se.site_id and sa."
+ "storageElement_id = se.id AND sacls.storageArea_id = sa.id and sacls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "uniqueID");
}
private String getSubmissionHostName(String submissionLocation) {
int dot = submissionLocation.indexOf(":") + 1;
return submissionLocation.substring(dot);
}
private String getSubmissionQueue(String submissionLocation) {
int dot = submissionLocation.indexOf(":");
if (dot == -1) {
return "";
}
return submissionLocation.substring(0, dot);
}
public String[] getVersionsOfCodeAtSite(String site, String code) {
String query = "SELECT DISTINCT sp.version FROM Sites s,Clusters c,SubClusters "
+ " sc,SoftwarePackages sp WHERE s.id = c.site_id AND c.id = sc.cluster_id "
+ " AND sc.id = sp.subcluster_id AND s.name=? AND sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeForQueueAndContactString(String queueName,
String hostName, String code) {
String query = "select distinct sp.version from Clusters c,ComputeElements "
+ " ce,SubClusters sc,SoftwarePackages sp WHERE c.id = ce.cluster_id AND "
+ " c.id = sc.cluster_id AND sc.id = sp.subcluster_id AND sp.name=? "
+ "AND ce.hostName=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, hostName);
setString(s, 3, queueName);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeOnGrid(String code) {
String query = "select distinct version from SoftwarePackages sp where sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeOnGridForVO(String code, String fqan) {
String query = "select distinct sp.version from Clusters c, SubClusters sc, SoftwarePackages sp,"
+ " ComputeElements ce, voViews v, voViewACLs acls WHERE c.id = sc.cluster_id AND c.id ="
+ " ce.cluster_id AND sp.subcluster_id = sc.id AND ce.id = v.ce_id AND acls.voView_id ="
+ " v.id AND sp.name =? and acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, fqan);
return runQuery(s, "version");
}
public boolean isParallelAvailForCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "select 1 from ComputeElements ce,SubClusters sc,SoftwarePackages "
+ " sp,SoftwareExecutables exec where ce.cluster_id = sc.cluster_id AND "
+ " sp.subcluster_id = sc.id AND exec.package_id = sp.id AND "
+ " sp.name=? AND sp.version=? AND "
+ " ce.hostname=? AND ce.name=? AND " + " isParallel=1";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
setString(s, 3, hostname);
setString(s, 4, queue);
String[] result = runQuery(s, "1");
return !((result == null) || (result.length == 0));
}
public boolean isSerialAvailForCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "select 1 from ComputeElements ce,SubClusters sc,SoftwarePackages "
+ " sp,SoftwareExecutables exec where ce.cluster_id = sc.cluster_id AND "
+ " sp.subcluster_id = sc.id AND exec.package_id = sp.id AND "
+ " sp.name=? AND sp.version=? AND "
+ " ce.hostname=? AND ce.name=? AND " + " isSerial=1";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
setString(s, 3, hostname);
setString(s, 4, queue);
String[] result = runQuery(s, "1");
return !((result == null) || (result.length == 0));
}
public boolean isVolatile(String endpoint, String path, String fqan){
PreparedStatement s;
Pattern complete = Pattern.compile("gsiftp://.+:[0-9]+");
Pattern portOnly = Pattern.compile(".+:[0-9]+");
Pattern protocolOnly = Pattern.compile("gsiftp://.+");
if (complete.matcher(endpoint).matches()) {
// do nothing, endpoint has valid value
}
else if (portOnly.matcher(endpoint).matches()){
endpoint = "gsiftp://" + endpoint;
}
else if (protocolOnly.matcher(endpoint).matches()){
endpoint += ":2811";
}
else {
endpoint = "gsiftp://" + endpoint + ":2811";
}
String query = "select sa.type from AccessProtocols ap, StorageElements s, StorageAreas sa" +
",storageAreaACLs acls WHERE sa.id = acls.storageArea_id AND s.id = sa.storageElement_id AND " +
"ap.storageElement_id = s.id AND acls.vo = ? AND ap.endPoint=? AND (sa.path = ? OR sa.path LIKE ?)";
s = getStatement(query);
setString(s,1,fqan);
setString(s,2,endpoint);
setString(s,3,path);
setString(s,4,path + "[%]");
String[] result = runQuery(s,"type");
if (result.length > 0 ){
return result[0].equals(VOLATILE);
}
query = "select sa.type from AccessProtocols ap, StorageElements s, StorageAreas sa" +
",storageAreaACLs acls WHERE sa.id = acls.storageArea_id AND s.id = sa.storageElement_id AND " +
"ap.storageElement_id = s.id AND acls.vo = ? AND ap.endPoint=? AND (sa.path = '${GLOBUS_USER_HOME}' or " +
" sa.path = '/~/' or sa.path LIKE '.%' )";
s = getStatement(query);
setString(s,1,fqan);
setString(s,2,endpoint);
result = runQuery(s,"type");
if (result.length > 0 ){
return result[0].equals(VOLATILE);
}
return true;
}
private String[] runQuery(PreparedStatement s, String output) {
try {
myLogger.debug(s.toString());
HashSet<String> resultSet = new HashSet<String>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
resultSet.add(rs.getString(output));
}
return resultSet.toArray(new String[] {});
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private String[][] runQuery(PreparedStatement s, String output1,
String output2) {
try {
myLogger.debug(s.toString());
LinkedList<String> resultSet1 = new LinkedList<String>();
LinkedList<String> resultSet2 = new LinkedList<String>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
resultSet1.add(rs.getString(output1));
resultSet2.add(rs.getString(output2));
}
return new String[][] { resultSet1.toArray(new String[] {}),
resultSet2.toArray(new String[] {}) };
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private String[][] runQuery(PreparedStatement s, String[] outputs) {
try {
myLogger.debug(s.toString());
LinkedList<String[]> resultSet = new LinkedList<String[]>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
String[] outputValues = new String[outputs.length];
for (int i = 0; i < outputs.length; i++) {
outputValues[i] = rs.getString(outputs[i]);
}
resultSet.add(outputValues);
}
return resultSet.toArray(new String[][] {});
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private void setString(PreparedStatement s, int i, String string) {
try {
s.setString(i, string);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
| public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://mysql-bg.ceres.auckland.ac.nz/mds_test",
"grisu_read", "password");
QueryClient qClient = new QueryClient("/tmp");
SQLQueryClient sClient = new SQLQueryClient(con);
HashMap<JobSubmissionProperty, String> props = new HashMap<JobSubmissionProperty, String>();
props.put(JobSubmissionProperty.APPLICATIONNAME, Constants.GENERIC_APPLICATION_NAME);
props.put(JobSubmissionProperty.APPLICATIONVERSION, Constants.NO_VERSION_INDICATOR_STRING);
props.put(JobSubmissionProperty.WALLTIME_IN_MINUTES, "4000");
System.out.println("Check R...");
List<GridResource> resources = sClient.findAllResourcesM(props,
"/ARCS/Monash", true);
for (GridResource r : resources) {
System.out.println("R site: " + r.getSiteName());
}
printResults(
qClient.getApplicationNamesThatProvideExecutable("javac"),
"Query Client method 1");
printResults(
sClient.getApplicationNamesThatProvideExecutable("javac"),
"SQL Client method 1");
// appears broken
// printResults(qClient.getClusterNamesAtSite("canterbury.ac.nz"),"Query Client method 2");
printResults(sClient.getClusterNamesAtSite("Canterbury"),
"SQL Client method 2");
// broken too, maybe...
// printResults(qClient.getClustersForCodeAtSite("canterbury.ac.nz","Java","1.4.2"),"Query Client method 3");
printResults(sClient.getClustersForCodeAtSite("Canterbury", "Java",
"1.4.2"), "SQL Client method 3");
printResults(qClient.getCodesAtSite("Canterbury"),
"Query Client method 4");
printResults(sClient.getCodesAtSite("Canterbury"),
"SQL Client method 4");
printResults(qClient.getCodesOnGrid(), "Query Client method 5");
printResults(sClient.getCodesOnGrid(), "SQL Client method 5");
printResults(qClient.getContactStringOfQueueAtSite("eRSA",
"hydra@hydra"), "Query Client method 6");
printResults(sClient.getContactStringOfQueueAtSite("eRSA",
"hydra@hydra"), "SQL Client method 6");
printResults(qClient.getDataDir("Auckland", "ng2.auckland.ac.nz",
"/ARCS/BeSTGRID"), "Query Client method 7");
printResults(sClient.getDataDir("Auckland", "ng2.auckland.ac.nz",
"/ARCS/BeSTGRID"), "SQL Client method 7");
printResults(
new String[] { qClient.getDefaultStorageElementForQueueAtSite(
"Canterbury", "grid_aix") },
"Query Client method 8");
printResults(
new String[] { sClient.getDefaultStorageElementForQueueAtSite(
"Canterbury", "grid_aix") }, "SQL Client method 8");
printResults(
qClient.getExeNameOfCodeAtSite("Auckland", "Java", "1.6"),
"Query Client method 9");
printResults(
sClient.getExeNameOfCodeAtSite("Auckland", "Java", "1.6"),
"SQL Client method 9");
printResults(qClient.getExeNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6"), "Query Client method 10");
printResults(sClient.getExeNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6"), "SQL Client method 10");
printResults(qClient.getGridFTPServersAtSite("Auckland"),
"Query Client method 11");
printResults(sClient.getGridFTPServersAtSite("Auckland"),
"SQL Client method 11");
printResults(qClient.getGridFTPServersForQueueAtSite("Auckland",
"[email protected]"),
"Query Client method 12");
printResults(sClient.getGridFTPServersForQueueAtSite("Auckland",
"[email protected]"),
"SQL Client method 12");
printResults(qClient.getGridFTPServersForStorageElementAtSite(
"Auckland", "ngdata.ceres.auckland.ac.nz"),
"Query Client method 13");
printResults(sClient.getGridFTPServersForStorageElementAtSite(
"Auckland", "ngdata.ceres.auckland.ac.nz"),
"SQL Client method 13");
// also broken
// printResults(qClient.getGridFTPServersOnGrid(),"Query Client method 14");
printResults(sClient.getGridFTPServersOnGrid(),
"SQL Client method 14");
printResults(new String[] { qClient.getJobManagerOfQueueAtSite(
"Auckland", "[email protected]") },
"Query Client method 15");
printResults(new String[] { sClient.getJobManagerOfQueueAtSite(
"Auckland", "[email protected]") },
"SQL Client method 15");
// not sure what we are supposed to do here
// System.out.println(qClient.getJobTypeOfCodeAtSite("Auckland",
// "Java", "1.6"));
printResults(new String[] { qClient.getLRMSTypeOfQueueAtSite(
"Auckland", "[email protected]") },
"Query Client method 17");
printResults(new String[] { sClient.getLRMSTypeOfQueueAtSite(
"Auckland", "[email protected]") },
"SQL Client method 17");
printResults(
new String[] { qClient
.getModuleNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6") }, "Query Client method 18");
printResults(
new String[] { sClient
.getModuleNameOfCodeForSubmissionLocation(
"[email protected]:ng2.auckland.ac.nz",
"Java", "1.6") }, "SQL Client method 18");
printResults(qClient.getQueueNamesAtSite("Canterbury"),
"Query Client method 19");
printResults(sClient.getQueueNamesAtSite("Canterbury"),
"SQL Client method 19");
printResults(
qClient.getQueueNamesAtSite("Canterbury", "/ARCS/NGAdmin"),
"Query Client method 20");
printResults(
sClient.getQueueNamesAtSite("Canterbury", "/ARCS/NGAdmin"),
"SQL Client method 20");
// broken too!
// printResults(qClient.getQueueNamesForClusterAtSite("Canterbury","ng1.canterbury.ac.nz"),"Query Client method 21");
printResults(sClient.getQueueNamesForClusterAtSite("Canterbury",
"ng1.canterbury.ac.nz"), "SQL Client method 21");
printResults(
qClient.getQueueNamesForCodeAtSite("Canterbury", "Java"),
"Query Client method 22");
printResults(
sClient.getQueueNamesForCodeAtSite("Canterbury", "Java"),
"SQL Client method 22");
printResults(qClient.getQueueNamesForCodeAtSite("Canterbury",
"Java", "1.4.2"), "Query Client method 23");
printResults(sClient.getQueueNamesForCodeAtSite("Canterbury",
"Java", "1.4.2"), "SQL Client method 23");
printResults(
new String[] { qClient.getSiteForHost("cognac.ivec.org") },
"Query Client method 24");
printResults(
new String[] { sClient.getSiteForHost("cognac.ivec.org") },
"SQL Client method 24");
printResults(qClient.getSitesOnGrid(), "Query Client method 25");
printResults(sClient.getSitesOnGrid(), "SQL Client method 25");
printResults(qClient.getSitesWithAVersionOfACode("Java", "1.6"),
"Query Client method 26");
printResults(sClient.getSitesWithAVersionOfACode("Java", "1.6"),
"SQL Client method 26");
printResults(qClient.getSitesWithCode("Java"),
"Query Client method 27");
printResults(sClient.getSitesWithCode("Java"),
"SQL Client method 27");
printResults(
new String[] { qClient
.getStorageElementForGridFTPServer("gsiftp://ng2.esscc.uq.edu.au:2811") },
"Query Client method 28");
printResults(
new String[] { sClient
.getStorageElementForGridFTPServer("gsiftp://ng2.esscc.uq.edu.au:2811") },
"SQL Client method 28");
printResults(qClient.getStorageElementsForSite("HPSC"),
"Query Client method 29");
printResults(sClient.getStorageElementsForSite("HPSC"),
"SQL Client method 29");
printResults(qClient.getVersionsOfCodeAtSite("Auckland", "Java"),
"Query Client method 30");
printResults(sClient.getVersionsOfCodeAtSite("Auckland", "Java"),
"SQL Client method 30");
printResults(
qClient.getVersionsOfCodeForQueueAndContactString(
"grid_aix",
"https://ng2hpc.canterbury.ac.nz:8443/wsrf/services/ManagedJobFactoryService",
"Java"), "Query Client method 31");
printResults(
sClient.getVersionsOfCodeForQueueAndContactString(
"grid_aix",
"https://ng2hpc.canterbury.ac.nz:8443/wsrf/services/ManagedJobFactoryService",
"Java"), "SQL Client method 31");
printResults(qClient.getVersionsOfCodeOnGrid("beast"),
"Query Client method 32");
printResults(sClient.getVersionsOfCodeOnGrid("beast"),
"SQL Client method 32");
printResults(
new String[] { ""
+ qClient.isParallelAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"Query Client method 33");
printResults(
new String[] { ""
+ sClient.isParallelAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"SQL Client method 33");
// and this one is broken as well so it seems...
printResults(
new String[] { ""
+ qClient.isSerialAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"Query Client method 34");
printResults(
new String[] { ""
+ sClient.isSerialAvailForCodeForSubmissionLocation(
"grid_aix:ng2hpc.canterbury.ac.nz",
"MrBayes", "3.1.2") },
"SQL Client method 34");
printResults(qClient.getSitesForVO("/ARCS/BeSTGRID"),
"Query Client method 35");
printResults(sClient.getSitesForVO("/ARCS/BeSTGRID"),
"SQL Client method 35");
Map<String, String[]> data = sClient
.calculateDataLocationsForVO("/ARCS/BeSTGRID");
for (String key : data.keySet()) {
System.out.println("key is : " + key);
String[] values = data.get(key);
for (String value : values) {
System.out.println(value);
}
}
printResults(qClient.getGridFTPServersForQueueAtSite("Canterbury",
"gt5test"), "qclient getGridFTPServersForQueueAtSite");
printResults(sClient.getGridFTPServersForQueueAtSite("Canterbury",
"gt5test"), "sclient getGridFTPServersForQueueAtSite");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-bestgrid", "/ARCS/BeSTGRID"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-bestgrid /ARCS/BeSTGRID");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/yhal003", "/ARCS/BeSTGRID/Local"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/yhal003 /ARCS/BeSTGRID/Local");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-sbs", "/ARCS/BeSTGRID/Drug_discovery/SBS-Structural_Biology"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-sbs /ARCS/BeSTGRID/Drug_discovery/SBS-Structural_Biology");
printResults(sClient.isVolatile("gsiftp://ng2.auckland.ac.nz:2811", "/home/grid-acsrc", "/ARCS/BeSTGRID/Drug_discovery/ACSRC"),
"qClient isVolatile gsiftp://ng2.auckland.ac.nz:2811 /home/grid-acsrc /ARCS/BeSTGRID/Drug_discovery/ACSRC");
Map<JobSubmissionProperty,String> jobProperties = new HashMap<JobSubmissionProperty,String>();
jobProperties.put(JobSubmissionProperty.APPLICATIONNAME,"mech-uoa");
//jobProperties.put(JobSubmissionProperty.APPLICATIONVERSION, "1.5");
//jobProperties.put(JobSubmissionProperty.NO_CPUS, "1");
resources = sClient.findAllResourcesM(jobProperties, "/nz/NeSI",false);
for (GridResource r: resources){
System.out.println(r.getQueueName());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void printResults(String[] results, String label) {
System.out.println(label);
for (String result : results) {
System.out.println(result);
}
}
private static void printResults(boolean result, String label){
printResults( new String[] {new Boolean(result).toString()},label);
}
private Connection con;
private String databaseUrl, user, password;
public SQLQueryClient(Connection con) {
this.con = con;
}
public SQLQueryClient(String databaseUrl, String user, String password) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.databaseUrl = databaseUrl;
this.user = user;
this.password = password;
this.con = DriverManager.getConnection(databaseUrl, user, password);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public Map<String, String[]> calculateDataLocationsForVO(String fqan) {
// getDataDir(String site, String storageElement, String FQAN)
HashMap<String, String[]> map = new HashMap<String, String[]>();
String query = "select sa.path,ap.endpoint from StorageElements se,StorageAreas sa,AccessProtocols ap, storageAreaACLs sacls "
+ " WHERE ap.storageElement_id = se.id AND sa.storageElement_id = se.id AND sacls.storageArea_id = sa.id and sacls.vo =?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
String[][] results = runQuery(s, "path", "endpoint");
String[] paths = results[0];
String[] endpoints = results[1];
for (int i = 0; i < endpoints.length; i++) {
map.put(endpoints[i], new String[] { paths[i] });
}
return map;
}
public List<GridResource> findAllResourcesM(
Map<JobSubmissionProperty, String> jobProperties, String fqan,
boolean exclude) {
List<GridResource> results = new LinkedList<GridResource>();
String query = "SELECT acls.vo fqan, contactString, gramVersion," +
" jobManager, ce.name queue, maxWalltime, v.freeJobSlots, " +
"v.runningJobs, v.waitingJobs, v.totalJobs, s.name site, " +
"lattitude, longitude, sp.name sname ,sp.version sversion" +
" FROM" +
" Sites s, SubClusters sc, Clusters c, ComputeElements ce, voViews v, " +
"voViewACLs acls, SoftwarePackages sp " +
"WHERE " +
"acls.voView_id = v.id and ce.cluster_id =c.id and " +
"c.site_id = s.id and c.id = sc.cluster_id and " +
"v.ce_id = ce.id and sp.subcluster_id = sc.id and acls.vo=?";
int wallTimeRequirement = -1;
try {
wallTimeRequirement = Integer.parseInt(jobProperties
.get(JobSubmissionProperty.WALLTIME_IN_MINUTES));
} catch (Exception e) {
}
int totalCPURequirement = -1;
try {
totalCPURequirement = Integer.parseInt(jobProperties
.get(JobSubmissionProperty.NO_CPUS));
} catch (Exception e) {
}
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
String[][] resources = runQuery(s, new String[] { "queue",
"contactString", "gramVersion", "jobManager", "freeJobSlots",
"runningJobs", "waitingJobs", "totalJobs", "site", "lattitude",
"longitude", "maxWalltime","sname","sversion" });
for (String[] resource : resources) {
// check if application name matches
String applicationName = jobProperties.get(JobSubmissionProperty.APPLICATIONNAME);
if (StringUtils.isNotBlank(applicationName)
&& !Constants.GENERIC_APPLICATION_NAME
.equals(applicationName)
&& !resource[12].equals(applicationName)) {
continue;
}
// check if application version matches
String applicationVersion = jobProperties.get(JobSubmissionProperty.APPLICATIONVERSION);
if (StringUtils.isNotBlank(applicationVersion)
&& !Constants.NO_VERSION_INDICATOR_STRING.equals(applicationVersion)
&& !resource[13].equals(applicationVersion)){
continue;
}
GridResourceBackendImpl gr = new GridResourceBackendImpl();
gr.setQueueName(resource[0]);
gr.setContactString(resource[1]);
gr.setGRAMVersion(resource[2]);
gr.setJobManager(resource[3]);
gr.setFreeJobSlots(Integer.parseInt(resource[4]));
int maxWalltime = Integer.parseInt(resource[11]);
if (exclude
&& ((gr.getFreeJobSlots() < totalCPURequirement) || (maxWalltime < wallTimeRequirement))) {
continue;
}
gr.setRunningJobs(Integer.parseInt(resource[5]));
gr.setWaitingJobs(Integer.parseInt(resource[6]));
gr.setTotalJobs(Integer.parseInt(resource[7]));
gr.setSiteName(resource[8]);
gr.setSiteLatitude(Double.parseDouble(resource[9]));
gr.setSiteLongitude(Double.parseDouble(resource[10]));
gr.setApplicationName(applicationName);
gr.addAvailableApplicationVersion(applicationVersion);
String[] exes = getExecutables(gr.getSiteName(),gr.getQueueName(),applicationName,applicationVersion);
Set<String> executables = new HashSet<String>();
for (String exe : exes) {
executables.add(exe);
}
if (executables.size() == 0){
executables.add(Constants.GENERIC_APPLICATION_NAME);
}
gr.setAllExecutables(executables);
results.add(gr);
}
return results;
}
private String[] getExecutables(String siteName, String queue, String appName, String appVersion){
if (appName == null && appVersion == null){
return new String[] {};
}
String query = "select exe.name exeName from Sites s, Clusters c,SubClusters sc"
+ ",ComputeElements ce, SoftwarePackages sp, SoftwareExecutables exe "
+ "where s.id = c.site_id and c.id= sc.cluster_id and sp.subcluster_id = sc.id "
+ "and exe.package_id = sp.id AND ce.cluster_id = c.id AND "
+ "s.name =? and ce.name =? AND (sp.name=? OR ? = ?) AND (sp.version=? OR ? = ?)";
PreparedStatement s = getStatement(query);
setString(s, 1, siteName);
setString(s, 2,queue);
setString(s, 3, appName);
setString(s, 4, appName);
setString(s, 5, Constants.GENERIC_APPLICATION_NAME);
setString(s, 6, appVersion);
setString(s, 7, appVersion);
setString(s, 8, Constants.NO_VERSION_INDICATOR_STRING);
return runQuery(s, "exeName");
}
public Map<String, String> getAllComputeHosts() {
Map<String, String> results = new HashMap<String, String>();
String query = "select DISTINCT s.name as site, "
+ " SUBSTRING_INDEX(TRIM(LEADING 'https://' FROM ce.contactString),':',1) hostname "
+ "FROM Sites s ,Clusters c,ComputeElements ce WHERE s.id = c.site_id and c.id = ce.cluster_id;";
PreparedStatement s = getStatement(query);
String[][] hostnames = runQuery(s, new String[] { "site", "hostname" });
for (String[] hostname : hostnames) {
results.put(hostname[1], hostname[0]);
}
return results;
}
public Map<String, String> getAllDataHosts() {
Map<String, String> results = new HashMap<String, String>();
String query = "SELECT DISTINCT s.name as site,"
+ "SUBSTRING_INDEX(TRIM(LEADING 'gsiftp://' FROM endpoint),':',1) as hostname "
+ "FROM Sites s,StorageElements se,StorageAreas sa, AccessProtocols p "
+ "WHERE s.id = se.site_id AND se.id = sa.storageElement_ID AND se.id=p.storageElement_ID";
PreparedStatement s = getStatement(query);
String[][] hostnames = runQuery(s, new String[] { "site", "hostname" });
for (String[] hostname : hostnames) {
results.put(hostname[1], hostname[0]);
}
return results;
}
// only partially implemented
public GridResource[] getAllGridResources() {
String query = "select contactString,gramVersion,jobManager,ce.name,"
+ "freeJobSlots,runningJobs,waitingJobs,totalJobs,s.name,"
+ "lattitude,longitude "
+ "from Sites s,Clusters c ,ComputeElements ce where "
+ "ce.cluster_id = c.id and c.site_id = s.id";
PreparedStatement s = getStatement(query);
String[][] results = runQuery(s, new String[] { "contactString",
"gramVersion", "jobManager", "ce.name", "freeJobSlots",
"runningJobs", "waitingJobs", "totalJobs", "s.name",
"lattitude", "longitude" });
GridResource[] grs = new GridResource[results.length];
for (int i = 0; i < results.length; i++) {
GridResourceBackendImpl gr = new GridResourceBackendImpl();
gr.setContactString(results[i][0]);
gr.setGRAMVersion(results[i][1]);
gr.setJobManager(results[i][2]);
gr.setQueueName(results[i][3]);
grs[i] = gr;
}
return grs;
}
public String[] getApplicationNamesThatProvideExecutable(String executable) {
String query = "SELECT DISTINCT BINARY sp.name as name FROM SoftwareExecutables AS "
+ " se,SoftwarePackages AS sp WHERE se.package_id = sp.id AND "
+ " se.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, executable);
return runQuery(s, "name");
}
public String[] getClusterNamesAtSite(String site) {
String query = "SELECT c.name as name FROM Sites AS s ,Clusters AS c WHERE s.id = c.site_id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getClustersForCodeAtSite(String site, String code,
String version) {
String query = " SELECT c.uniqueID FROM Sites AS s ,Clusters AS c, SubClusters AS "
+ " sc,SoftwarePackages as p where s.id = c.site_id AND sc.cluster_id = c.id "
+ " AND p.subcluster_id = sc.id AND s.name=? AND "
+ " p.name=? AND p.version = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "uniqueID");
}
public String[] getCodesAtSite(String site) {
String query = "SELECT DISTINCT p.name FROM Sites AS s ,Clusters AS c, SubClusters AS "
+ " sc,SoftwarePackages AS p WHERE s.id = c.site_id AND sc.cluster_id = "
+ " c.id AND s.name=? AND p.subcluster_id = sc.id;";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getCodesOnGrid() {
String query = "SELECT DISTINCT BINARY name AS NAME FROM SoftwarePackages";
PreparedStatement s = getStatement(query);
return runQuery(s, "name");
}
public String[] getCodesOnGridForVO(String fqan) {
String query = "select distinct binary sp.name as name from SubClusters sc, ComputeElements ce, voViews v, voViewACLs acls, SoftwarePackages sp"
+ " WHERE sc.cluster_id = ce.cluster_id AND v.ce_id = ce.id "
+ "AND acls.voView_id = v.id AND sp.subcluster_id = sc.id AND acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "name");
}
public String[] getContactStringOfQueueAtSite(String site, String queue) {
String query = " SELECT contactString FROM ComputeElements ce,Clusters c,Sites s WHERE "
+ "c.site_id = s.id AND ce.cluster_id = c.id AND s.name = ? AND ce.name =? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "contactString");
}
public String[] getDataDir(String site, String storageElement, String FQAN) {
String query = " SELECT StorageAreas.path FROM "
+ " Sites,StorageElements,StorageAreas,storageAreaACLs WHERE "
+ " Sites.id=StorageElements.site_id AND StorageElements.id = "
+ " StorageAreas.storageElement_id AND StorageAreas.id = "
+ " storageAreaACLs.storageArea_id AND Sites.name=? "
+ "AND vo=? AND StorageElements.uniqueID =?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 3, storageElement);
setString(s, 2, FQAN);
return runQuery(s, "path");
}
public String getDefaultStorageElementForQueueAtSite(String site,
String queue) {
String query = "SELECT se.uniqueID FROM Sites AS s,StorageElements AS "
+ " se,ComputeElements AS ce WHERE s.id = se.site_id AND s.id = se.site_id "
+ " AND ce.defaultSE_id = se.id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
String[] elements = runQuery(s, "uniqueID");
if ((elements == null) || (elements.length == 0)) {
return null;
} else {
return elements[0];
}
}
public String[] getExeNameOfCodeAtSite(String site, String code,
String version) {
String query = "SELECT exec.name FROM Sites AS s ,Clusters AS c,SubClusters AS "
+ " sc,SoftwarePackages AS sp,SoftwareExecutables AS exec WHERE s.id = "
+ " c.site_id AND c.id = sc.cluster_id AND sc.id = sp.subcluster_id AND "
+ " exec.package_id = sp.id AND s.name=? AND "
+ " sp.name=? AND sp.version=? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "name");
}
public String[] getExeNameOfCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "SELECT exec.name FROM Sites AS s ,ComputeElements AS ce,Clusters AS "
+ " c ,SubClusters AS sc,SoftwarePackages AS sp,SoftwareExecutables AS "
+ " exec WHERE c.id = ce.cluster_id AND s.id = c.site_id AND c.id = "
+ " sc.cluster_id AND sc.id = sp.subcluster_id AND exec.package_id = "
+ " sp.id AND ce.name=? AND "
+ " ce.hostname=? AND sp.name=? AND sp.version=?";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, queue);
setString(s, 2, hostname);
setString(s, 3, code);
setString(s, 4, version);
return runQuery(s, "name");
}
public String[] getGridFTPServersAtSite(String site) {
String query = "SELECT DISTINCT endpoint FROM Sites AS s ,StorageElements AS "
+ " se,StorageAreas AS sa, AccessProtocols AS p WHERE s.id = se.site_id "
+ " AND se.id = sa.storageElement_ID AND se.id=p.storageElement_ID AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersForQueueAtSite(String site, String queue) {
String query = "SELECT DISTINCT endpoint FROM Sites s ,Clusters c,StorageElements "
+ " se,StorageAreas sa, AccessProtocols p,ComputeElements ce "
+ " WHERE s.id = se.site_id AND s.id = c.site_id AND ce.cluster_id = c.id AND se.id = "
+ "sa.storageElement_ID AND ce.defaultSE_id = se.id AND se.id=p.storageElement_ID AND "
+ " s.name=? AND ce.name = ? ";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersForStorageElementAtSite(String site,
String storageElement) {
String query = "select distinct endpoint from Sites s, Clusters c ,StorageElements "
+ " se,StorageAreas sa, AccessProtocols p,ComputeElements ce "
+ " WHERE s.id = se.site_id AND s.id = c.site_id AND c.id = ce.cluster_id AND se.id = "
+ " sa.storageElement_ID AND se.id=p.storageElement_ID AND "
+ " s.name=? AND se.uniqueID =?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, storageElement);
return runQuery(s, "endpoint");
}
public String[] getGridFTPServersOnGrid() {
String query = "select AccessProtocols.endpoint from StorageElements,AccessProtocols "
+ " where StorageElements.id = AccessProtocols.storageElement_id";
PreparedStatement s = getStatement(query);
return runQuery(s, "endpoint");
}
public String getJobManagerOfQueueAtSite(String site, String queue) {
String query = "select ce.jobManager from Sites s,Clusters c,ComputeElements ce WHERE s.id "
+ " = c.site_id AND c.id = ce.cluster_id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "jobManager")[0];
}
// not sure what this means
public String getJobTypeOfCodeAtSite(String site, String code,
String version) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getLRMSTypeOfQueueAtSite(String site, String queue) {
String query = "SELECT ce.lRMSType FROM Sites s,Clusters c,ComputeElements ce WHERE s.id = "
+ " c.site_id AND c.id = ce.cluster_id AND s.name=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, queue);
return runQuery(s, "lRMSType")[0];
}
public String getModuleNameOfCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "SELECT sp.module FROM Sites AS s ,ComputeElements AS ce,Clusters AS "
+ " c ,SubClusters AS sc,SoftwarePackages AS sp "
+ " WHERE s.id = c.site_id AND c.id = ce.cluster_id AND c.id = "
+ " sc.cluster_id AND sc.id = sp.subcluster_id AND ce.name=? AND "
+ " ce.hostname=? AND sp.name=? AND sp.version=?";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, queue);
setString(s, 2, hostname);
setString(s, 3, code);
setString(s, 4, version);
String[] module = runQuery(s, "module");
if ((module == null) || (module.length == 0)) {
return null;
} else {
return module[0];
}
}
public String[] getQueueNamesAtSite(String site) {
String query = " SELECT ce.name FROM Sites s,Clusters c "
+ ",ComputeElements ce WHERE s.id = c.site_id AND c.id = ce.cluster_id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "name");
}
public String[] getQueueNamesAtSite(String site, String fqan) {
String query = "select ce.name from voViews v,Sites s,Clusters c,ComputeElements ce,voViewACLs "
+ " acls where s.id = c.site_id and c.id = ce.cluster_id and v.ce_id=ce.id AND v.id = "
+ " acls.voView_id AND s.name=? and vo = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, fqan);
return runQuery(s, "name");
}
public String[] getQueueNamesForClusterAtSite(String site, String cluster) {
String query = "select ce.name from Sites s,ComputeElements ce,Clusters as c where "
+ "s.id = c.site_id and c.id = ce.cluster_id AND s.name=? and c.name = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, cluster);
return runQuery(s, "name");
}
public String[] getQueueNamesForCodeAtSite(String site, String code) {
String query = "select ce.name from Sites as s ,ComputeElements as ce,Clusters as "
+ " c,SubClusters as sc,SoftwarePackages as sp WHERE s.id = c.site_id AND "
+ " c.id = ce.cluster_id AND c.id = sc.cluster_id AND sc.id = "
+ " sp.subcluster_id AND s.name=? AND sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
return runQuery(s, "name");
}
public String[] getQueueNamesForCodeAtSite(String site, String code,
String version) {
String query = "select ce.name from Sites as s ,ComputeElements as ce,Clusters as "
+ " c,SubClusters as sc,SoftwarePackages as sp WHERE s.id = c.site_id AND "
+ " c.id = ce.cluster_id AND c.id = sc.cluster_id AND sc.id = "
+ " sp.subcluster_id AND s.name=? AND sp.name=? AND sp.version=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
setString(s, 3, version);
return runQuery(s, "name");
}
public String getSiteForHost(String host) {
String query = "SELECT DISTINCT s.name from Sites s, Clusters c, ComputeElements ce where s.id "
+ " = c.site_id AND c.id = ce.cluster_id and ce.hostname=?";
PreparedStatement s = getStatement(query);
setString(s, 1, host);
String[] sites = runQuery(s, "name");
if ((sites == null) || (sites.length == 0)) {
return null;
} else {
return sites[0];
}
}
public String[] getSitesForVO(String fqan) {
String query = " select distinct s.name from Sites s,Clusters c, ComputeElements ce"
+ ",voViews v,voViewACLs acls WHERE s.id=c.site_id and c.id = ce.cluster_id "
+ "AND ce.id = v.ce_id and acls.voView_id=v.id AND acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "name");
}
public String[] getSitesOnGrid() {
String query = "select s.name from Sites s";
PreparedStatement s = getStatement(query);
return runQuery(s, "name");
}
public String[] getSitesWithAVersionOfACode(String code, String version) {
String query = "select distinct s.name from Sites s,Clusters c,SubClusters sc, "
+ " SoftwarePackages sp where s.id = c.site_id and c.id = sc.cluster_id "
+ " AND sp.subcluster_id = sc.id and sp.name=? and sp.version = ?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
return runQuery(s, "name");
}
public String[] getSitesWithCode(String code) {
String query = "select distinct s.name from Sites s,Clusters c,SubClusters sc, "
+ " SoftwarePackages sp where s.id = c.site_id and c.id = sc.cluster_id "
+ " AND sp.subcluster_id = sc.id and sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
return runQuery(s, "name");
}
private PreparedStatement getStatement(String query) {
try {
if (!con.isValid(1)) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(this.databaseUrl, this.user,
this.password);
}
PreparedStatement s = con.prepareStatement(query);
return s;
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public String getStorageElementForGridFTPServer(String gridFtp) {
String query = "select se.uniqueID from StorageElements se, AccessProtocols p WHERE "
+ " p.storageElement_id=se.id AND endpoint=?";
PreparedStatement s = getStatement(query);
setString(s, 1, gridFtp);
String[] ses = runQuery(s, "uniqueID");
if ((ses == null) || (ses.length == 0)) {
return null;
} else {
return ses[0];
}
}
public String[] getStorageElementsForSite(String site) {
String query = "select se.uniqueID from Sites s,StorageElements se WHERE se.site_id=s.id AND s.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
return runQuery(s, "uniqueID");
}
public String[] getStorageElementsForVO(String fqan) {
String query = "select distinct se.uniqueID from Sites s, StorageElements se,"
+ "StorageAreas sa, storageAreaACLs sacls WHERE s.id = se.site_id and sa."
+ "storageElement_id = se.id AND sacls.storageArea_id = sa.id and sacls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, fqan);
return runQuery(s, "uniqueID");
}
private String getSubmissionHostName(String submissionLocation) {
int dot = submissionLocation.indexOf(":") + 1;
return submissionLocation.substring(dot);
}
private String getSubmissionQueue(String submissionLocation) {
int dot = submissionLocation.indexOf(":");
if (dot == -1) {
return "";
}
return submissionLocation.substring(0, dot);
}
public String[] getVersionsOfCodeAtSite(String site, String code) {
String query = "SELECT DISTINCT sp.version FROM Sites s,Clusters c,SubClusters "
+ " sc,SoftwarePackages sp WHERE s.id = c.site_id AND c.id = sc.cluster_id "
+ " AND sc.id = sp.subcluster_id AND s.name=? AND sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, site);
setString(s, 2, code);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeForQueueAndContactString(String queueName,
String hostName, String code) {
String query = "select distinct sp.version from Clusters c,ComputeElements "
+ " ce,SubClusters sc,SoftwarePackages sp WHERE c.id = ce.cluster_id AND "
+ " c.id = sc.cluster_id AND sc.id = sp.subcluster_id AND sp.name=? "
+ "AND ce.hostName=? AND ce.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, hostName);
setString(s, 3, queueName);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeOnGrid(String code) {
String query = "select distinct version from SoftwarePackages sp where sp.name=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
return runQuery(s, "version");
}
public String[] getVersionsOfCodeOnGridForVO(String code, String fqan) {
String query = "select distinct sp.version from Clusters c, SubClusters sc, SoftwarePackages sp,"
+ " ComputeElements ce, voViews v, voViewACLs acls WHERE c.id = sc.cluster_id AND c.id ="
+ " ce.cluster_id AND sp.subcluster_id = sc.id AND ce.id = v.ce_id AND acls.voView_id ="
+ " v.id AND sp.name =? and acls.vo=?";
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, fqan);
return runQuery(s, "version");
}
public boolean isParallelAvailForCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "select 1 from ComputeElements ce,SubClusters sc,SoftwarePackages "
+ " sp,SoftwareExecutables exec where ce.cluster_id = sc.cluster_id AND "
+ " sp.subcluster_id = sc.id AND exec.package_id = sp.id AND "
+ " sp.name=? AND sp.version=? AND "
+ " ce.hostname=? AND ce.name=? AND " + " isParallel=1";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
setString(s, 3, hostname);
setString(s, 4, queue);
String[] result = runQuery(s, "1");
return !((result == null) || (result.length == 0));
}
public boolean isSerialAvailForCodeForSubmissionLocation(String subLoc,
String code, String version) {
String query = "select 1 from ComputeElements ce,SubClusters sc,SoftwarePackages "
+ " sp,SoftwareExecutables exec where ce.cluster_id = sc.cluster_id AND "
+ " sp.subcluster_id = sc.id AND exec.package_id = sp.id AND "
+ " sp.name=? AND sp.version=? AND "
+ " ce.hostname=? AND ce.name=? AND " + " isSerial=1";
String hostname = getSubmissionHostName(subLoc);
String queue = getSubmissionQueue(subLoc);
PreparedStatement s = getStatement(query);
setString(s, 1, code);
setString(s, 2, version);
setString(s, 3, hostname);
setString(s, 4, queue);
String[] result = runQuery(s, "1");
return !((result == null) || (result.length == 0));
}
public boolean isVolatile(String endpoint, String path, String fqan){
PreparedStatement s;
Pattern complete = Pattern.compile("gsiftp://.+:[0-9]+");
Pattern portOnly = Pattern.compile(".+:[0-9]+");
Pattern protocolOnly = Pattern.compile("gsiftp://.+");
if (complete.matcher(endpoint).matches()) {
// do nothing, endpoint has valid value
}
else if (portOnly.matcher(endpoint).matches()){
endpoint = "gsiftp://" + endpoint;
}
else if (protocolOnly.matcher(endpoint).matches()){
endpoint += ":2811";
}
else {
endpoint = "gsiftp://" + endpoint + ":2811";
}
String query = "select sa.type from AccessProtocols ap, StorageElements s, StorageAreas sa" +
",storageAreaACLs acls WHERE sa.id = acls.storageArea_id AND s.id = sa.storageElement_id AND " +
"ap.storageElement_id = s.id AND acls.vo = ? AND ap.endPoint=? AND (sa.path = ? OR sa.path LIKE ?)";
s = getStatement(query);
setString(s,1,fqan);
setString(s,2,endpoint);
setString(s,3,path);
setString(s,4,path + "[%]");
String[] result = runQuery(s,"type");
if (result.length > 0 ){
return result[0].equals(VOLATILE);
}
query = "select sa.type from AccessProtocols ap, StorageElements s, StorageAreas sa" +
",storageAreaACLs acls WHERE sa.id = acls.storageArea_id AND s.id = sa.storageElement_id AND " +
"ap.storageElement_id = s.id AND acls.vo = ? AND ap.endPoint=? AND (sa.path = '${GLOBUS_USER_HOME}' or " +
" sa.path = '/~/' or sa.path LIKE '.%' )";
s = getStatement(query);
setString(s,1,fqan);
setString(s,2,endpoint);
result = runQuery(s,"type");
if (result.length > 0 ){
return result[0].equals(VOLATILE);
}
return true;
}
private String[] runQuery(PreparedStatement s, String output) {
try {
myLogger.debug(s.toString());
HashSet<String> resultSet = new HashSet<String>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
resultSet.add(rs.getString(output));
}
return resultSet.toArray(new String[] {});
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private String[][] runQuery(PreparedStatement s, String output1,
String output2) {
try {
myLogger.debug(s.toString());
LinkedList<String> resultSet1 = new LinkedList<String>();
LinkedList<String> resultSet2 = new LinkedList<String>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
resultSet1.add(rs.getString(output1));
resultSet2.add(rs.getString(output2));
}
return new String[][] { resultSet1.toArray(new String[] {}),
resultSet2.toArray(new String[] {}) };
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private String[][] runQuery(PreparedStatement s, String[] outputs) {
try {
myLogger.debug(s.toString());
LinkedList<String[]> resultSet = new LinkedList<String[]>();
s.execute();
ResultSet rs = s.getResultSet();
while (rs.next()) {
String[] outputValues = new String[outputs.length];
for (int i = 0; i < outputs.length; i++) {
outputValues[i] = rs.getString(outputs[i]);
}
resultSet.add(outputValues);
}
return resultSet.toArray(new String[][] {});
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
private void setString(PreparedStatement s, int i, String string) {
try {
s.setString(i, string);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
index bcfbb37fc..09150612d 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/ScheduleTaskMenuContributor.java
@@ -1,329 +1,329 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers 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
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil;
import org.eclipse.mylyn.internal.tasks.ui.planner.DateSelectionDialog;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.tasks.ui.DatePicker;
import org.eclipse.mylyn.tasks.ui.TaskListManager;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.ui.PlatformUI;
/**
* TODO: this has bloated, refactor
*
* @author Rob Elves
* @author Mik Kersten
*/
public class ScheduleTaskMenuContributor implements IDynamicSubMenuContributor {
private static final String LABEL_THIS_WEEK = "This week";
private static final String LABEL_REMINDER = "Schedule for";
private static final String LABEL_TODAY = "Today";
private static final String LABEL_NEXT_WEEK = "Next Week";
private static final String LABEL_TWO_WEEKS = "Two Weeks";
private static final String LABEL_FUTURE = "Future";
private static final String LABEL_CALENDAR = "Choose Date...";
private static final String LABEL_NOT_SCHEDULED = "Not Scheduled";
@SuppressWarnings("deprecation")
public MenuManager getSubMenuManager(final List<AbstractTaskContainer> selectedElements) {
final TaskListManager tasklistManager = TasksUiPlugin.getTaskListManager();
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
subMenuManager.setVisible(selectedElements.size() > 0 && selectedElements.get(0) instanceof AbstractTask);// !(selectedElements.get(0) instanceof AbstractTaskContainer || selectedElements.get(0) instanceof AbstractRepositoryQuery));
AbstractTaskContainer singleSelection = null;
if (selectedElements.size() == 1) {
AbstractTaskContainer selectedElement = selectedElements.get(0);
if (selectedElement instanceof AbstractTask) {
singleSelection = selectedElement;
}
}
final AbstractTask singleTaskSelection = tasklistManager.getTaskForElement(singleSelection, false);
final List<AbstractTaskContainer> taskListElementsToSchedule = new ArrayList<AbstractTaskContainer>();
for (AbstractTaskContainer selectedElement : selectedElements) {
if (selectedElement instanceof AbstractTask) {
taskListElementsToSchedule.add(selectedElement);
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledEndOfDay(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
action.setText(LABEL_TODAY);
action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && (TasksUiPlugin.getTaskListManager().isScheduledForToday(singleTaskSelection)
- || singleTaskSelection.isPastReminder())) {
+ || (singleTaskSelection.isPastReminder() && !singleTaskSelection.internalIsFloatingScheduledDate()))) {
action.setChecked(true);
}
// subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
for (int i = today + 1; i <= today + 7; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
int dueIn = day - today;
TasksUiPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
getDayLabel(i, action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null
&& !singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, i - today);
now.getTime();
Calendar then = Calendar.getInstance();
then.setTime(singleTaskSelection.getScheduledForDate());
if(now.get(Calendar.DAY_OF_MONTH) == then.get(Calendar.DAY_OF_MONTH)) {
action.setChecked(true);
}
}
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
TaskActivityUtil.snapStartOfWorkWeek(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, reminderCalendar.getTime(), true);
}
}
}
};
action.setText(LABEL_THIS_WEEK);
action.setImageDescriptor(TasksUiImages.SCHEDULE_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate() && TasksUiPlugin.getTaskListManager().isScheduledForThisWeek(singleTaskSelection)) {
action.setChecked(true);
}
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
Calendar startNextWeek = Calendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(startNextWeek);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, startNextWeek.getTime(), true);
}
}
};
action.setText(LABEL_NEXT_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate()
&& TasksUiPlugin.getTaskListManager().isScheduledAfterThisWeek(singleTaskSelection)
&& !TasksUiPlugin.getTaskListManager().isScheduledForLater(singleTaskSelection)) {
action.setChecked(true);
}
subMenuManager.add(action);
// 2 weeks
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
Calendar twoWeeks = TaskActivityUtil.getCalendar();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(twoWeeks);
twoWeeks.add(Calendar.DAY_OF_MONTH, 7);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, twoWeeks.getTime(), true);
}
}
}
};
action.setText(LABEL_TWO_WEEKS);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null && singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
Calendar end = TaskActivityUtil.getCalendar();
end.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
TaskActivityUtil.snapEndOfWeek(end);
if (TaskActivityUtil.isBetween(time, start, end)) {
action.setChecked(true);
}
}
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
start.add(Calendar.WEEK_OF_MONTH, 1);
if (time.compareTo(start) >= 0) {
// future
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(LABEL_FUTURE);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
theCalendar.setTime(singleTaskSelection.getScheduledForDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), theCalendar, DatePicker.TITLE_DIALOG, false);
int result = reminderDialog.open();
if (result == Window.OK) {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = null;
if (element instanceof AbstractTask) {
task = (AbstractTask) element;
}
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderDialog.getDate());
}
}
}
};
action.setText(LABEL_CALENDAR);
// action.setImageDescriptor(TasksUiImages.CALENDAR);
// action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null, false);
}
}
};
action.setText(LABEL_NOT_SCHEDULED);
// action.setImageDescriptor(TasksUiImages.REMOVE);
if (singleTaskSelection != null) {
if (singleTaskSelection.getScheduledForDate() == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
private void getDayLabel(int i, Action action) {
if (i > 8) {
// rotates up to 7 days ahead
i = i - 7;
}
switch (i) {
case Calendar.MONDAY:
action.setText("Monday");
break;
case Calendar.TUESDAY:
action.setText("Tuesday");
break;
case Calendar.WEDNESDAY:
action.setText("Wednesday");
break;
case Calendar.THURSDAY:
action.setText("Thursday");
break;
case Calendar.FRIDAY:
action.setText("Friday");
break;
case Calendar.SATURDAY:
action.setText("Saturday");
break;
case 8:
action.setText("Sunday");
break;
default:
break;
}
}
private boolean canSchedule(AbstractTaskContainer singleSelection, List<AbstractTaskContainer> elements) {
if (singleSelection instanceof AbstractTask) {
return ((!((AbstractTask) singleSelection).isCompleted()) || elements.size() > 0);
} else {
return elements.size() > 0;
}
// return (singleSelection != null && !singleSelection.isCompleted())
// || elements.size() > 0;
}
}
| true | true | public MenuManager getSubMenuManager(final List<AbstractTaskContainer> selectedElements) {
final TaskListManager tasklistManager = TasksUiPlugin.getTaskListManager();
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
subMenuManager.setVisible(selectedElements.size() > 0 && selectedElements.get(0) instanceof AbstractTask);// !(selectedElements.get(0) instanceof AbstractTaskContainer || selectedElements.get(0) instanceof AbstractRepositoryQuery));
AbstractTaskContainer singleSelection = null;
if (selectedElements.size() == 1) {
AbstractTaskContainer selectedElement = selectedElements.get(0);
if (selectedElement instanceof AbstractTask) {
singleSelection = selectedElement;
}
}
final AbstractTask singleTaskSelection = tasklistManager.getTaskForElement(singleSelection, false);
final List<AbstractTaskContainer> taskListElementsToSchedule = new ArrayList<AbstractTaskContainer>();
for (AbstractTaskContainer selectedElement : selectedElements) {
if (selectedElement instanceof AbstractTask) {
taskListElementsToSchedule.add(selectedElement);
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledEndOfDay(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
action.setText(LABEL_TODAY);
action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && (TasksUiPlugin.getTaskListManager().isScheduledForToday(singleTaskSelection)
|| singleTaskSelection.isPastReminder())) {
action.setChecked(true);
}
// subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
for (int i = today + 1; i <= today + 7; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
int dueIn = day - today;
TasksUiPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
getDayLabel(i, action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null
&& !singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, i - today);
now.getTime();
Calendar then = Calendar.getInstance();
then.setTime(singleTaskSelection.getScheduledForDate());
if(now.get(Calendar.DAY_OF_MONTH) == then.get(Calendar.DAY_OF_MONTH)) {
action.setChecked(true);
}
}
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
TaskActivityUtil.snapStartOfWorkWeek(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, reminderCalendar.getTime(), true);
}
}
}
};
action.setText(LABEL_THIS_WEEK);
action.setImageDescriptor(TasksUiImages.SCHEDULE_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate() && TasksUiPlugin.getTaskListManager().isScheduledForThisWeek(singleTaskSelection)) {
action.setChecked(true);
}
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
Calendar startNextWeek = Calendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(startNextWeek);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, startNextWeek.getTime(), true);
}
}
};
action.setText(LABEL_NEXT_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate()
&& TasksUiPlugin.getTaskListManager().isScheduledAfterThisWeek(singleTaskSelection)
&& !TasksUiPlugin.getTaskListManager().isScheduledForLater(singleTaskSelection)) {
action.setChecked(true);
}
subMenuManager.add(action);
// 2 weeks
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
Calendar twoWeeks = TaskActivityUtil.getCalendar();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(twoWeeks);
twoWeeks.add(Calendar.DAY_OF_MONTH, 7);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, twoWeeks.getTime(), true);
}
}
}
};
action.setText(LABEL_TWO_WEEKS);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null && singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
Calendar end = TaskActivityUtil.getCalendar();
end.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
TaskActivityUtil.snapEndOfWeek(end);
if (TaskActivityUtil.isBetween(time, start, end)) {
action.setChecked(true);
}
}
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
start.add(Calendar.WEEK_OF_MONTH, 1);
if (time.compareTo(start) >= 0) {
// future
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(LABEL_FUTURE);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
theCalendar.setTime(singleTaskSelection.getScheduledForDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), theCalendar, DatePicker.TITLE_DIALOG, false);
int result = reminderDialog.open();
if (result == Window.OK) {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = null;
if (element instanceof AbstractTask) {
task = (AbstractTask) element;
}
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderDialog.getDate());
}
}
}
};
action.setText(LABEL_CALENDAR);
// action.setImageDescriptor(TasksUiImages.CALENDAR);
// action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null, false);
}
}
};
action.setText(LABEL_NOT_SCHEDULED);
// action.setImageDescriptor(TasksUiImages.REMOVE);
if (singleTaskSelection != null) {
if (singleTaskSelection.getScheduledForDate() == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
| public MenuManager getSubMenuManager(final List<AbstractTaskContainer> selectedElements) {
final TaskListManager tasklistManager = TasksUiPlugin.getTaskListManager();
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
subMenuManager.setVisible(selectedElements.size() > 0 && selectedElements.get(0) instanceof AbstractTask);// !(selectedElements.get(0) instanceof AbstractTaskContainer || selectedElements.get(0) instanceof AbstractRepositoryQuery));
AbstractTaskContainer singleSelection = null;
if (selectedElements.size() == 1) {
AbstractTaskContainer selectedElement = selectedElements.get(0);
if (selectedElement instanceof AbstractTask) {
singleSelection = selectedElement;
}
}
final AbstractTask singleTaskSelection = tasklistManager.getTaskForElement(singleSelection, false);
final List<AbstractTaskContainer> taskListElementsToSchedule = new ArrayList<AbstractTaskContainer>();
for (AbstractTaskContainer selectedElement : selectedElements) {
if (selectedElement instanceof AbstractTask) {
taskListElementsToSchedule.add(selectedElement);
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledEndOfDay(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
action.setText(LABEL_TODAY);
action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && (TasksUiPlugin.getTaskListManager().isScheduledForToday(singleTaskSelection)
|| (singleTaskSelection.isPastReminder() && !singleTaskSelection.internalIsFloatingScheduledDate()))) {
action.setChecked(true);
}
// subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
for (int i = today + 1; i <= today + 7; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
int dueIn = day - today;
TasksUiPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderCalendar.getTime());
}
}
};
getDayLabel(i, action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null
&& !singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DAY_OF_MONTH, i - today);
now.getTime();
Calendar then = Calendar.getInstance();
then.setTime(singleTaskSelection.getScheduledForDate());
if(now.get(Calendar.DAY_OF_MONTH) == then.get(Calendar.DAY_OF_MONTH)) {
action.setChecked(true);
}
}
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = TaskActivityUtil.getCalendar();
TaskActivityUtil.snapStartOfWorkWeek(reminderCalendar);
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, reminderCalendar.getTime(), true);
}
}
}
};
action.setText(LABEL_THIS_WEEK);
action.setImageDescriptor(TasksUiImages.SCHEDULE_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate() && TasksUiPlugin.getTaskListManager().isScheduledForThisWeek(singleTaskSelection)) {
action.setChecked(true);
}
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
Calendar startNextWeek = Calendar.getInstance();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(startNextWeek);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, startNextWeek.getTime(), true);
}
}
};
action.setText(LABEL_NEXT_WEEK);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.internalIsFloatingScheduledDate()
&& TasksUiPlugin.getTaskListManager().isScheduledAfterThisWeek(singleTaskSelection)
&& !TasksUiPlugin.getTaskListManager().isScheduledForLater(singleTaskSelection)) {
action.setChecked(true);
}
subMenuManager.add(action);
// 2 weeks
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
if(task != null) {
Calendar twoWeeks = TaskActivityUtil.getCalendar();
TasksUiPlugin.getTaskListManager().setScheduledNextWeek(twoWeeks);
twoWeeks.add(Calendar.DAY_OF_MONTH, 7);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, twoWeeks.getTime(), true);
}
}
}
};
action.setText(LABEL_TWO_WEEKS);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null && singleTaskSelection.internalIsFloatingScheduledDate()) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
Calendar end = TaskActivityUtil.getCalendar();
end.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
TaskActivityUtil.snapEndOfWeek(end);
if (TaskActivityUtil.isBetween(time, start, end)) {
action.setChecked(true);
}
}
subMenuManager.add(action);
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
Calendar time = TaskActivityUtil.getCalendar();
time.setTime(singleTaskSelection.getScheduledForDate());
Calendar start = TaskActivityUtil.getCalendar();
start.setTime(TasksUiPlugin.getTaskActivityManager().getActivityFuture().getStart().getTime());
start.add(Calendar.WEEK_OF_MONTH, 1);
if (time.compareTo(start) >= 0) {
// future
action = new Action() {
@Override
public void run() {
// ignore
}
};
action.setChecked(true);
action.setText(LABEL_FUTURE);
subMenuManager.add(action);
}
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if (singleTaskSelection != null && singleTaskSelection.getScheduledForDate() != null) {
theCalendar.setTime(singleTaskSelection.getScheduledForDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), theCalendar, DatePicker.TITLE_DIALOG, false);
int result = reminderDialog.open();
if (result == Window.OK) {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = null;
if (element instanceof AbstractTask) {
task = (AbstractTask) element;
}
TasksUiPlugin.getTaskListManager().setScheduledFor(task, reminderDialog.getDate());
}
}
}
};
action.setText(LABEL_CALENDAR);
// action.setImageDescriptor(TasksUiImages.CALENDAR);
// action.setImageDescriptor(TasksUiImages.SCHEDULE_DAY);
action.setEnabled(canSchedule(singleSelection, taskListElementsToSchedule));
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
for (AbstractTaskContainer element : taskListElementsToSchedule) {
AbstractTask task = tasklistManager.getTaskForElement(element, true);
TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null, false);
}
}
};
action.setText(LABEL_NOT_SCHEDULED);
// action.setImageDescriptor(TasksUiImages.REMOVE);
if (singleTaskSelection != null) {
if (singleTaskSelection.getScheduledForDate() == null) {
action.setChecked(true);
}
}
subMenuManager.add(action);
return subMenuManager;
}
|
diff --git a/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/jobs/Jobs.java b/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/jobs/Jobs.java
index af15fbf06..6327c9b6e 100644
--- a/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/jobs/Jobs.java
+++ b/framework/pull-agent/src/main/java/org/apache/manifoldcf/crawler/jobs/Jobs.java
@@ -1,2931 +1,2931 @@
/* $Id: Jobs.java 991295 2010-08-31 19:12:14Z kwright $ */
/**
* 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.manifoldcf.crawler.jobs;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.CacheKeyFactory;
import java.util.*;
/** This class manages the jobs table.
*
* <br><br>
* <b>jobs</b>
* <table border="1" cellpadding="3" cellspacing="0">
* <tr class="TableHeadingColor">
* <th>Field</th><th>Type</th><th>Description </th>
* <tr><td>id</td><td>BIGINT</td><td>Primary Key</td></tr>
* <tr><td>description</td><td>VARCHAR(255)</td><td></td></tr>
* <tr><td>status</td><td>CHAR(1)</td><td>operational field</td></tr>
* <tr><td>lasttime</td><td>BIGINT</td><td>operational field</td></tr>
* <tr><td>starttime</td><td>BIGINT</td><td>operational field</td></tr>
* <tr><td>lastchecktime</td><td>BIGINT</td><td>operational field</td></tr>
* <tr><td>endtime</td><td>BIGINT</td><td>operational field</td></tr>
* <tr><td>docspec</td><td>LONGTEXT</td><td></td></tr>
* <tr><td>outputspec</td><td>LONGTEXT</td><td></td></tr>
* <tr><td>connectionname</td><td>VARCHAR(32)</td><td>Reference:repoconnections.connectionname</td></tr>
* <tr><td>outputname</td><td>VARCHAR(32)</td><td>Reference:outputconnections.connectionname</td></tr>
* <tr><td>type</td><td>CHAR(1)</td><td></td></tr>
* <tr><td>intervaltime</td><td>BIGINT</td><td></td></tr>
* <tr><td>expirationtime</td><td>BIGINT</td><td></td></tr>
* <tr><td>windowend</td><td>BIGINT</td><td></td></tr>
* <tr><td>priority</td><td>BIGINT</td><td></td></tr>
* <tr><td>startmethod</td><td>CHAR(1)</td><td></td></tr>
* <tr><td>errortext</td><td>LONGTEXT</td><td></td></tr>
* <tr><td>reseedinterval</td><td>BIGINT</td><td></td></tr>
* <tr><td>reseedtime</td><td>BIGINT</td><td></td></tr>
* <tr><td>hopcountmode</td><td>CHAR(1)</td><td></td></tr>
* </table>
* <br><br>
*
*/
public class Jobs extends org.apache.manifoldcf.core.database.BaseTable
{
public static final String _rcsid = "@(#)$Id: Jobs.java 991295 2010-08-31 19:12:14Z kwright $";
// Status field values
//
// There are some themes in this state diagram. For instance, for all active states there's a corresponding "active seeding" state, which
// indicates that automatic seeding is taking place at that time. Also, the "pause a job" sequence goes from "pausing" to "paused", while
// "resuming a job" goes from "resuming" to "active". This is complicated by the fact that entering the "activewait" state is very similar
// to entering the "paused" state, in that the job must go first to the "active waiting" state and then to the "active wait" state, but it
// is completely orthogonal to the "paused" state, because one is triggered automatically and the other by human control. Similarly,
// resuming from an "active wait" state must transition through another state to return to the "active" state.
//
// However, it is only certain transitions that require special states. For example, leaving a waited/paused state and returning to "active"
// does something, as does entering either active wait or paused. Also transitions between these states do NOT require intermediates.
// The state diagram reflects that. But it also has to reflect that during the "pausing" stage, "activewait" may occur, and visa versa.
public static final int STATUS_INACTIVE = 0; // Not running
public static final int STATUS_ACTIVE = 1; // Active, within a valid window
public static final int STATUS_ACTIVESEEDING = 2; // Same as active, but seeding process is currently active also.
public static final int STATUS_ACTIVEWAITING = 3; // In the process of waiting due to window expiration; will enter STATUS_ACTIVEWAIT when done.
public static final int STATUS_ACTIVEWAITINGSEEDING = 4; // In the process of waiting due to window exp, also seeding; will enter STATUS_ACTIVEWAITSEEDING when done.
public static final int STATUS_ACTIVEWAIT = 5; // Active, but paused due to window expiration
public static final int STATUS_ACTIVEWAITSEEDING = 6; // Same as active wait, but seeding process is currently active also.
public static final int STATUS_PAUSING = 7; // In the process of pausing a job; will enter STATUS_PAUSED when done.
public static final int STATUS_PAUSINGSEEDING = 8; // In the process of pausing a job, but seeding also; will enter STATUS_PAUSEDSEEDING when done.
public static final int STATUS_PAUSINGWAITING = 9; // In the process of pausing a job; will enter STATUS_PAUSEDWAIT when done.
public static final int STATUS_PAUSINGWAITINGSEEDING = 10; // In the process of pausing a job, but seeding also; will enter STATUS_PAUSEDWAITSEEDING when done.
public static final int STATUS_PAUSED = 11; // Paused, but within a valid window
public static final int STATUS_PAUSEDSEEDING = 12; // Same as paused, but seeding process is currently active also.
public static final int STATUS_PAUSEDWAIT = 13; // Paused, and outside of window expiration
public static final int STATUS_PAUSEDWAITSEEDING = 14; // Same as paused wait, but seeding process is currently active also.
public static final int STATUS_SHUTTINGDOWN = 15; // Done, except for process cleanup
public static final int STATUS_RESUMING = 16; // In the process of resuming a paused or waited job; will enter STATUS_ACTIVE when done
public static final int STATUS_RESUMINGSEEDING = 17; // In the process of resuming a paused or waited job, seeding process active too; will enter STATUS_ACTIVESEEDING when done.
public static final int STATUS_ABORTING = 18; // Aborting (not yet aborted because documents still being processed)
public static final int STATUS_STARTINGUP = 19; // Loading the queue (will go into ACTIVE if successful, or INACTIVE if not)
public static final int STATUS_STARTINGUPMINIMAL = 20; // Loading the queue for minimal job run (will go into ACTIVE if successful, or INACTIVE if not)
public static final int STATUS_ABORTINGSTARTINGUP = 21; // Will abort once the queue loading is complete
public static final int STATUS_ABORTINGSTARTINGUPMINIMAL = 22; // Will abort once the queue loading is complete
public static final int STATUS_READYFORSTARTUP = 23; // Job is marked for minimal startup; startup thread has not taken it yet.
public static final int STATUS_READYFORSTARTUPMINIMAL = 24; // Job is marked for startup; startup thread has not taken it yet.
public static final int STATUS_READYFORDELETE = 25; // Job is marked for delete; delete thread has not taken it yet.
public static final int STATUS_ABORTINGSEEDING = 26; // Same as aborting, but seeding process is currently active also.
public static final int STATUS_ABORTINGFORRESTART = 27; // Same as aborting, except after abort is complete startup will happen.
public static final int STATUS_ABORTINGFORRESTARTMINIMAL = 28; // Same as aborting, except after abort is complete startup will happen.
public static final int STATUS_ABORTINGFORRESTARTSEEDING = 29; // Seeding version of aborting for restart
public static final int STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL = 30; // Seeding version of aborting for restart
public static final int STATUS_ABORTINGSTARTINGUPFORRESTART = 31; // Starting up version of aborting for restart
public static final int STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL = 32; // Starting up version of aborting for restart
public static final int STATUS_READYFORNOTIFY = 33; // Job is ready to be notified of completion
public static final int STATUS_NOTIFYINGOFCOMPLETION = 34; // Notifying connector of terminating job (either aborted, or finished)
public static final int STATUS_DELETING = 35; // The job is deleting.
public static final int STATUS_DELETESTARTINGUP = 36; // The delete is starting up.
// These statuses have to do with whether a job has an installed underlying connector or not.
// There are two reasons to have a special state here: (1) if the behavior of the crawler differs, or (2) if the
// UI would present something different.
//
// For the base states, such as for an inactive job, I've chosen not to have an "uninstalled" version of the state, for now.
// This is because I believe that feedback will be adequate without such states.
// But, since there is no indication in the jobs table of an uninstalled connector for such jobs, the code which starts
// jobs up (or otherwise would enter any state that has a corresponding special state) must check to see if the underlying
// connector exists before deciding what state to put the job into.
public static final int STATUS_ACTIVE_UNINSTALLED = 37; // Active, but repository connector not installed
public static final int STATUS_ACTIVESEEDING_UNINSTALLED = 38; // Active and seeding, but repository connector not installed
public static final int STATUS_ACTIVE_NOOUTPUT = 39; // Active, but output connector not installed
public static final int STATUS_ACTIVESEEDING_NOOUTPUT = 40; // Active and seeding, but output connector not installed
public static final int STATUS_ACTIVE_NEITHER = 41; // Active, but neither repository connector nor output connector installed
public static final int STATUS_ACTIVESEEDING_NEITHER = 42; // Active and seeding, but neither repository connector nor output connector installed
public static final int STATUS_DELETING_NOOUTPUT = 43; // Job is being deleted but there's no output connector installed
// Type field values
public static final int TYPE_CONTINUOUS = IJobDescription.TYPE_CONTINUOUS;
public static final int TYPE_SPECIFIED = IJobDescription.TYPE_SPECIFIED;
// Start method field values
public static final int START_WINDOWBEGIN = IJobDescription.START_WINDOWBEGIN;
public static final int START_WINDOWINSIDE = IJobDescription.START_WINDOWINSIDE;
public static final int START_DISABLE = IJobDescription.START_DISABLE;
// Hopcount mode values
public static final int HOPCOUNT_ACCURATE = IJobDescription.HOPCOUNT_ACCURATE;
public static final int HOPCOUNT_NODELETE = IJobDescription.HOPCOUNT_NODELETE;
public static final int HOPCOUNT_NEVERDELETE = IJobDescription.HOPCOUNT_NEVERDELETE;
// Field names
public final static String idField = "id";
public final static String descriptionField = "description";
public final static String documentSpecField = "docspec";
public final static String connectionNameField = "connectionname";
public final static String outputSpecField = "outputspec";
public final static String outputNameField = "outputname";
public final static String typeField = "type";
/** This is the minimum reschedule interval for a document being crawled adaptively (in ms.) */
public final static String intervalField = "intervaltime";
/** This is the expiration time of documents for a given job (in ms.) */
public final static String expirationField = "expirationtime";
/** This is the job's priority vs. other jobs. */
public final static String priorityField = "priority";
/** How/when to start the job */
public final static String startMethodField = "startmethod";
/** If this is an adaptive job, what should the reseed interval be (in milliseconds) */
public final static String reseedIntervalField = "reseedinterval";
// These fields are NOT part of the definition, but are operational
/** Status of this job. */
public final static String statusField = "status";
/** The last time this job was assessed, in ms. since epoch. */
public final static String lastTimeField = "lasttime";
/** If active, paused, activewait, or pausedwait, the start time of the current session, else null. */
public final static String startTimeField = "starttime";
/** The time of the LAST session, if any. This is the place where the "last repository change check time"
* is gotten from. */
public final static String lastCheckTimeField = "lastchecktime";
/** If inactive, the end time of the LAST session, if any. */
public final static String endTimeField = "endtime";
/** If non-null, this is the time that the current execution window closes, in ms since epoch. */
public final static String windowEndField = "windowend";
/** If non-null, this is the last error that occurred (which aborted the last task, either running the job or doing the
* delete cleanup). */
public final static String errorField = "errortext";
/** For an adaptive job, this is the next time to reseed the job. */
public final static String reseedTimeField = "reseedtime";
/** For a job whose connector supports hopcounts, this describes how those hopcounts are handled. */
public final static String hopcountModeField = "hopcountmode";
protected static Map statusMap;
protected static Map typeMap;
protected static Map startMap;
protected static Map hopmodeMap;
static
{
statusMap = new HashMap();
statusMap.put("N",new Integer(STATUS_INACTIVE));
statusMap.put("A",new Integer(STATUS_ACTIVE));
statusMap.put("P",new Integer(STATUS_PAUSED));
statusMap.put("S",new Integer(STATUS_SHUTTINGDOWN));
statusMap.put("s",new Integer(STATUS_READYFORNOTIFY));
statusMap.put("n",new Integer(STATUS_NOTIFYINGOFCOMPLETION));
statusMap.put("W",new Integer(STATUS_ACTIVEWAIT));
statusMap.put("Z",new Integer(STATUS_PAUSEDWAIT));
statusMap.put("X",new Integer(STATUS_ABORTING));
statusMap.put("B",new Integer(STATUS_STARTINGUP));
statusMap.put("b",new Integer(STATUS_STARTINGUPMINIMAL));
statusMap.put("Q",new Integer(STATUS_ABORTINGSTARTINGUP));
statusMap.put("q",new Integer(STATUS_ABORTINGSTARTINGUPMINIMAL));
statusMap.put("C",new Integer(STATUS_READYFORSTARTUP));
statusMap.put("c",new Integer(STATUS_READYFORSTARTUPMINIMAL));
statusMap.put("E",new Integer(STATUS_READYFORDELETE));
statusMap.put("V",new Integer(STATUS_DELETESTARTINGUP));
statusMap.put("e",new Integer(STATUS_DELETING));
statusMap.put("Y",new Integer(STATUS_ABORTINGFORRESTART));
statusMap.put("M",new Integer(STATUS_ABORTINGFORRESTARTMINIMAL));
statusMap.put("T",new Integer(STATUS_ABORTINGSTARTINGUPFORRESTART));
statusMap.put("t",new Integer(STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL));
statusMap.put("a",new Integer(STATUS_ACTIVESEEDING));
statusMap.put("x",new Integer(STATUS_ABORTINGSEEDING));
statusMap.put("p",new Integer(STATUS_PAUSEDSEEDING));
statusMap.put("w",new Integer(STATUS_ACTIVEWAITSEEDING));
statusMap.put("z",new Integer(STATUS_PAUSEDWAITSEEDING));
statusMap.put("y",new Integer(STATUS_ABORTINGFORRESTARTSEEDING));
statusMap.put("m",new Integer(STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL));
statusMap.put("H",new Integer(STATUS_ACTIVEWAITING));
statusMap.put("h",new Integer(STATUS_ACTIVEWAITINGSEEDING));
statusMap.put("F",new Integer(STATUS_PAUSING));
statusMap.put("f",new Integer(STATUS_PAUSINGSEEDING));
statusMap.put("G",new Integer(STATUS_PAUSINGWAITING));
statusMap.put("g",new Integer(STATUS_PAUSINGWAITINGSEEDING));
statusMap.put("I",new Integer(STATUS_RESUMING));
statusMap.put("i",new Integer(STATUS_RESUMINGSEEDING));
// These are the uninstalled states. The values, I'm afraid, are pretty random.
statusMap.put("R",new Integer(STATUS_ACTIVE_UNINSTALLED));
statusMap.put("r",new Integer(STATUS_ACTIVESEEDING_UNINSTALLED));
statusMap.put("O",new Integer(STATUS_ACTIVE_NOOUTPUT));
statusMap.put("o",new Integer(STATUS_ACTIVESEEDING_NOOUTPUT));
statusMap.put("U",new Integer(STATUS_ACTIVE_NEITHER));
statusMap.put("u",new Integer(STATUS_ACTIVESEEDING_NEITHER));
statusMap.put("D",new Integer(STATUS_DELETING_NOOUTPUT));
typeMap = new HashMap();
typeMap.put("C",new Integer(TYPE_CONTINUOUS));
typeMap.put("S",new Integer(TYPE_SPECIFIED));
startMap = new HashMap();
startMap.put("B",new Integer(START_WINDOWBEGIN));
startMap.put("I",new Integer(START_WINDOWINSIDE));
startMap.put("D",new Integer(START_DISABLE));
hopmodeMap = new HashMap();
hopmodeMap.put("A",new Integer(HOPCOUNT_ACCURATE));
hopmodeMap.put("N",new Integer(HOPCOUNT_NODELETE));
hopmodeMap.put("V",new Integer(HOPCOUNT_NEVERDELETE));
}
// Local variables
protected ICacheManager cacheManager;
protected ScheduleManager scheduleManager;
protected HopFilterManager hopFilterManager;
protected ForcedParamManager forcedParamManager;
protected IOutputConnectionManager outputMgr;
protected IRepositoryConnectionManager connectionMgr;
protected IThreadContext threadContext;
/** Constructor.
*@param database is the database handle.
*/
public Jobs(IThreadContext threadContext, IDBInterface database)
throws ManifoldCFException
{
super(database,"jobs");
this.threadContext = threadContext;
scheduleManager = new ScheduleManager(threadContext,database);
hopFilterManager = new HopFilterManager(threadContext,database);
forcedParamManager = new ForcedParamManager(threadContext,database);
cacheManager = CacheManagerFactory.make(threadContext);
outputMgr = OutputConnectionManagerFactory.make(threadContext);
connectionMgr = RepositoryConnectionManagerFactory.make(threadContext);
}
/** Install or upgrade this table.
*/
public void install(String outputTableName, String outputNameField, String connectionTableName, String connectionNameField)
throws ManifoldCFException
{
// Standard practice: Have a loop around everything, in case upgrade needs it.
while (true)
{
Map existing = getTableSchema(null,null);
if (existing == null)
{
HashMap map = new HashMap();
map.put(idField,new ColumnDescription("BIGINT",true,false,null,null,false));
map.put(descriptionField,new ColumnDescription("VARCHAR(255)",false,false,null,null,false));
map.put(statusField,new ColumnDescription("CHAR(1)",false,false,null,null,false));
map.put(lastTimeField,new ColumnDescription("BIGINT",false,false,null,null,false));
map.put(startTimeField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(lastCheckTimeField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(endTimeField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(documentSpecField,new ColumnDescription("LONGTEXT",false,true,null,null,false));
map.put(outputSpecField,new ColumnDescription("LONGTEXT",false,true,null,null,false));
map.put(this.connectionNameField,new ColumnDescription("VARCHAR(32)",false,false,connectionTableName,connectionNameField,false));
map.put(this.outputNameField,new ColumnDescription("VARCHAR(32)",false,false,outputTableName,outputNameField,false));
map.put(typeField,new ColumnDescription("CHAR(1)",false,false,null,null,false));
map.put(intervalField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(expirationField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(windowEndField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(priorityField,new ColumnDescription("BIGINT",false,false,null,null,false));
map.put(startMethodField,new ColumnDescription("CHAR(1)",false,false,null,null,false));
map.put(errorField,new ColumnDescription("LONGTEXT",false,true,null,null,false));
map.put(reseedIntervalField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(reseedTimeField,new ColumnDescription("BIGINT",false,true,null,null,false));
map.put(hopcountModeField,new ColumnDescription("CHAR(1)",false,true,null,null,false));
performCreate(map,null);
}
else
{
// Do any needed upgrades
}
// Handle related tables
scheduleManager.install(getTableName(),idField);
hopFilterManager.install(getTableName(),idField);
forcedParamManager.install(getTableName(),idField);
// Index management
IndexDescription statusIndex = new IndexDescription(false,new String[]{statusField,idField,priorityField});
IndexDescription connectionIndex = new IndexDescription(false,new String[]{connectionNameField});
IndexDescription outputIndex = new IndexDescription(false,new String[]{outputNameField});
// Get rid of indexes that shouldn't be there
Map indexes = getTableIndexes(null,null);
Iterator iter = indexes.keySet().iterator();
while (iter.hasNext())
{
String indexName = (String)iter.next();
IndexDescription id = (IndexDescription)indexes.get(indexName);
if (statusIndex != null && id.equals(statusIndex))
statusIndex = null;
else if (connectionIndex != null && id.equals(connectionIndex))
connectionIndex = null;
else if (outputIndex != null && id.equals(outputIndex))
outputIndex = null;
else if (indexName.indexOf("_pkey") == -1)
// This index shouldn't be here; drop it
performRemoveIndex(indexName);
}
// Add the ones we didn't find
if (statusIndex != null)
performAddIndex(null,statusIndex);
if (connectionIndex != null)
performAddIndex(null,connectionIndex);
if (outputIndex != null)
performAddIndex(null,outputIndex);
break;
}
}
/** Uninstall.
*/
public void deinstall()
throws ManifoldCFException
{
beginTransaction();
try
{
forcedParamManager.deinstall();
hopFilterManager.deinstall();
scheduleManager.deinstall();
performDrop(null);
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Come up with a maximum time (in minutes) for re-analyzing tables.
*@return the time, in minutes.
*/
public int getAnalyzeTime()
throws ManifoldCFException
{
// Since we never expect jobs to grow rapidly, every 24hrs should always be fine
return 24 * 60;
}
/** Analyze job tables that need analysis.
*/
public void analyzeTables()
throws ManifoldCFException
{
analyzeTable();
}
/** Read schedule records for a specified set of jobs. Cannot use caching!
*/
public ScheduleRecord[][] readScheduleRecords(Long[] jobIDs)
throws ManifoldCFException
{
Map uniqueIDs = new HashMap();
int i = 0;
while (i < jobIDs.length)
{
Long jobID = jobIDs[i++];
uniqueIDs.put(jobID,jobID);
}
HashMap returnValues = new HashMap();
beginTransaction();
try
{
ArrayList params = new ArrayList();
int j = 0;
int maxIn = scheduleManager.maxClauseGetRowsAlternate();
Iterator iter = uniqueIDs.keySet().iterator();
while (iter.hasNext())
{
if (j == maxIn)
{
scheduleManager.getRowsAlternate(returnValues,params);
params.clear();
j = 0;
}
params.add(iter.next());
j++;
}
if (j > 0)
scheduleManager.getRowsAlternate(returnValues,params);
}
catch (Error e)
{
signalRollback();
throw e;
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
// Fill the return array
ScheduleRecord[][] rval = new ScheduleRecord[jobIDs.length][];
i = 0;
while (i < jobIDs.length)
{
ArrayList al = (ArrayList)returnValues.get(jobIDs[i]);
ScheduleRecord[] srList;
if (al == null)
srList = new ScheduleRecord[0];
else
{
srList = new ScheduleRecord[al.size()];
int k = 0;
while (k < srList.length)
{
srList[k] = (ScheduleRecord)al.get(k);
k++;
}
}
rval[i++] = srList;
}
return rval;
}
/** Get a list of all jobs which are not in the process of being deleted already.
*@return the array of all jobs.
*/
public IJobDescription[] getAll()
throws ManifoldCFException
{
// Begin transaction
beginTransaction();
try
{
// Put together cache key
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getJobsKey());
ssb.add(getJobStatusKey());
StringSet cacheKeys = new StringSet(ssb);
ArrayList list = new ArrayList();
list.add(statusToString(STATUS_READYFORDELETE));
list.add(statusToString(STATUS_DELETESTARTINGUP));
list.add(statusToString(STATUS_DELETING));
list.add(statusToString(STATUS_DELETING_NOOUTPUT));
IResultSet set = performQuery("SELECT "+idField+","+descriptionField+" FROM "+
getTableName()+" WHERE "+statusField+"!=? AND "+statusField+"!=? AND "+statusField+"!=? AND "+statusField+"!=?"+
" ORDER BY "+descriptionField+" ASC",list,cacheKeys,null);
// Convert to an array of id's, and then load them
Long[] ids = new Long[set.getRowCount()];
boolean[] readOnlies = new boolean[set.getRowCount()];
int i = 0;
while (i < ids.length)
{
IResultRow row = set.getRow(i);
ids[i] = (Long)row.getValue(idField);
readOnlies[i++] = true;
}
return loadMultiple(ids,readOnlies);
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Get a list of active job identifiers and their associated connection names.
*@return a resultset with "jobid" and "connectionname" fields.
*/
public IResultSet getActiveJobConnections()
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new MultiClause(statusField,new Object[]{
statusToString(STATUS_ACTIVE),
statusToString(STATUS_ACTIVESEEDING)})});
return performQuery("SELECT "+idField+" AS jobid,"+connectionNameField+" AS connectionname FROM "+getTableName()+" WHERE "+
query,list,null,null);
}
/** Get unique connection names for all active jobs.
*@return the array of connection names corresponding to active jobs.
*/
public String[] getActiveConnectionNames()
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new MultiClause(statusField,new Object[]{
statusToString(STATUS_ACTIVE),
statusToString(STATUS_ACTIVESEEDING)})});
IResultSet set = performQuery("SELECT DISTINCT "+connectionNameField+" FROM "+getTableName()+" WHERE "+
query,list,null,null);
String[] rval = new String[set.getRowCount()];
int i = 0;
while (i < set.getRowCount())
{
IResultRow row = set.getRow(i);
rval[i] = (String)row.getValue(connectionNameField);
i++;
}
return rval;
}
/** Are there any jobs that have a specified priority level */
public boolean hasPriorityJobs(int priority)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new MultiClause(statusField,new Object[]{
statusToString(STATUS_ACTIVE),
statusToString(STATUS_ACTIVESEEDING)})});
IResultSet set = performQuery("SELECT * FROM "+getTableName()+" WHERE "+query+" AND "+priorityField+"="+Integer.toString(priority)+
" "+constructOffsetLimitClause(0,1),list,null,null,1);
return set.getRowCount() > 0;
}
/** Create a job.
*/
public IJobDescription create()
throws ManifoldCFException
{
JobDescription rval = new JobDescription();
rval.setIsNew(true);
rval.setID(new Long(IDFactory.make(threadContext)));
return rval;
}
/** Delete a job. This is not enough by itself; the queue entries also need to be deleted.
*@param id is the job id.
*/
public void delete(Long id)
throws ManifoldCFException
{
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getJobsKey());
ssb.add(getJobStatusKey());
ssb.add(getJobIDKey(id));
StringSet cacheKeys = new StringSet(ssb);
beginTransaction();
try
{
scheduleManager.deleteRows(id);
hopFilterManager.deleteRows(id);
forcedParamManager.deleteRows(id);
ArrayList params = new ArrayList();
String query = buildConjunctionClause(params,new ClauseDescription[]{
new UnitaryClause(idField,id)});
performDelete("WHERE "+query,params,cacheKeys);
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Load a job for editing.
*@param id is the job id.
*@return the editable job description.
*/
public IJobDescription load(Long id, boolean readOnly)
throws ManifoldCFException
{
return loadMultiple(new Long[]{id}, new boolean[]{readOnly})[0];
}
/** Load multiple jobs for editing.
*@param ids is the set of id's to load
*@param readOnlies are boolean values, set to true if the job description to be read is to be designated "read only".
*@return the array of objects, in order.
*/
public IJobDescription[] loadMultiple(Long[] ids, boolean[] readOnlies)
throws ManifoldCFException
{
// Build description objects
JobObjectDescription[] objectDescriptions = new JobObjectDescription[ids.length];
int i = 0;
StringSetBuffer ssb = new StringSetBuffer();
while (i < ids.length)
{
ssb.clear();
ssb.add(getJobIDKey(ids[i]));
objectDescriptions[i] = new JobObjectDescription(ids[i],new StringSet(ssb));
i++;
}
JobObjectExecutor exec = new JobObjectExecutor(this,objectDescriptions);
cacheManager.findObjectsAndExecute(objectDescriptions,null,exec,getTransactionID());
return exec.getResults(readOnlies);
}
/** Save a job description.
*@param jobDescription is the job description.
*/
public void save(IJobDescription jobDescription)
throws ManifoldCFException
{
// The invalidation keys for this are both the general and the specific.
Long id = jobDescription.getID();
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getJobsKey());
ssb.add(getJobStatusKey());
ssb.add(getJobIDKey(id));
StringSet invKeys = new StringSet(ssb);
while (true)
{
long sleepAmt = 0L;
try
{
ICacheHandle ch = cacheManager.enterCache(null,invKeys,getTransactionID());
try
{
beginTransaction();
try
{
//performLock();
// See whether the instance exists
ArrayList params = new ArrayList();
String query = buildConjunctionClause(params,new ClauseDescription[]{
new UnitaryClause(idField,id)});
IResultSet set = performQuery("SELECT * FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",params,null,null);
HashMap values = new HashMap();
values.put(descriptionField,jobDescription.getDescription());
values.put(outputNameField,jobDescription.getOutputConnectionName());
values.put(connectionNameField,jobDescription.getConnectionName());
String newOutputXML = jobDescription.getOutputSpecification().toXML();
values.put(outputSpecField,newOutputXML);
String newXML = jobDescription.getSpecification().toXML();
values.put(documentSpecField,newXML);
values.put(typeField,typeToString(jobDescription.getType()));
values.put(startMethodField,startMethodToString(jobDescription.getStartMethod()));
values.put(intervalField,jobDescription.getInterval());
values.put(reseedIntervalField,jobDescription.getReseedInterval());
values.put(expirationField,jobDescription.getExpiration());
values.put(priorityField,new Integer(jobDescription.getPriority()));
values.put(hopcountModeField,hopcountModeToString(jobDescription.getHopcountMode()));
if (set.getRowCount() > 0)
{
// Update
// We need to reset the lastCheckTimeField if there are any changes that
// could affect what set of documents we allow!!!
IResultRow row = set.getRow(0);
boolean isSame = true;
// Determine whether we need to reset the scan time for documents.
// Basically, any change to job parameters that could affect ingestion should clear isSame so that we
// relook at all the documents, not just the recent ones.
if (isSame)
{
String oldOutputSpecXML = (String)row.getValue(outputSpecField);
if (!oldOutputSpecXML.equals(newOutputXML))
isSame = false;
}
if (isSame)
{
String oldDocSpecXML = (String)row.getValue(documentSpecField);
if (!oldDocSpecXML.equals(newXML))
isSame = false;
}
if (isSame)
{
// Compare hopcount filter criteria.
Map filterRows = hopFilterManager.readRows(id);
Map newFilterRows = jobDescription.getHopCountFilters();
if (filterRows.size() != newFilterRows.size())
isSame = false;
else
{
for (String linkType : (Collection<String>)filterRows.keySet())
{
- Integer oldCount = (Integer)filterRows.get(linkType);
- Integer newCount = (Integer)newFilterRows.get(linkType);
+ Long oldCount = (Long)filterRows.get(linkType);
+ Long newCount = (Long)newFilterRows.get(linkType);
if (oldCount == null || newCount == null)
{
isSame = false;
break;
}
- else if (oldCount.intValue() != newCount.intValue())
+ else if (oldCount.longValue() != newCount.longValue())
{
isSame = false;
break;
}
}
}
}
if (!isSame)
values.put(lastCheckTimeField,null);
params.clear();
query = buildConjunctionClause(params,new ClauseDescription[]{
new UnitaryClause(idField,id)});
performUpdate(values," WHERE "+query,params,null);
scheduleManager.deleteRows(id);
hopFilterManager.deleteRows(id);
forcedParamManager.deleteRows(id);
}
else
{
// Insert
values.put(startTimeField,null);
values.put(lastCheckTimeField,null);
values.put(endTimeField,null);
values.put(statusField,statusToString(STATUS_INACTIVE));
values.put(lastTimeField,new Long(System.currentTimeMillis()));
values.put(idField,id);
performInsert(values,null);
}
// Write schedule records
scheduleManager.writeRows(id,jobDescription);
// Write hop filter rows
hopFilterManager.writeRows(id,jobDescription);
// Write forced params
forcedParamManager.writeRows(id,jobDescription);
cacheManager.invalidateKeys(ch);
break;
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
finally
{
cacheManager.leaveCache(ch);
}
}
catch (ManifoldCFException e)
{
if (e.getErrorCode() != ManifoldCFException.DATABASE_TRANSACTION_ABORT)
throw e;
sleepAmt = getSleepAmt();
continue;
}
finally
{
sleepFor(sleepAmt);
}
}
}
/** This method is called on a restart.
*/
public void restart()
throws ManifoldCFException
{
beginTransaction();
try
{
StringSet invKey = new StringSet(getJobStatusKey());
ArrayList list = new ArrayList();
HashMap map = new HashMap();
String query;
// Starting up delete goes back to just being ready for delete
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_DELETESTARTINGUP))});
map.put(statusField,statusToString(STATUS_READYFORDELETE));
performUpdate(map,"WHERE "+query,list,invKey);
// Notifying of completion goes back to just being ready for notify
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_NOTIFYINGOFCOMPLETION))});
map.put(statusField,statusToString(STATUS_READYFORNOTIFY));
performUpdate(map,"WHERE "+query,list,invKey);
// Starting up or aborting starting up goes back to just being ready
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new MultiClause(statusField,new Object[]{
statusToString(STATUS_STARTINGUP),
statusToString(STATUS_ABORTINGSTARTINGUP)})});
map.put(statusField,statusToString(STATUS_READYFORSTARTUP));
performUpdate(map,"WHERE "+query,list,invKey);
// Starting up or aborting starting up goes back to just being ready
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new MultiClause(statusField,new Object[]{
statusToString(STATUS_STARTINGUPMINIMAL),
statusToString(STATUS_ABORTINGSTARTINGUPMINIMAL)})});
map.put(statusField,statusToString(STATUS_READYFORSTARTUPMINIMAL));
performUpdate(map,"WHERE "+query,list,invKey);
// Aborting starting up for restart state goes to ABORTINGFORRESTART
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGSTARTINGUPFORRESTART))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTART));
performUpdate(map,"WHERE "+query,list,invKey);
// Aborting starting up for restart state goes to ABORTINGFORRESTART
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTARTMINIMAL));
performUpdate(map,"WHERE "+query,list,invKey);
// All seeding values return to pre-seeding values
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING))});
map.put(statusField,statusToString(STATUS_ACTIVE));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSINGSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVEWAITINGSEEDING))});
map.put(statusField,statusToString(STATUS_ACTIVEWAITING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSINGWAITINGSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSINGWAITING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_RESUMINGSEEDING))});
map.put(statusField,statusToString(STATUS_RESUMING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGSEEDING))});
map.put(statusField,statusToString(STATUS_ABORTING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGFORRESTARTSEEDING))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTART));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTARTMINIMAL));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSEDSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSED));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVEWAITSEEDING))});
map.put(statusField,statusToString(STATUS_ACTIVEWAIT));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSEDWAITSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSEDWAIT));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING_UNINSTALLED))});
map.put(statusField,statusToString(STATUS_ACTIVE_UNINSTALLED));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING_NOOUTPUT))});
map.put(statusField,statusToString(STATUS_ACTIVE_NOOUTPUT));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING_NEITHER))});
map.put(statusField,statusToString(STATUS_ACTIVE_NEITHER));
performUpdate(map,"WHERE "+query,list,invKey);
// No need to do anything to the queue; it looks like it can take care of
// itself.
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Signal to a job that its underlying output connector has gone away.
*@param jobID is the identifier of the job.
*@param oldStatusValue is the current status value for the job.
*/
public void noteOutputConnectorDeregistration(Long jobID, int oldStatusValue)
throws ManifoldCFException
{
int newStatusValue;
// The following states are special, in that when the underlying connector goes away, the jobs
// in such states are switched away to something else. There are TWO reasons that a state may be in
// this category: EITHER we don't want the job in this state to be treated in the same way if its
// connector is uninstalled, OR we need feedback for the user interface. If it's the latter situation,
// then all usages of the corresponding states will be identical - and that's in fact precisely where we
// start with in all the code.
switch (oldStatusValue)
{
case STATUS_ACTIVE:
newStatusValue = STATUS_ACTIVE_NOOUTPUT;
break;
case STATUS_ACTIVESEEDING:
newStatusValue = STATUS_ACTIVESEEDING_NOOUTPUT;
break;
case STATUS_ACTIVE_UNINSTALLED:
newStatusValue = STATUS_ACTIVE_NEITHER;
break;
case STATUS_ACTIVESEEDING_UNINSTALLED:
newStatusValue = STATUS_ACTIVESEEDING_NEITHER;
break;
case STATUS_DELETING:
newStatusValue = STATUS_DELETING_NOOUTPUT;
break;
default:
newStatusValue = oldStatusValue;
break;
}
if (newStatusValue == oldStatusValue)
return;
StringSet invKey = new StringSet(getJobStatusKey());
HashMap newValues = new HashMap();
newValues.put(statusField,statusToString(newStatusValue));
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
performUpdate(newValues,"WHERE "+query,list,invKey);
}
/** Signal to a job that its underlying output connector has returned.
*@param jobID is the identifier of the job.
*@param oldStatusValue is the current status value for the job.
*/
public void noteOutputConnectorRegistration(Long jobID, int oldStatusValue)
throws ManifoldCFException
{
int newStatusValue;
// The following states are special, in that when the underlying connector returns, the jobs
// in such states are switched back to their connector-installed value.
switch (oldStatusValue)
{
case STATUS_ACTIVE_NOOUTPUT:
newStatusValue = STATUS_ACTIVE;
break;
case STATUS_ACTIVESEEDING_NOOUTPUT:
newStatusValue = STATUS_ACTIVESEEDING;
break;
case STATUS_ACTIVE_NEITHER:
newStatusValue = STATUS_ACTIVE_UNINSTALLED;
break;
case STATUS_ACTIVESEEDING_NEITHER:
newStatusValue = STATUS_ACTIVESEEDING_UNINSTALLED;
break;
case STATUS_DELETING_NOOUTPUT:
newStatusValue = STATUS_DELETING;
break;
default:
newStatusValue = oldStatusValue;
break;
}
if (newStatusValue == oldStatusValue)
return;
StringSet invKey = new StringSet(getJobStatusKey());
HashMap newValues = new HashMap();
newValues.put(statusField,statusToString(newStatusValue));
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
performUpdate(newValues,"WHERE "+query,list,invKey);
}
/** Signal to a job that its underlying connector has gone away.
*@param jobID is the identifier of the job.
*@param oldStatusValue is the current status value for the job.
*/
public void noteConnectorDeregistration(Long jobID, int oldStatusValue)
throws ManifoldCFException
{
int newStatusValue;
// The following states are special, in that when the underlying connector goes away, the jobs
// in such states are switched away to something else. There are TWO reasons that a state may be in
// this category: EITHER we don't want the job in this state to be treated in the same way if its
// connector is uninstalled, OR we need feedback for the user interface. If it's the latter situation,
// then all usages of the corresponding states will be identical - and that's in fact precisely where we
// start with in all the code.
switch (oldStatusValue)
{
case STATUS_ACTIVE:
newStatusValue = STATUS_ACTIVE_UNINSTALLED;
break;
case STATUS_ACTIVESEEDING:
newStatusValue = STATUS_ACTIVESEEDING_UNINSTALLED;
break;
case STATUS_ACTIVE_NOOUTPUT:
newStatusValue = STATUS_ACTIVE_NEITHER;
break;
case STATUS_ACTIVESEEDING_NOOUTPUT:
newStatusValue = STATUS_ACTIVESEEDING_NEITHER;
break;
default:
newStatusValue = oldStatusValue;
break;
}
if (newStatusValue == oldStatusValue)
return;
StringSet invKey = new StringSet(getJobStatusKey());
HashMap newValues = new HashMap();
newValues.put(statusField,statusToString(newStatusValue));
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
performUpdate(newValues,"WHERE "+query,list,invKey);
}
/** Signal to a job that its underlying connector has returned.
*@param jobID is the identifier of the job.
*@param oldStatusValue is the current status value for the job.
*/
public void noteConnectorRegistration(Long jobID, int oldStatusValue)
throws ManifoldCFException
{
int newStatusValue;
// The following states are special, in that when the underlying connector returns, the jobs
// in such states are switched back to their connector-installed value.
switch (oldStatusValue)
{
case STATUS_ACTIVE_UNINSTALLED:
newStatusValue = STATUS_ACTIVE;
break;
case STATUS_ACTIVESEEDING_UNINSTALLED:
newStatusValue = STATUS_ACTIVESEEDING;
break;
case STATUS_ACTIVE_NEITHER:
newStatusValue = STATUS_ACTIVE_NOOUTPUT;
break;
case STATUS_ACTIVESEEDING_NEITHER:
newStatusValue = STATUS_ACTIVESEEDING_NOOUTPUT;
break;
default:
newStatusValue = oldStatusValue;
break;
}
if (newStatusValue == oldStatusValue)
return;
StringSet invKey = new StringSet(getJobStatusKey());
HashMap newValues = new HashMap();
newValues.put(statusField,statusToString(newStatusValue));
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
performUpdate(newValues,"WHERE "+query,list,invKey);
}
/** Note a change in connection configuration.
* This method will be called whenever a connection's configuration is modified, or when an external repository change
* is signalled.
*/
public void noteConnectionChange(String connectionName)
throws ManifoldCFException
{
// No cache keys need invalidation, since we're changing the start time, not the status.
HashMap newValues = new HashMap();
newValues.put(lastCheckTimeField,null);
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(connectionNameField,connectionName)});
performUpdate(newValues,"WHERE "+query,list,null);
}
/** Note a change in output connection configuration.
* This method will be called whenever a connection's configuration is modified, or when an external target config change
* is signalled.
*/
public void noteOutputConnectionChange(String connectionName)
throws ManifoldCFException
{
// No cache keys need invalidation, since we're changing the start time, not the status.
HashMap newValues = new HashMap();
newValues.put(lastCheckTimeField,null);
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(outputNameField,connectionName)});
performUpdate(newValues,"WHERE "+query,list,null);
}
/** Check whether a job's status indicates that it is in ACTIVE or ACTIVESEEDING state.
*/
public boolean checkJobActive(Long jobID)
throws ManifoldCFException
{
StringSet cacheKeys = new StringSet(getJobStatusKey());
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+" FROM "+
getTableName()+" WHERE "+query,list,cacheKeys,null);
if (set.getRowCount() == 0)
return false;
IResultRow row = set.getRow(0);
String statusValue = (String)row.getValue(statusField);
int status = stringToStatus(statusValue);
// Any active state in the lifecycle will do: seeding, active, active_seeding
return (status == STATUS_ACTIVE || status == STATUS_ACTIVESEEDING ||
status == STATUS_STARTINGUP || status == STATUS_STARTINGUPMINIMAL);
}
/** Reset delete startup worker thread status.
*/
public void resetDeleteStartupWorkerStatus()
throws ManifoldCFException
{
// This handles everything that the delete startup thread would resolve.
ArrayList list = new ArrayList();
HashMap map = new HashMap();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_DELETESTARTINGUP))});
map.put(statusField,statusToString(STATUS_READYFORDELETE));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Reset notification worker thread status.
*/
public void resetNotificationWorkerStatus()
throws ManifoldCFException
{
// This resets everything that the job notification thread would resolve.
ArrayList list = new ArrayList();
HashMap map = new HashMap();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_NOTIFYINGOFCOMPLETION))});
map.put(statusField,statusToString(STATUS_READYFORNOTIFY));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Reset startup worker thread status.
*/
public void resetStartupWorkerStatus()
throws ManifoldCFException
{
// We have to handle all states that the startup thread would resolve, and change them to something appropriate.
ArrayList list = new ArrayList();
HashMap map = new HashMap();
String query;
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_STARTINGUP))});
map.put(statusField,statusToString(STATUS_READYFORSTARTUP));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_STARTINGUPMINIMAL))});
map.put(statusField,statusToString(STATUS_READYFORSTARTUPMINIMAL));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new MultiClause(statusField,new Object[]{
statusToString(STATUS_ABORTINGSTARTINGUP),
statusToString(STATUS_ABORTINGSTARTINGUPMINIMAL)})});
map.put(statusField,statusToString(STATUS_ABORTING));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGSTARTINGUPFORRESTART))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTART));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTARTMINIMAL));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Reset as part of restoring seeding worker threads.
*/
public void resetSeedingWorkerStatus()
throws ManifoldCFException
{
beginTransaction();
try
{
StringSet invKey = new StringSet(getJobStatusKey());
ArrayList list = new ArrayList();
HashMap map = new HashMap();
String query;
// All seeding values return to pre-seeding values
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING))});
map.put(statusField,statusToString(STATUS_ACTIVE));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSINGSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVEWAITINGSEEDING))});
map.put(statusField,statusToString(STATUS_ACTIVEWAITING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSINGWAITINGSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSINGWAITING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_RESUMINGSEEDING))});
map.put(statusField,statusToString(STATUS_RESUMING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGSEEDING))});
map.put(statusField,statusToString(STATUS_ABORTING));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGFORRESTARTSEEDING))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTART));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL))});
map.put(statusField,statusToString(STATUS_ABORTINGFORRESTARTMINIMAL));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSEDSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSED));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVEWAITSEEDING))});
map.put(statusField,statusToString(STATUS_ACTIVEWAIT));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_PAUSEDWAITSEEDING))});
map.put(statusField,statusToString(STATUS_PAUSEDWAIT));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING_UNINSTALLED))});
map.put(statusField,statusToString(STATUS_ACTIVE_UNINSTALLED));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING_NOOUTPUT))});
map.put(statusField,statusToString(STATUS_ACTIVE_NOOUTPUT));
performUpdate(map,"WHERE "+query,list,invKey);
list.clear();
query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_ACTIVESEEDING_NEITHER))});
map.put(statusField,statusToString(STATUS_ACTIVE_NEITHER));
performUpdate(map,"WHERE "+query,list,invKey);
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Write job status and window end, and clear the endtime field. (The start time will be written
* when the job enters the "active" state.)
*@param jobID is the job identifier.
*@param windowEnd is the window end time, if any
*@param requestMinimum is true if a minimal job run is requested
*/
public void startJob(Long jobID, Long windowEnd, boolean requestMinimum)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(statusField,statusToString(requestMinimum?STATUS_READYFORSTARTUPMINIMAL:STATUS_READYFORSTARTUP));
map.put(endTimeField,null);
// Make sure error is removed (from last time)
map.put(errorField,null);
map.put(windowEndField,windowEnd);
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Put job back into active state, from the shutting-down state.
*@param jobID is the job identifier.
*/
public void returnJobToActive(Long jobID)
throws ManifoldCFException
{
beginTransaction();
try
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+","+connectionNameField+","+outputNameField+" FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Can't find job "+jobID.toString());
IResultRow row = set.getRow(0);
int status = stringToStatus((String)row.getValue(statusField));
int newStatus;
switch (status)
{
case STATUS_SHUTTINGDOWN:
if (connectionMgr.checkConnectorExists((String)row.getValue(connectionNameField)))
{
if (outputMgr.checkConnectorExists((String)row.getValue(outputNameField)))
newStatus = STATUS_ACTIVE;
else
newStatus = STATUS_ACTIVE_NOOUTPUT;
}
else
{
if (outputMgr.checkConnectorExists((String)row.getValue(outputNameField)))
newStatus = STATUS_ACTIVE_UNINSTALLED;
else
newStatus = STATUS_ACTIVE_NEITHER;
}
break;
default:
// Complain!
throw new ManifoldCFException("Unexpected job status encountered: "+Integer.toString(status));
}
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Put job into "deleting" state, and set the start time field.
*@param jobID is the job identifier.
*@param startTime is the current time in milliseconds from start of epoch.
*/
public void noteJobDeleteStarted(Long jobID, long startTime)
throws ManifoldCFException
{
beginTransaction();
try
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+","+connectionNameField+","+outputNameField+" FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Can't find job "+jobID.toString());
IResultRow row = set.getRow(0);
int status = stringToStatus((String)row.getValue(statusField));
int newStatus;
switch (status)
{
case STATUS_DELETESTARTINGUP:
if (outputMgr.checkConnectorExists((String)row.getValue(outputNameField)))
newStatus = STATUS_DELETING;
else
newStatus = STATUS_DELETING_NOOUTPUT;
break;
default:
// Complain!
throw new ManifoldCFException("Unexpected job status encountered: "+Integer.toString(status));
}
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
if (newStatus == STATUS_DELETING || newStatus == STATUS_DELETING_NOOUTPUT)
{
map.put(startTimeField,new Long(startTime));
}
map.put(lastCheckTimeField,new Long(startTime));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Make job active, and set the start time field.
*@param jobID is the job identifier.
*@param startTime is the current time in milliseconds from start of epoch.
*/
public void noteJobStarted(Long jobID, long startTime)
throws ManifoldCFException
{
beginTransaction();
try
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+","+connectionNameField+","+outputNameField+" FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Can't find job "+jobID.toString());
IResultRow row = set.getRow(0);
int status = stringToStatus((String)row.getValue(statusField));
int newStatus;
switch (status)
{
case STATUS_STARTINGUP:
case STATUS_STARTINGUPMINIMAL:
if (connectionMgr.checkConnectorExists((String)row.getValue(connectionNameField)))
{
if (outputMgr.checkConnectorExists((String)row.getValue(outputNameField)))
newStatus = STATUS_ACTIVE;
else
newStatus = STATUS_ACTIVE_NOOUTPUT;
}
else
{
if (outputMgr.checkConnectorExists((String)row.getValue(outputNameField)))
newStatus = STATUS_ACTIVE_UNINSTALLED;
else
newStatus = STATUS_ACTIVE_NEITHER;
}
break;
case STATUS_ABORTINGSTARTINGUP:
case STATUS_ABORTINGSTARTINGUPMINIMAL:
newStatus = STATUS_ABORTING;
break;
case STATUS_ABORTINGSTARTINGUPFORRESTART:
newStatus = STATUS_ABORTINGFORRESTART;
break;
case STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL:
newStatus = STATUS_ABORTINGFORRESTARTMINIMAL;
break;
default:
// Complain!
throw new ManifoldCFException("Unexpected job status encountered: "+Integer.toString(status));
}
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
if (newStatus == STATUS_ACTIVE || newStatus == STATUS_ACTIVE_UNINSTALLED ||
newStatus == STATUS_ACTIVE_NOOUTPUT || newStatus == STATUS_ACTIVE_NEITHER)
{
map.put(startTimeField,new Long(startTime));
}
// The seeding was complete or we wouldn't have gotten called, so at least note that.
map.put(lastCheckTimeField,new Long(startTime));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Note job seeded.
*@param jobID is the job id.
*@param seedTime is the job seed time.
*/
public void noteJobSeeded(Long jobID, long seedTime)
throws ManifoldCFException
{
// We have to convert the current status to the non-seeding equivalent
beginTransaction();
try
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+" FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Can't find job "+jobID.toString());
IResultRow row = set.getRow(0);
int status = stringToStatus((String)row.getValue(statusField));
int newStatus;
switch (status)
{
case STATUS_ACTIVESEEDING:
newStatus = STATUS_ACTIVE;
break;
case STATUS_PAUSINGSEEDING:
newStatus = STATUS_PAUSING;
break;
case STATUS_ACTIVEWAITINGSEEDING:
newStatus = STATUS_ACTIVEWAITING;
break;
case STATUS_PAUSINGWAITINGSEEDING:
newStatus = STATUS_PAUSINGWAITING;
break;
case STATUS_ACTIVESEEDING_UNINSTALLED:
newStatus = STATUS_ACTIVE_UNINSTALLED;
break;
case STATUS_ACTIVESEEDING_NOOUTPUT:
newStatus = STATUS_ACTIVE_NOOUTPUT;
break;
case STATUS_ACTIVESEEDING_NEITHER:
newStatus = STATUS_ACTIVE_NEITHER;
break;
case STATUS_ACTIVEWAITSEEDING:
newStatus = STATUS_ACTIVEWAIT;
break;
case STATUS_PAUSEDSEEDING:
newStatus = STATUS_PAUSED;
break;
case STATUS_PAUSEDWAITSEEDING:
newStatus = STATUS_PAUSEDWAIT;
break;
case STATUS_ABORTINGSEEDING:
newStatus = STATUS_ABORTING;
break;
case STATUS_ABORTINGFORRESTARTSEEDING:
newStatus = STATUS_ABORTINGFORRESTART;
break;
case STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL:
newStatus = STATUS_ABORTINGFORRESTARTMINIMAL;
break;
default:
throw new ManifoldCFException("Unexpected job status encountered: "+Integer.toString(status));
}
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
map.put(lastCheckTimeField,new Long(seedTime));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
catch (Error e)
{
signalRollback();
throw e;
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Cause job that is in "wait" state to become un-waited.
*@param jobID is the job identifier.
*@param newStatus is the new status (either STATUS_ACTIVE or STATUS_PAUSED or
* STATUS_ACTIVESEEDING or STATUS_PAUSEDSEEDING)
*@param windowEnd is the window end time, if any.
*/
public void unwaitJob(Long jobID, int newStatus, Long windowEnd)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
map.put(windowEndField,windowEnd);
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Cause job that is in active or paused state to become waited.
*@param jobID is the job identifier.
*@param newStatus is the new status (either STATUS_ACTIVEWAIT or STATUS_PAUSEDWAIT or
* STATUS_ACTIVEWAITSEEDING or STATUS_PAUSEDWAITSEEDING)
*/
public void waitJob(Long jobID, int newStatus)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
map.put(windowEndField,null);
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Abort a job.
*@param jobID is the job id.
*@param errorText is the error, or null if none.
*@return true if there wasn't an abort already logged for this job.
*/
public boolean abortJob(Long jobID, String errorText)
throws ManifoldCFException
{
// Get the current job status
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+" FROM "+getTableName()+
" WHERE "+query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Job does not exist: "+jobID);
IResultRow row = set.getRow(0);
int status = stringToStatus(row.getValue(statusField).toString());
if (status == STATUS_ABORTING || status == STATUS_ABORTINGSEEDING ||
status == STATUS_ABORTINGSTARTINGUP || status == STATUS_ABORTINGSTARTINGUPMINIMAL)
return false;
int newStatus;
switch (status)
{
case STATUS_STARTINGUP:
case STATUS_ABORTINGSTARTINGUPFORRESTART:
newStatus = STATUS_ABORTINGSTARTINGUP;
break;
case STATUS_STARTINGUPMINIMAL:
case STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL:
newStatus = STATUS_ABORTINGSTARTINGUPMINIMAL;
break;
case STATUS_READYFORSTARTUP:
case STATUS_READYFORSTARTUPMINIMAL:
case STATUS_ACTIVE:
case STATUS_ACTIVE_UNINSTALLED:
case STATUS_ACTIVE_NOOUTPUT:
case STATUS_ACTIVE_NEITHER:
case STATUS_ACTIVEWAIT:
case STATUS_PAUSING:
case STATUS_ACTIVEWAITING:
case STATUS_PAUSINGWAITING:
case STATUS_PAUSED:
case STATUS_PAUSEDWAIT:
case STATUS_ABORTINGFORRESTART:
case STATUS_ABORTINGFORRESTARTMINIMAL:
newStatus = STATUS_ABORTING;
break;
case STATUS_ACTIVESEEDING:
case STATUS_ACTIVESEEDING_UNINSTALLED:
case STATUS_ACTIVESEEDING_NOOUTPUT:
case STATUS_ACTIVESEEDING_NEITHER:
case STATUS_ACTIVEWAITSEEDING:
case STATUS_PAUSINGSEEDING:
case STATUS_ACTIVEWAITINGSEEDING:
case STATUS_PAUSINGWAITINGSEEDING:
case STATUS_PAUSEDSEEDING:
case STATUS_PAUSEDWAITSEEDING:
case STATUS_ABORTINGFORRESTARTSEEDING:
case STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL:
newStatus = STATUS_ABORTINGSEEDING;
break;
default:
throw new ManifoldCFException("Job "+jobID+" is not active");
}
// Pause the job
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
map.put(errorField,errorText);
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
return true;
}
/** Restart a job. Finish off what's currently happening, and then start the job up again.
*@param jobID is the job id.
*@param requestMinimum is true if the minimal job run is requested.
*/
public void abortRestartJob(Long jobID, boolean requestMinimum)
throws ManifoldCFException
{
// Get the current job status
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+" FROM "+getTableName()+
" WHERE "+query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Job does not exist: "+jobID);
IResultRow row = set.getRow(0);
int status = stringToStatus(row.getValue(statusField).toString());
if (status == STATUS_ABORTINGFORRESTART || status == STATUS_ABORTINGFORRESTARTSEEDING ||
status == STATUS_ABORTINGSTARTINGUPFORRESTART ||
status == STATUS_ABORTINGFORRESTARTMINIMAL || status == STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL ||
status == STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL)
return;
int newStatus;
switch (status)
{
case STATUS_STARTINGUP:
case STATUS_STARTINGUPMINIMAL:
newStatus = requestMinimum?STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL:STATUS_ABORTINGSTARTINGUPFORRESTART;
break;
case STATUS_READYFORSTARTUP:
case STATUS_READYFORSTARTUPMINIMAL:
case STATUS_ACTIVE:
case STATUS_ACTIVE_UNINSTALLED:
case STATUS_ACTIVE_NOOUTPUT:
case STATUS_ACTIVE_NEITHER:
case STATUS_ACTIVEWAIT:
case STATUS_PAUSING:
case STATUS_ACTIVEWAITING:
case STATUS_PAUSINGWAITING:
case STATUS_PAUSED:
case STATUS_PAUSEDWAIT:
newStatus = requestMinimum?STATUS_ABORTINGFORRESTARTMINIMAL:STATUS_ABORTINGFORRESTART;
break;
case STATUS_ACTIVESEEDING:
case STATUS_ACTIVESEEDING_UNINSTALLED:
case STATUS_ACTIVESEEDING_NOOUTPUT:
case STATUS_ACTIVESEEDING_NEITHER:
case STATUS_ACTIVEWAITSEEDING:
case STATUS_PAUSINGSEEDING:
case STATUS_ACTIVEWAITINGSEEDING:
case STATUS_PAUSINGWAITINGSEEDING:
case STATUS_PAUSEDSEEDING:
case STATUS_PAUSEDWAITSEEDING:
newStatus = requestMinimum?STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL:STATUS_ABORTINGFORRESTARTSEEDING;
break;
default:
throw new ManifoldCFException("Job "+jobID+" is not restartable");
}
// reset the job
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Pause a job.
*@param jobID is the job id.
*/
public void pauseJob(Long jobID)
throws ManifoldCFException
{
// Get the current job status
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+" FROM "+getTableName()+
" WHERE "+query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Job does not exist: "+jobID);
IResultRow row = set.getRow(0);
int status = stringToStatus(row.getValue(statusField).toString());
int newStatus;
switch (status)
{
case STATUS_ACTIVE:
case STATUS_ACTIVE_UNINSTALLED:
case STATUS_ACTIVE_NOOUTPUT:
case STATUS_ACTIVE_NEITHER:
newStatus = STATUS_PAUSING;
break;
case STATUS_ACTIVEWAITING:
newStatus = STATUS_PAUSINGWAITING;
break;
case STATUS_ACTIVEWAIT:
newStatus = STATUS_PAUSEDWAIT;
break;
case STATUS_ACTIVESEEDING:
case STATUS_ACTIVESEEDING_UNINSTALLED:
case STATUS_ACTIVESEEDING_NOOUTPUT:
case STATUS_ACTIVESEEDING_NEITHER:
newStatus = STATUS_PAUSINGSEEDING;
break;
case STATUS_ACTIVEWAITINGSEEDING:
newStatus = STATUS_PAUSINGWAITINGSEEDING;
break;
case STATUS_ACTIVEWAITSEEDING:
newStatus = STATUS_PAUSEDWAITSEEDING;
break;
default:
throw new ManifoldCFException("Job "+jobID+" is not active");
}
// Pause the job
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Restart a job.
*@param jobID is the job id.
*/
public void restartJob(Long jobID)
throws ManifoldCFException
{
// Get the current job status
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+","+connectionNameField+","+outputNameField+" FROM "+getTableName()+
" WHERE "+query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Job does not exist: "+jobID);
IResultRow row = set.getRow(0);
int status = stringToStatus(row.getValue(statusField).toString());
String connectionName = (String)row.getValue(connectionNameField);
String outputName = (String)row.getValue(outputNameField);
int newStatus;
switch (status)
{
case STATUS_PAUSED:
newStatus = STATUS_RESUMING;
break;
case STATUS_PAUSEDWAIT:
newStatus = STATUS_ACTIVEWAIT;
break;
case STATUS_PAUSEDSEEDING:
newStatus = STATUS_RESUMINGSEEDING;
break;
case STATUS_PAUSEDWAITSEEDING:
newStatus = STATUS_ACTIVEWAITSEEDING;
break;
default:
throw new ManifoldCFException("Job "+jobID+" is not paused");
}
// Pause the job
HashMap map = new HashMap();
map.put(statusField,statusToString(newStatus));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Update a job's status, and its reseed time.
*@param jobID is the job id.
*@param status is the desired status.
*@param reseedTime is the reseed time.
*/
public void writeStatus(Long jobID, int status, Long reseedTime)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(statusField,statusToString(status));
map.put(reseedTimeField,reseedTime);
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Update a job's status.
*@param jobID is the job id.
*@param status is the desired status.
*/
public void writeStatus(Long jobID, int status)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(statusField,statusToString(status));
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Update a job's last-time field.
*@param jobID is the job id.
*@param currentTime is the current time.
*/
public void updateLastTime(Long jobID, long currentTime)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(lastTimeField,new Long(currentTime));
performUpdate(map,"WHERE "+query,list,null);
}
/** Finish a job.
* Write completion and the current time.
*@param jobID is the job id.
*@param finishTime is the finish time.
*/
public void finishJob(Long jobID, long finishTime)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(statusField,statusToString(STATUS_READYFORNOTIFY));
map.put(errorField,null);
map.put(endTimeField,new Long(finishTime));
map.put(lastTimeField,new Long(finishTime));
map.put(windowEndField,null);
map.put(reseedTimeField,null);
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** Resume a stopped job (from a pause or activewait).
* Updates the job record in a manner consistent with the job's state.
*/
public void finishResumeJob(Long jobID, long currentTime)
throws ManifoldCFException
{
beginTransaction();
try
{
// Get the current job status
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+","+connectionNameField+","+outputNameField+" FROM "+getTableName()+
" WHERE "+query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Job does not exist: "+jobID);
IResultRow row = set.getRow(0);
int status = stringToStatus(row.getValue(statusField).toString());
String connectionName = (String)row.getValue(connectionNameField);
String outputName = (String)row.getValue(outputNameField);
int newStatus;
HashMap map = new HashMap();
switch (status)
{
case STATUS_RESUMING:
if (connectionMgr.checkConnectorExists(connectionName))
{
if (outputMgr.checkConnectorExists(outputName))
newStatus = STATUS_ACTIVE;
else
newStatus = STATUS_ACTIVE_NOOUTPUT;
}
else
{
if (outputMgr.checkConnectorExists(outputName))
newStatus = STATUS_ACTIVE_UNINSTALLED;
else
newStatus = STATUS_ACTIVE_NEITHER;
}
map.put(statusField,statusToString(newStatus));
break;
case STATUS_RESUMINGSEEDING:
if (connectionMgr.checkConnectorExists(connectionName))
{
if (outputMgr.checkConnectorExists(outputName))
newStatus = STATUS_ACTIVESEEDING;
else
newStatus = STATUS_ACTIVESEEDING_NOOUTPUT;
}
else
{
if (outputMgr.checkConnectorExists(outputName))
newStatus = STATUS_ACTIVESEEDING_UNINSTALLED;
else
newStatus = STATUS_ACTIVESEEDING_NEITHER;
}
map.put(statusField,statusToString(newStatus));
break;
default:
throw new ManifoldCFException("Unexpected value for job status: "+Integer.toString(status));
}
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Stop a job suddenly (abort, pause, activewait).
* Updates the job record in a manner consistent with the job's state.
*/
public void finishStopJob(Long jobID, long currentTime)
throws ManifoldCFException
{
beginTransaction();
try
{
// Get the current job status
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
IResultSet set = performQuery("SELECT "+statusField+" FROM "+getTableName()+
" WHERE "+query+" FOR UPDATE",list,null,null);
if (set.getRowCount() == 0)
throw new ManifoldCFException("Job does not exist: "+jobID);
IResultRow row = set.getRow(0);
int status = stringToStatus(row.getValue(statusField).toString());
HashMap map = new HashMap();
switch (status)
{
case STATUS_ABORTING:
// Mark status of job as "inactive"
map.put(statusField,statusToString(STATUS_READYFORNOTIFY));
map.put(endTimeField,null);
map.put(lastTimeField,new Long(currentTime));
map.put(windowEndField,null);
map.put(reseedTimeField,null);
break;
case STATUS_ABORTINGFORRESTART:
map.put(statusField,statusToString(STATUS_READYFORSTARTUP));
map.put(endTimeField,null);
// Make sure error is removed (from last time)
map.put(errorField,null);
map.put(windowEndField,null);
break;
case STATUS_ABORTINGFORRESTARTMINIMAL:
map.put(statusField,statusToString(STATUS_READYFORSTARTUPMINIMAL));
map.put(endTimeField,null);
// Make sure error is removed (from last time)
map.put(errorField,null);
map.put(windowEndField,null);
break;
case STATUS_PAUSING:
map.put(statusField,statusToString(STATUS_PAUSED));
break;
case STATUS_PAUSINGSEEDING:
map.put(statusField,statusToString(STATUS_PAUSEDSEEDING));
break;
case STATUS_ACTIVEWAITING:
map.put(statusField,statusToString(STATUS_ACTIVEWAIT));
break;
case STATUS_ACTIVEWAITINGSEEDING:
map.put(statusField,statusToString(STATUS_ACTIVEWAITSEEDING));
break;
case STATUS_PAUSINGWAITING:
map.put(statusField,statusToString(STATUS_PAUSEDWAIT));
break;
case STATUS_PAUSINGWAITINGSEEDING:
map.put(statusField,statusToString(STATUS_PAUSEDWAITSEEDING));
break;
default:
throw new ManifoldCFException("Unexpected value for job status: "+Integer.toString(status));
}
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Mark job as having properly notified the output connector of completion.
*@param jobID is the job id.
*/
public void notificationComplete(Long jobID)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(idField,jobID)});
HashMap map = new HashMap();
map.put(statusField,statusToString(STATUS_INACTIVE));
// Leave everything else around from the abort/finish.
performUpdate(map,"WHERE "+query,list,new StringSet(getJobStatusKey()));
}
/** See if there's a reference to a connection name.
*@param connectionName is the name of the connection.
*@return true if there is a reference, false otherwise.
*/
public boolean checkIfReference(String connectionName)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(connectionNameField,connectionName)});
IResultSet set = performQuery("SELECT "+idField+" FROM "+getTableName()+
" WHERE "+query,list,new StringSet(getJobsKey()),null);
return set.getRowCount() > 0;
}
/** See if there's a reference to an output connection name.
*@param connectionName is the name of the connection.
*@return true if there is a reference, false otherwise.
*/
public boolean checkIfOutputReference(String connectionName)
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(outputNameField,connectionName)});
IResultSet set = performQuery("SELECT "+idField+" FROM "+getTableName()+
" WHERE "+query,list,new StringSet(getJobsKey()),null);
return set.getRowCount() > 0;
}
/** Get the job IDs associated with a given connection name.
*@param connectionName is the name of the connection.
*@return the set of job id's associated with that connection.
*/
public IJobDescription[] findJobsForConnection(String connectionName)
throws ManifoldCFException
{
// Begin transaction
beginTransaction();
try
{
// Put together cache key
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getJobsKey());
StringSet cacheKeys = new StringSet(ssb);
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(connectionNameField,connectionName)});
IResultSet set = performQuery("SELECT "+idField+","+descriptionField+" FROM "+
getTableName()+" WHERE "+query+
" ORDER BY "+descriptionField+" ASC",list,cacheKeys,null);
// Convert to an array of id's, and then load them
Long[] ids = new Long[set.getRowCount()];
boolean[] readOnlies = new boolean[set.getRowCount()];
int i = 0;
while (i < ids.length)
{
IResultRow row = set.getRow(i);
ids[i] = (Long)row.getValue(idField);
readOnlies[i++] = true;
}
return loadMultiple(ids,readOnlies);
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
/** Return true if there is a job in the DELETING state. (This matches the
* conditions for values to be returned from
* getNextDeletableDocuments).
*@return true if such jobs exist.
*/
public boolean deletingJobsPresent()
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_DELETING))});
IResultSet set = performQuery("SELECT "+idField+" FROM "+getTableName()+" WHERE "+
query+" "+constructOffsetLimitClause(0,1),
list,new StringSet(getJobStatusKey()),null,1);
return set.getRowCount() > 0;
}
/** Return true if there is a job in the
* SHUTTINGDOWN state. (This matches the conditions for values to be returned from
* getNextCleanableDocuments).
*@return true if such jobs exist.
*/
public boolean cleaningJobsPresent()
throws ManifoldCFException
{
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new UnitaryClause(statusField,statusToString(STATUS_SHUTTINGDOWN))});
IResultSet set = performQuery("SELECT "+idField+" FROM "+getTableName()+" WHERE "+
query+" "+constructOffsetLimitClause(0,1),
list,new StringSet(getJobStatusKey()),null,1);
return set.getRowCount() > 0;
}
/** Return true if there is a job in either the ACTIVE or the ACTIVESEEDING state.
* (This matches the conditions for values to be returned from getNextDocuments).
*@return true if such jobs exist.
*/
public boolean activeJobsPresent()
throws ManifoldCFException
{
// To improve the postgres CPU usage of the system at rest, we do a *fast* check to be
// sure there are ANY jobs in an active state.
ArrayList list = new ArrayList();
String query = buildConjunctionClause(list,new ClauseDescription[]{
new MultiClause(statusField,new Object[]{
statusToString(STATUS_ACTIVE),
statusToString(STATUS_ACTIVESEEDING)})});
IResultSet set = performQuery("SELECT "+idField+" FROM "+getTableName()+" WHERE "+
query+" "+constructOffsetLimitClause(0,1),list,new StringSet(getJobStatusKey()),null,1);
return set.getRowCount() > 0;
}
// These functions map from status to a string and back
/** Go from string to status.
*@param value is the string.
*@return the status value.
*/
public static int stringToStatus(String value)
throws ManifoldCFException
{
Integer x = (Integer)statusMap.get(value);
if (x == null)
throw new ManifoldCFException("Bad status value: '"+value+"'");
return x.intValue();
}
/** Go from status to string.
*@param status is the status.
*@return the string.
*/
public static String statusToString(int status)
throws ManifoldCFException
{
switch (status)
{
case STATUS_INACTIVE:
return "N";
case STATUS_ACTIVE:
return "A";
case STATUS_PAUSED:
return "P";
case STATUS_SHUTTINGDOWN:
return "S";
case STATUS_NOTIFYINGOFCOMPLETION:
return "n";
case STATUS_READYFORNOTIFY:
return "s";
case STATUS_ACTIVEWAIT:
return "W";
case STATUS_PAUSEDWAIT:
return "Z";
case STATUS_ABORTING:
return "X";
case STATUS_ABORTINGFORRESTART:
return "Y";
case STATUS_ABORTINGFORRESTARTMINIMAL:
return "M";
case STATUS_STARTINGUP:
return "B";
case STATUS_STARTINGUPMINIMAL:
return "b";
case STATUS_ABORTINGSTARTINGUP:
return "Q";
case STATUS_ABORTINGSTARTINGUPMINIMAL:
return "q";
case STATUS_ABORTINGSTARTINGUPFORRESTART:
return "T";
case STATUS_ABORTINGSTARTINGUPFORRESTARTMINIMAL:
return "t";
case STATUS_READYFORSTARTUP:
return "C";
case STATUS_READYFORSTARTUPMINIMAL:
return "c";
case STATUS_READYFORDELETE:
return "E";
case STATUS_DELETESTARTINGUP:
return "V";
case STATUS_DELETING:
return "e";
case STATUS_ACTIVESEEDING:
return "a";
case STATUS_ABORTINGSEEDING:
return "x";
case STATUS_PAUSEDSEEDING:
return "p";
case STATUS_ACTIVEWAITSEEDING:
return "w";
case STATUS_PAUSEDWAITSEEDING:
return "z";
case STATUS_ABORTINGFORRESTARTSEEDING:
return "y";
case STATUS_ABORTINGFORRESTARTSEEDINGMINIMAL:
return "m";
case STATUS_ACTIVE_UNINSTALLED:
return "R";
case STATUS_ACTIVESEEDING_UNINSTALLED:
return "r";
case STATUS_ACTIVE_NOOUTPUT:
return "O";
case STATUS_ACTIVESEEDING_NOOUTPUT:
return "o";
case STATUS_ACTIVE_NEITHER:
return "U";
case STATUS_ACTIVESEEDING_NEITHER:
return "u";
case STATUS_DELETING_NOOUTPUT:
return "D";
case STATUS_ACTIVEWAITING:
return "H";
case STATUS_ACTIVEWAITINGSEEDING:
return "h";
case STATUS_PAUSING:
return "F";
case STATUS_PAUSINGSEEDING:
return "f";
case STATUS_PAUSINGWAITING:
return "G";
case STATUS_PAUSINGWAITINGSEEDING:
return "g";
case STATUS_RESUMING:
return "I";
case STATUS_RESUMINGSEEDING:
return "i";
default:
throw new ManifoldCFException("Bad status value: "+Integer.toString(status));
}
}
/** Go from string to type.
*@param value is the string.
*@return the type value.
*/
public static int stringToType(String value)
throws ManifoldCFException
{
Integer x = (Integer)typeMap.get(value);
if (x == null)
throw new ManifoldCFException("Bad type value: '"+value+"'");
return x.intValue();
}
/** Go from type to string.
*@param type is the type.
*@return the string.
*/
public static String typeToString(int type)
throws ManifoldCFException
{
switch (type)
{
case TYPE_CONTINUOUS:
return "C";
case TYPE_SPECIFIED:
return "S";
default:
throw new ManifoldCFException("Bad type: "+Integer.toString(type));
}
}
/** Go from string to hopcount mode.
*/
public static int stringToHopcountMode(String value)
throws ManifoldCFException
{
if (value == null || value.length() == 0)
return HOPCOUNT_ACCURATE;
Integer x = (Integer)hopmodeMap.get(value);
if (x == null)
throw new ManifoldCFException("Bad hopcount mode value: '"+value+"'");
return x.intValue();
}
/** Go from hopcount mode to string.
*/
public static String hopcountModeToString(int value)
throws ManifoldCFException
{
switch(value)
{
case HOPCOUNT_ACCURATE:
return "A";
case HOPCOUNT_NODELETE:
return "N";
case HOPCOUNT_NEVERDELETE:
return "V";
default:
throw new ManifoldCFException("Unknown hopcount mode value "+Integer.toString(value));
}
}
/** Go from string to start method.
*@param value is the string.
*@return the start method value.
*/
public static int stringToStartMethod(String value)
throws ManifoldCFException
{
Integer x = (Integer)startMap.get(value);
if (x == null)
throw new ManifoldCFException("Bad start method value: '"+value+"'");
return x.intValue();
}
/** Get from start method to string.
*@param startMethod is the start method.
*@return a string.
*/
public static String startMethodToString(int startMethod)
throws ManifoldCFException
{
switch(startMethod)
{
case START_WINDOWBEGIN:
return "B";
case START_WINDOWINSIDE:
return "I";
case START_DISABLE:
return "D";
default:
throw new ManifoldCFException("Bad start method: "+Integer.toString(startMethod));
}
}
/** Go from string to enumerated value.
*@param value is the input.
*@return the enumerated value.
*/
public static EnumeratedValues stringToEnumeratedValue(String value)
throws ManifoldCFException
{
if (value == null)
return null;
try
{
ArrayList valStore = new ArrayList();
if (!value.equals("*"))
{
int curpos = 0;
while (true)
{
int newpos = value.indexOf(",",curpos);
if (newpos == -1)
{
valStore.add(new Integer(value.substring(curpos)));
break;
}
valStore.add(new Integer(value.substring(curpos,newpos)));
curpos = newpos+1;
}
}
return new EnumeratedValues(valStore);
}
catch (NumberFormatException e)
{
throw new ManifoldCFException("Bad number: '"+value+"'",e);
}
}
/** Go from enumerated value to string.
*@param values is the enumerated value.
*@return the string value.
*/
public static String enumeratedValueToString(EnumeratedValues values)
{
if (values == null)
return null;
if (values.size() == 0)
return "*";
StringBuilder rval = new StringBuilder();
Iterator iter = values.getValues();
boolean first = true;
while (iter.hasNext())
{
if (first)
first = false;
else
rval.append(',');
rval.append(((Integer)iter.next()).toString());
}
return rval.toString();
}
// Cache key picture for jobs. There is one global job cache key, and a cache key for each individual job (which is based on
// id).
protected static String getJobsKey()
{
return CacheKeyFactory.makeJobsKey();
}
protected static String getJobIDKey(Long jobID)
{
return CacheKeyFactory.makeJobIDKey(jobID.toString());
}
protected static String getJobStatusKey()
{
return CacheKeyFactory.makeJobStatusKey();
}
/** Get multiple jobs (without caching)
*@param ids is the set of ids to get jobs for.
*@return the corresponding job descriptions.
*/
protected JobDescription[] getJobsMultiple(Long[] ids)
throws ManifoldCFException
{
// Fetch all the jobs, but only once for each ID. Then, assign each one by id into the final array.
HashMap uniqueIDs = new HashMap();
int i = 0;
while (i < ids.length)
{
uniqueIDs.put(ids[i],ids[i]);
i++;
}
HashMap returnValues = new HashMap();
beginTransaction();
try
{
StringBuilder sb = new StringBuilder();
ArrayList params = new ArrayList();
int j = 0;
int maxIn = getMaxInClause();
Iterator iter = uniqueIDs.keySet().iterator();
while (iter.hasNext())
{
if (j == maxIn)
{
getJobsChunk(returnValues,sb.toString(),params);
sb.setLength(0);
params.clear();
j = 0;
}
if (j > 0)
sb.append(',');
sb.append('?');
params.add((Long)iter.next());
j++;
}
if (j > 0)
getJobsChunk(returnValues,sb.toString(),params);
}
catch (Error e)
{
signalRollback();
throw e;
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
// Build the return array
JobDescription[] rval = new JobDescription[ids.length];
i = 0;
while (i < rval.length)
{
Long id = ids[i];
JobDescription jd = (JobDescription)returnValues.get(id);
if (jd != null)
jd.makeReadOnly();
rval[i] = jd;
i++;
}
return rval;
}
/** Read a chunk of repository connections.
*@param returnValues is keyed by id and contains a JobDescription value.
*@param idList is the list of id's.
*@param params is the set of parameters.
*/
protected void getJobsChunk(Map returnValues, String idList, ArrayList params)
throws ManifoldCFException
{
try
{
IResultSet set;
set = performQuery("SELECT * FROM "+getTableName()+" WHERE "+
idField+" IN ("+idList+")",params,null,null);
int i = 0;
while (i < set.getRowCount())
{
IResultRow row = set.getRow(i++);
Long id = (Long)row.getValue(idField);
JobDescription rc = new JobDescription();
rc.setID(id);
rc.setIsNew(false);
rc.setDescription(row.getValue(descriptionField).toString());
rc.setOutputConnectionName(row.getValue(outputNameField).toString());
rc.setConnectionName(row.getValue(connectionNameField).toString());
rc.setType(stringToType(row.getValue(typeField).toString()));
rc.setStartMethod(stringToStartMethod(row.getValue(startMethodField).toString()));
rc.setHopcountMode(stringToHopcountMode((String)row.getValue(hopcountModeField)));
// System.out.println("XML = "+row.getValue(documentSpecField).toString());
rc.getOutputSpecification().fromXML(row.getValue(outputSpecField).toString());
rc.getSpecification().fromXML(row.getValue(documentSpecField).toString());
Object x;
rc.setInterval((Long)row.getValue(intervalField));
rc.setReseedInterval((Long)row.getValue(reseedIntervalField));
rc.setExpiration((Long)row.getValue(expirationField));
rc.setPriority(Integer.parseInt(row.getValue(priorityField).toString()));
returnValues.put(id,rc);
}
// Fill in schedules for jobs
scheduleManager.getRows(returnValues,idList,params);
hopFilterManager.getRows(returnValues,idList,params);
forcedParamManager.getRows(returnValues,idList,params);
}
catch (NumberFormatException e)
{
throw new ManifoldCFException("Bad number",e);
}
}
/** Job object description class. This class describes an object in the cache.
*/
protected static class JobObjectDescription extends org.apache.manifoldcf.core.cachemanager.BaseDescription
{
protected Long jobID;
protected String criticalSectionName;
protected StringSet cacheKeys;
public JobObjectDescription(Long jobID, StringSet invKeys)
{
super("jobdescriptioncache");
this.jobID = jobID;
criticalSectionName = getClass().getName()+"-"+jobID.toString();
cacheKeys = invKeys;
}
public Long getJobID()
{
return jobID;
}
public int hashCode()
{
return jobID.hashCode() ;
}
public boolean equals(Object o)
{
if (!(o instanceof JobObjectDescription))
return false;
JobObjectDescription d = (JobObjectDescription)o;
return d.jobID.equals(jobID);
}
public String getCriticalSectionName()
{
return criticalSectionName;
}
/** Get the cache keys for an object (which may or may not exist yet in
* the cache). This method is called in order for cache manager to throw the correct locks.
* @return the object's cache keys, or null if the object should not
* be cached.
*/
public StringSet getObjectKeys()
{
return cacheKeys;
}
}
/** This is the executor object for locating job objects.
*/
protected static class JobObjectExecutor extends org.apache.manifoldcf.core.cachemanager.ExecutorBase
{
// Member variables
protected Jobs thisManager;
protected JobDescription[] returnValues;
protected HashMap returnMap = new HashMap();
/** Constructor.
*@param manager is the ToolManager.
*@param objectDescriptions are the object descriptions.
*/
public JobObjectExecutor(Jobs manager, JobObjectDescription[] objectDescriptions)
{
super();
thisManager = manager;
returnValues = new JobDescription[objectDescriptions.length];
int i = 0;
while (i < objectDescriptions.length)
{
returnMap.put(objectDescriptions[i].getJobID(),new Integer(i));
i++;
}
}
/** Get the result.
*@return the looked-up or read cached instances.
*/
public JobDescription[] getResults(boolean[] readOnlies)
{
JobDescription[] rval = new JobDescription[returnValues.length];
int i = 0;
while (i < rval.length)
{
JobDescription jd = returnValues[i];
if (jd != null)
rval[i] = jd.duplicate(readOnlies[i]);
else
rval[i] = null;
i++;
}
return rval;
}
/** Create a set of new objects to operate on and cache. This method is called only
* if the specified object(s) are NOT available in the cache. The specified objects
* should be created and returned; if they are not created, it means that the
* execution cannot proceed, and the execute() method will not be called.
* @param objectDescriptions is the set of unique identifier of the object.
* @return the newly created objects to cache, or null, if any object cannot be created.
* The order of the returned objects must correspond to the order of the object descriptinos.
*/
public Object[] create(ICacheDescription[] objectDescriptions) throws ManifoldCFException
{
// Turn the object descriptions into the parameters for the ToolInstance requests
Long[] ids = new Long[objectDescriptions.length];
int i = 0;
while (i < ids.length)
{
JobObjectDescription desc = (JobObjectDescription)objectDescriptions[i];
ids[i] = desc.getJobID();
i++;
}
return thisManager.getJobsMultiple(ids);
}
/** Notify the implementing class of the existence of a cached version of the
* object. The object is passed to this method so that the execute() method below
* will have it available to operate on. This method is also called for all objects
* that are freshly created as well.
* @param objectDescription is the unique identifier of the object.
* @param cachedObject is the cached object.
*/
public void exists(ICacheDescription objectDescription, Object cachedObject) throws ManifoldCFException
{
// Cast what came in as what it really is
JobObjectDescription objectDesc = (JobObjectDescription)objectDescription;
JobDescription ci = (JobDescription)cachedObject;
// All objects stored in this cache are read-only; no need to duplicate them at this level.
// In order to make the indexes line up, we need to use the hashtable built by
// the constructor.
returnValues[((Integer)returnMap.get(objectDesc.getJobID())).intValue()] = ci;
}
/** Perform the desired operation. This method is called after either createGetObject()
* or exists() is called for every requested object.
*/
public void execute() throws ManifoldCFException
{
// Does nothing; we only want to fetch objects in this cacher.
}
}
}
| false | true | public void save(IJobDescription jobDescription)
throws ManifoldCFException
{
// The invalidation keys for this are both the general and the specific.
Long id = jobDescription.getID();
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getJobsKey());
ssb.add(getJobStatusKey());
ssb.add(getJobIDKey(id));
StringSet invKeys = new StringSet(ssb);
while (true)
{
long sleepAmt = 0L;
try
{
ICacheHandle ch = cacheManager.enterCache(null,invKeys,getTransactionID());
try
{
beginTransaction();
try
{
//performLock();
// See whether the instance exists
ArrayList params = new ArrayList();
String query = buildConjunctionClause(params,new ClauseDescription[]{
new UnitaryClause(idField,id)});
IResultSet set = performQuery("SELECT * FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",params,null,null);
HashMap values = new HashMap();
values.put(descriptionField,jobDescription.getDescription());
values.put(outputNameField,jobDescription.getOutputConnectionName());
values.put(connectionNameField,jobDescription.getConnectionName());
String newOutputXML = jobDescription.getOutputSpecification().toXML();
values.put(outputSpecField,newOutputXML);
String newXML = jobDescription.getSpecification().toXML();
values.put(documentSpecField,newXML);
values.put(typeField,typeToString(jobDescription.getType()));
values.put(startMethodField,startMethodToString(jobDescription.getStartMethod()));
values.put(intervalField,jobDescription.getInterval());
values.put(reseedIntervalField,jobDescription.getReseedInterval());
values.put(expirationField,jobDescription.getExpiration());
values.put(priorityField,new Integer(jobDescription.getPriority()));
values.put(hopcountModeField,hopcountModeToString(jobDescription.getHopcountMode()));
if (set.getRowCount() > 0)
{
// Update
// We need to reset the lastCheckTimeField if there are any changes that
// could affect what set of documents we allow!!!
IResultRow row = set.getRow(0);
boolean isSame = true;
// Determine whether we need to reset the scan time for documents.
// Basically, any change to job parameters that could affect ingestion should clear isSame so that we
// relook at all the documents, not just the recent ones.
if (isSame)
{
String oldOutputSpecXML = (String)row.getValue(outputSpecField);
if (!oldOutputSpecXML.equals(newOutputXML))
isSame = false;
}
if (isSame)
{
String oldDocSpecXML = (String)row.getValue(documentSpecField);
if (!oldDocSpecXML.equals(newXML))
isSame = false;
}
if (isSame)
{
// Compare hopcount filter criteria.
Map filterRows = hopFilterManager.readRows(id);
Map newFilterRows = jobDescription.getHopCountFilters();
if (filterRows.size() != newFilterRows.size())
isSame = false;
else
{
for (String linkType : (Collection<String>)filterRows.keySet())
{
Integer oldCount = (Integer)filterRows.get(linkType);
Integer newCount = (Integer)newFilterRows.get(linkType);
if (oldCount == null || newCount == null)
{
isSame = false;
break;
}
else if (oldCount.intValue() != newCount.intValue())
{
isSame = false;
break;
}
}
}
}
if (!isSame)
values.put(lastCheckTimeField,null);
params.clear();
query = buildConjunctionClause(params,new ClauseDescription[]{
new UnitaryClause(idField,id)});
performUpdate(values," WHERE "+query,params,null);
scheduleManager.deleteRows(id);
hopFilterManager.deleteRows(id);
forcedParamManager.deleteRows(id);
}
else
{
// Insert
values.put(startTimeField,null);
values.put(lastCheckTimeField,null);
values.put(endTimeField,null);
values.put(statusField,statusToString(STATUS_INACTIVE));
values.put(lastTimeField,new Long(System.currentTimeMillis()));
values.put(idField,id);
performInsert(values,null);
}
// Write schedule records
scheduleManager.writeRows(id,jobDescription);
// Write hop filter rows
hopFilterManager.writeRows(id,jobDescription);
// Write forced params
forcedParamManager.writeRows(id,jobDescription);
cacheManager.invalidateKeys(ch);
break;
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
finally
{
cacheManager.leaveCache(ch);
}
}
catch (ManifoldCFException e)
{
if (e.getErrorCode() != ManifoldCFException.DATABASE_TRANSACTION_ABORT)
throw e;
sleepAmt = getSleepAmt();
continue;
}
finally
{
sleepFor(sleepAmt);
}
}
}
| public void save(IJobDescription jobDescription)
throws ManifoldCFException
{
// The invalidation keys for this are both the general and the specific.
Long id = jobDescription.getID();
StringSetBuffer ssb = new StringSetBuffer();
ssb.add(getJobsKey());
ssb.add(getJobStatusKey());
ssb.add(getJobIDKey(id));
StringSet invKeys = new StringSet(ssb);
while (true)
{
long sleepAmt = 0L;
try
{
ICacheHandle ch = cacheManager.enterCache(null,invKeys,getTransactionID());
try
{
beginTransaction();
try
{
//performLock();
// See whether the instance exists
ArrayList params = new ArrayList();
String query = buildConjunctionClause(params,new ClauseDescription[]{
new UnitaryClause(idField,id)});
IResultSet set = performQuery("SELECT * FROM "+getTableName()+" WHERE "+
query+" FOR UPDATE",params,null,null);
HashMap values = new HashMap();
values.put(descriptionField,jobDescription.getDescription());
values.put(outputNameField,jobDescription.getOutputConnectionName());
values.put(connectionNameField,jobDescription.getConnectionName());
String newOutputXML = jobDescription.getOutputSpecification().toXML();
values.put(outputSpecField,newOutputXML);
String newXML = jobDescription.getSpecification().toXML();
values.put(documentSpecField,newXML);
values.put(typeField,typeToString(jobDescription.getType()));
values.put(startMethodField,startMethodToString(jobDescription.getStartMethod()));
values.put(intervalField,jobDescription.getInterval());
values.put(reseedIntervalField,jobDescription.getReseedInterval());
values.put(expirationField,jobDescription.getExpiration());
values.put(priorityField,new Integer(jobDescription.getPriority()));
values.put(hopcountModeField,hopcountModeToString(jobDescription.getHopcountMode()));
if (set.getRowCount() > 0)
{
// Update
// We need to reset the lastCheckTimeField if there are any changes that
// could affect what set of documents we allow!!!
IResultRow row = set.getRow(0);
boolean isSame = true;
// Determine whether we need to reset the scan time for documents.
// Basically, any change to job parameters that could affect ingestion should clear isSame so that we
// relook at all the documents, not just the recent ones.
if (isSame)
{
String oldOutputSpecXML = (String)row.getValue(outputSpecField);
if (!oldOutputSpecXML.equals(newOutputXML))
isSame = false;
}
if (isSame)
{
String oldDocSpecXML = (String)row.getValue(documentSpecField);
if (!oldDocSpecXML.equals(newXML))
isSame = false;
}
if (isSame)
{
// Compare hopcount filter criteria.
Map filterRows = hopFilterManager.readRows(id);
Map newFilterRows = jobDescription.getHopCountFilters();
if (filterRows.size() != newFilterRows.size())
isSame = false;
else
{
for (String linkType : (Collection<String>)filterRows.keySet())
{
Long oldCount = (Long)filterRows.get(linkType);
Long newCount = (Long)newFilterRows.get(linkType);
if (oldCount == null || newCount == null)
{
isSame = false;
break;
}
else if (oldCount.longValue() != newCount.longValue())
{
isSame = false;
break;
}
}
}
}
if (!isSame)
values.put(lastCheckTimeField,null);
params.clear();
query = buildConjunctionClause(params,new ClauseDescription[]{
new UnitaryClause(idField,id)});
performUpdate(values," WHERE "+query,params,null);
scheduleManager.deleteRows(id);
hopFilterManager.deleteRows(id);
forcedParamManager.deleteRows(id);
}
else
{
// Insert
values.put(startTimeField,null);
values.put(lastCheckTimeField,null);
values.put(endTimeField,null);
values.put(statusField,statusToString(STATUS_INACTIVE));
values.put(lastTimeField,new Long(System.currentTimeMillis()));
values.put(idField,id);
performInsert(values,null);
}
// Write schedule records
scheduleManager.writeRows(id,jobDescription);
// Write hop filter rows
hopFilterManager.writeRows(id,jobDescription);
// Write forced params
forcedParamManager.writeRows(id,jobDescription);
cacheManager.invalidateKeys(ch);
break;
}
catch (ManifoldCFException e)
{
signalRollback();
throw e;
}
catch (Error e)
{
signalRollback();
throw e;
}
finally
{
endTransaction();
}
}
finally
{
cacheManager.leaveCache(ch);
}
}
catch (ManifoldCFException e)
{
if (e.getErrorCode() != ManifoldCFException.DATABASE_TRANSACTION_ABORT)
throw e;
sleepAmt = getSleepAmt();
continue;
}
finally
{
sleepFor(sleepAmt);
}
}
}
|
diff --git a/src/fi/helsinki/cs/scheduler3000/cli/SaveScheduleCsv.java b/src/fi/helsinki/cs/scheduler3000/cli/SaveScheduleCsv.java
index 30c3fa0..8daca7a 100644
--- a/src/fi/helsinki/cs/scheduler3000/cli/SaveScheduleCsv.java
+++ b/src/fi/helsinki/cs/scheduler3000/cli/SaveScheduleCsv.java
@@ -1,51 +1,51 @@
package fi.helsinki.cs.scheduler3000.cli;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import fi.helsinki.cs.scheduler3000.io.ScheduleWriter;
import fi.helsinki.cs.scheduler3000.io.ScheduleWriter.FORMAT;
import fi.helsinki.cs.scheduler3000.model.Schedule;
public class SaveScheduleCsv extends CliCommand {
private Schedule schedule;
public SaveScheduleCsv(Schedule schedule) {
this.schedule = schedule;
}
void run() {
saveScheduleDialog();
}
private void saveScheduleDialog() {
System.out.println("Give name of the file to open");
- System.out.println("Notice that file will be saved with .csv-extension, eg. \"myfile\" will be \"myfile.dat\" ");
+ System.out.println("Notice that file will be saved with .csv-extension, eg. \"myfile\" will be \"myfile.csv\" ");
printPrompt();
String filename = input.nextLine().trim() + ".csv";
while (true){
ScheduleWriter writer =
new ScheduleWriter(schedule, new File(filename), FORMAT.CSV );
if ( writer.write() ){
break;
}
else {
System.out.println("Please enter the name of the file again");
System.out.println("You can exit with " + endCommand);
filename = input.nextLine().trim() + ".dat";
if (filename.trim().toLowerCase().equals(endCommand)) {
return;
}
}
}
System.out.println("Schedule saved as \"" + filename + "\"");
}
}
| true | true | private void saveScheduleDialog() {
System.out.println("Give name of the file to open");
System.out.println("Notice that file will be saved with .csv-extension, eg. \"myfile\" will be \"myfile.dat\" ");
printPrompt();
String filename = input.nextLine().trim() + ".csv";
while (true){
ScheduleWriter writer =
new ScheduleWriter(schedule, new File(filename), FORMAT.CSV );
if ( writer.write() ){
break;
}
else {
System.out.println("Please enter the name of the file again");
System.out.println("You can exit with " + endCommand);
filename = input.nextLine().trim() + ".dat";
if (filename.trim().toLowerCase().equals(endCommand)) {
return;
}
}
}
System.out.println("Schedule saved as \"" + filename + "\"");
}
| private void saveScheduleDialog() {
System.out.println("Give name of the file to open");
System.out.println("Notice that file will be saved with .csv-extension, eg. \"myfile\" will be \"myfile.csv\" ");
printPrompt();
String filename = input.nextLine().trim() + ".csv";
while (true){
ScheduleWriter writer =
new ScheduleWriter(schedule, new File(filename), FORMAT.CSV );
if ( writer.write() ){
break;
}
else {
System.out.println("Please enter the name of the file again");
System.out.println("You can exit with " + endCommand);
filename = input.nextLine().trim() + ".dat";
if (filename.trim().toLowerCase().equals(endCommand)) {
return;
}
}
}
System.out.println("Schedule saved as \"" + filename + "\"");
}
|
diff --git a/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java b/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java
index 13b388b27..6c235c8fa 100644
--- a/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java
+++ b/common/src/main/java/de/escidoc/core/common/business/filter/SRURequest.java
@@ -1,337 +1,337 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE
* or http://www.escidoc.de/license.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at license/ESCIDOC.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2010 Fachinformationszentrum Karlsruhe Gesellschaft
* fuer wissenschaftlich-technische Information mbH and Max-Planck-
* Gesellschaft zur Foerderung der Wissenschaft e.V.
* All rights reserved. Use is subject to license terms.
*/
package de.escidoc.core.common.business.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.URL;
import java.net.URLEncoder;
import java.util.EnumMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.escidoc.core.common.business.Constants;
import de.escidoc.core.common.business.fedora.resources.ResourceType;
import de.escidoc.core.common.exceptions.system.WebserverSystemException;
import de.escidoc.core.common.servlet.EscidocServlet;
import de.escidoc.core.common.util.IOUtils;
import de.escidoc.core.common.util.configuration.EscidocConfiguration;
import de.escidoc.core.common.util.service.ConnectionUtility;
import de.escidoc.core.common.util.service.UserContext;
import de.escidoc.core.common.util.xml.XmlUtility;
/**
* Abstract super class for all types of SRU requests.
*
* @author André Schenk
*
* @spring.bean id="de.escidoc.core.common.business.filter.SRURequest"
*/
public class SRURequest {
/**
* Logging goes there.
*/
private static final Logger LOGGER = LoggerFactory
.getLogger(SRURequest.class);
// map from resource type to the corresponding admin index
private static final Map<ResourceType, String> ADMIN_INDEXES =
new EnumMap<ResourceType, String>(ResourceType.class);
static {
ADMIN_INDEXES.put(ResourceType.CONTAINER, "item_container_admin");
ADMIN_INDEXES.put(ResourceType.CONTENT_MODEL, "content_model_admin");
ADMIN_INDEXES.put(ResourceType.CONTENT_RELATION,
"content_relation_admin");
ADMIN_INDEXES.put(ResourceType.CONTEXT, "context_admin");
ADMIN_INDEXES.put(ResourceType.ITEM, "item_container_admin");
ADMIN_INDEXES.put(ResourceType.OU, "ou_admin");
}
private ConnectionUtility connectionUtility;
/**
* Send an explain request to the SRW servlet and write the response to the
* given writer. The given resource type determines the SRW index to use.
*
* @param output
* writer to which the SRW response is written
* @param resourceType
* resource type for which "explain" will be called
*
* @throws WebserverSystemException
* Thrown if the connection to the SRW servlet failed.
*/
public final void explain(
final Writer output, final ResourceType resourceType)
throws WebserverSystemException {
try {
final String url =
EscidocConfiguration.getInstance().get(
EscidocConfiguration.SRW_URL)
+ "/search/"
+ ADMIN_INDEXES.get(resourceType)
+ "?operation=explain&version=1.1";
final HttpResponse response =
connectionUtility.getRequestURL(new URL(url), null);
if (response != null) {
final HttpEntity entity = response.getEntity();
BufferedReader input = null;
try {
input =
new BufferedReader(new InputStreamReader(
entity.getContent(), getCharset(entity
.getContentType().getValue())));
String line;
while ((line = input.readLine()) != null) {
output.write(line);
output.write('\n');
}
}
finally {
IOUtils.closeStream(input);
}
}
}
catch (IOException e) {
throw new WebserverSystemException(e);
}
}
/**
* Extract the charset information from the given content type header.
*
* @param contentType
* content type header
* @return charset information
*/
private static String getCharset(final String contentType) {
String result = XmlUtility.CHARACTER_ENCODING;
if (contentType != null) {
// FIXME better use javax.mail.internet.ContentType
final String[] parameters = contentType.split(";");
for (final String parameter : parameters) {
if (parameter.startsWith("charset")) {
final String[] charset = parameter.split("=");
if (charset.length > 1) {
result = charset[1];
}
break;
}
}
}
return result;
}
/**
* Send a searchRetrieve request to the SRW servlet and write the response
* to the given writer. The given resource type determines the SRW index to
* use.
*
* @param output
* Writer to which the SRW response is written.
* @param resourceTypes
* Resource types to be expected in the SRW response.
* @param parameters
* SRU request parameters
*
* @throws WebserverSystemException
* Thrown if the connection to the SRW servlet failed.
*/
public final void searchRetrieve(
final Writer output, final ResourceType[] resourceTypes,
final SRURequestParameters parameters) throws WebserverSystemException {
searchRetrieve(output, resourceTypes, parameters.getQuery(),
parameters.getMaximumRecords(), parameters.getStartRecord(),
parameters.getExtraData(), parameters.getRecordPacking());
}
/**
* Send a searchRetrieve request to the SRW servlet and write the response
* to the given writer. The given resource type determines the SRW index to
* use.
*
* @param output
* Writer to which the SRW response is written.
* @param resourceTypes
* Resource types to be expected in the SRW response.
* @param query
* Contains a query expressed in CQL to be processed by the
* server.
* @param limit
* The number of records requested to be returned. The value must
* be 0 or greater. Default value if not supplied is determined
* by the server. The server MAY return less than this number of
* records, for example if there are fewer matching records than
* requested, but MUST NOT return more than this number of
* records.
* @param offset
* The position within the sequence of matched records of the
* first record to be returned. The first position in the
* sequence is 1. The value supplied MUST be greater than 0.
* @param extraData
* map with additional parameters like user id, role id
* @param recordPacking
* A string to determine how the record should be escaped in the
* response. Defined values are 'string' and 'xml'. The default
* is 'xml'.
*
* @throws WebserverSystemException
* Thrown if the connection to the SRW servlet failed.
*/
public final void searchRetrieve(
final Writer output, final ResourceType[] resourceTypes,
final String query, final int limit, final int offset,
final Map<String, String> extraData, final RecordPacking recordPacking)
throws WebserverSystemException {
try {
final StringBuilder resourceTypeQuery = new StringBuilder();
for (final ResourceType resourceType : resourceTypes) {
if (resourceTypeQuery.length() > 0) {
resourceTypeQuery.append(" OR ");
}
resourceTypeQuery.append("\"type\"=");
resourceTypeQuery.append(resourceType.getLabel());
}
final StringBuilder internalQuery = new StringBuilder();
if ((query != null) && (query.length() > 0)) {
if (resourceTypeQuery.length() > 0) {
internalQuery.append('(');
internalQuery.append(resourceTypeQuery);
internalQuery.append(") AND ");
}
internalQuery.append('(').append(query).append(')');
}
else {
internalQuery.append(resourceTypeQuery);
}
String url =
EscidocConfiguration.getInstance().get(
EscidocConfiguration.SRW_URL)
+ "/search/"
+ ADMIN_INDEXES.get(resourceTypes[0])
+ '?'
+ Constants.SRU_PARAMETER_OPERATION
+ "=searchRetrieve&"
+ Constants.SRU_PARAMETER_VERSION
+ "=1.1&"
+ Constants.SRU_PARAMETER_QUERY
+ '='
+ URLEncoder.encode(internalQuery.toString(),
XmlUtility.CHARACTER_ENCODING);
if (limit != LuceneRequestParameters.DEFAULT_MAXIMUM_RECORDS) {
url +=
'&' + Constants.SRU_PARAMETER_MAXIMUM_RECORDS + '=' + limit;
}
if (offset != LuceneRequestParameters.DEFAULT_START_RECORD) {
url +=
'&' + Constants.SRU_PARAMETER_START_RECORD + '=' + offset;
}
if (extraData != null) {
- StringBuffer urlBuffer = new StringBuffer(url);
+ final StringBuilder urlBuffer = new StringBuilder(url);
for (final Entry<String, String> entry : extraData.entrySet()) {
urlBuffer.append('&');
urlBuffer.append(entry.getKey());
urlBuffer.append('=');
urlBuffer.append(entry.getValue());
}
url = urlBuffer.toString();
}
if (recordPacking != null) {
url +=
'&' + Constants.SRU_PARAMETER_RECORD_PACKING + '='
+ recordPacking.getType();
}
if (!UserContext.isRestAccess()) {
url +=
'&' + Constants.SRU_PARAMETER_RECORD_SCHEMA
+ "=eSciDocSoap";
}
LOGGER.info("SRW URL: " + url);
final Cookie cookie =
new BasicClientCookie(EscidocServlet.COOKIE_LOGIN,
UserContext.getHandle());
final HttpResponse response =
connectionUtility.getRequestURL(new URL(url), cookie);
if (response != null) {
final HttpEntity entity = response.getEntity();
BufferedReader input = null;
try {
input =
new BufferedReader(new InputStreamReader(
entity.getContent(), getCharset(entity
.getContentType().getValue())));
String line;
while ((line = input.readLine()) != null) {
output.write(line);
output.write('\n');
}
}
finally {
IOUtils.closeStream(input);
}
}
}
catch (IOException e) {
throw new WebserverSystemException(e);
}
}
/**
* Set the connection utility.
*
* @param connectionUtility
* ConnectionUtility.
*
* @spring.property ref="escidoc.core.common.util.service.ConnectionUtility"
*/
public void setConnectionUtility(final ConnectionUtility connectionUtility) {
this.connectionUtility = connectionUtility;
}
}
| true | true | public final void searchRetrieve(
final Writer output, final ResourceType[] resourceTypes,
final String query, final int limit, final int offset,
final Map<String, String> extraData, final RecordPacking recordPacking)
throws WebserverSystemException {
try {
final StringBuilder resourceTypeQuery = new StringBuilder();
for (final ResourceType resourceType : resourceTypes) {
if (resourceTypeQuery.length() > 0) {
resourceTypeQuery.append(" OR ");
}
resourceTypeQuery.append("\"type\"=");
resourceTypeQuery.append(resourceType.getLabel());
}
final StringBuilder internalQuery = new StringBuilder();
if ((query != null) && (query.length() > 0)) {
if (resourceTypeQuery.length() > 0) {
internalQuery.append('(');
internalQuery.append(resourceTypeQuery);
internalQuery.append(") AND ");
}
internalQuery.append('(').append(query).append(')');
}
else {
internalQuery.append(resourceTypeQuery);
}
String url =
EscidocConfiguration.getInstance().get(
EscidocConfiguration.SRW_URL)
+ "/search/"
+ ADMIN_INDEXES.get(resourceTypes[0])
+ '?'
+ Constants.SRU_PARAMETER_OPERATION
+ "=searchRetrieve&"
+ Constants.SRU_PARAMETER_VERSION
+ "=1.1&"
+ Constants.SRU_PARAMETER_QUERY
+ '='
+ URLEncoder.encode(internalQuery.toString(),
XmlUtility.CHARACTER_ENCODING);
if (limit != LuceneRequestParameters.DEFAULT_MAXIMUM_RECORDS) {
url +=
'&' + Constants.SRU_PARAMETER_MAXIMUM_RECORDS + '=' + limit;
}
if (offset != LuceneRequestParameters.DEFAULT_START_RECORD) {
url +=
'&' + Constants.SRU_PARAMETER_START_RECORD + '=' + offset;
}
if (extraData != null) {
StringBuffer urlBuffer = new StringBuffer(url);
for (final Entry<String, String> entry : extraData.entrySet()) {
urlBuffer.append('&');
urlBuffer.append(entry.getKey());
urlBuffer.append('=');
urlBuffer.append(entry.getValue());
}
url = urlBuffer.toString();
}
if (recordPacking != null) {
url +=
'&' + Constants.SRU_PARAMETER_RECORD_PACKING + '='
+ recordPacking.getType();
}
if (!UserContext.isRestAccess()) {
url +=
'&' + Constants.SRU_PARAMETER_RECORD_SCHEMA
+ "=eSciDocSoap";
}
LOGGER.info("SRW URL: " + url);
final Cookie cookie =
new BasicClientCookie(EscidocServlet.COOKIE_LOGIN,
UserContext.getHandle());
final HttpResponse response =
connectionUtility.getRequestURL(new URL(url), cookie);
if (response != null) {
final HttpEntity entity = response.getEntity();
BufferedReader input = null;
try {
input =
new BufferedReader(new InputStreamReader(
entity.getContent(), getCharset(entity
.getContentType().getValue())));
String line;
while ((line = input.readLine()) != null) {
output.write(line);
output.write('\n');
}
}
finally {
IOUtils.closeStream(input);
}
}
}
catch (IOException e) {
throw new WebserverSystemException(e);
}
}
| public final void searchRetrieve(
final Writer output, final ResourceType[] resourceTypes,
final String query, final int limit, final int offset,
final Map<String, String> extraData, final RecordPacking recordPacking)
throws WebserverSystemException {
try {
final StringBuilder resourceTypeQuery = new StringBuilder();
for (final ResourceType resourceType : resourceTypes) {
if (resourceTypeQuery.length() > 0) {
resourceTypeQuery.append(" OR ");
}
resourceTypeQuery.append("\"type\"=");
resourceTypeQuery.append(resourceType.getLabel());
}
final StringBuilder internalQuery = new StringBuilder();
if ((query != null) && (query.length() > 0)) {
if (resourceTypeQuery.length() > 0) {
internalQuery.append('(');
internalQuery.append(resourceTypeQuery);
internalQuery.append(") AND ");
}
internalQuery.append('(').append(query).append(')');
}
else {
internalQuery.append(resourceTypeQuery);
}
String url =
EscidocConfiguration.getInstance().get(
EscidocConfiguration.SRW_URL)
+ "/search/"
+ ADMIN_INDEXES.get(resourceTypes[0])
+ '?'
+ Constants.SRU_PARAMETER_OPERATION
+ "=searchRetrieve&"
+ Constants.SRU_PARAMETER_VERSION
+ "=1.1&"
+ Constants.SRU_PARAMETER_QUERY
+ '='
+ URLEncoder.encode(internalQuery.toString(),
XmlUtility.CHARACTER_ENCODING);
if (limit != LuceneRequestParameters.DEFAULT_MAXIMUM_RECORDS) {
url +=
'&' + Constants.SRU_PARAMETER_MAXIMUM_RECORDS + '=' + limit;
}
if (offset != LuceneRequestParameters.DEFAULT_START_RECORD) {
url +=
'&' + Constants.SRU_PARAMETER_START_RECORD + '=' + offset;
}
if (extraData != null) {
final StringBuilder urlBuffer = new StringBuilder(url);
for (final Entry<String, String> entry : extraData.entrySet()) {
urlBuffer.append('&');
urlBuffer.append(entry.getKey());
urlBuffer.append('=');
urlBuffer.append(entry.getValue());
}
url = urlBuffer.toString();
}
if (recordPacking != null) {
url +=
'&' + Constants.SRU_PARAMETER_RECORD_PACKING + '='
+ recordPacking.getType();
}
if (!UserContext.isRestAccess()) {
url +=
'&' + Constants.SRU_PARAMETER_RECORD_SCHEMA
+ "=eSciDocSoap";
}
LOGGER.info("SRW URL: " + url);
final Cookie cookie =
new BasicClientCookie(EscidocServlet.COOKIE_LOGIN,
UserContext.getHandle());
final HttpResponse response =
connectionUtility.getRequestURL(new URL(url), cookie);
if (response != null) {
final HttpEntity entity = response.getEntity();
BufferedReader input = null;
try {
input =
new BufferedReader(new InputStreamReader(
entity.getContent(), getCharset(entity
.getContentType().getValue())));
String line;
while ((line = input.readLine()) != null) {
output.write(line);
output.write('\n');
}
}
finally {
IOUtils.closeStream(input);
}
}
}
catch (IOException e) {
throw new WebserverSystemException(e);
}
}
|
diff --git a/WEB-INF/src/controller/BuyItemAction.java b/WEB-INF/src/controller/BuyItemAction.java
index bc8a6bd..8f8a2f3 100644
--- a/WEB-INF/src/controller/BuyItemAction.java
+++ b/WEB-INF/src/controller/BuyItemAction.java
@@ -1,138 +1,139 @@
package controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;
import databean.Item;
import databean.Message;
import databean.User;
import formbeans.BuyItemForm;
import model.ItemDAO;
import model.MessageDAO;
import model.Model;
import model.UserDAO;
public class BuyItemAction extends Action{
private FormBeanFactory<BuyItemForm> formBeanFactory = FormBeanFactory.getInstance(BuyItemForm.class, "<>\"");
ItemDAO itemDAO;
MessageDAO messageDAO;
UserDAO userDAO;
public BuyItemAction(Model model){
itemDAO = model.getItemDAO();
messageDAO = model.getMessageDAO();
userDAO = model.getUserDAO();
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "buyItem.do";
}
@Override
public String perform(HttpServletRequest request) {
// TODO Auto-generated method stub
BuyItemForm form = formBeanFactory.create(request);
List<String> errors = new ArrayList<String>();
request.setAttribute("errors", errors);
errors.addAll(form.getValidationErrors());
if (errors.size() != 0) return "index.jsp";
int itemId = form.getItemIdAsInt();
try {
if(itemId > itemDAO.getAllItems().length)
return "index.jsp";
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int buyType = form.getBuyTypeAsInt();
User curUser = (User) request.getSession(false).getAttribute("user");
if(buyType == 1){
try {
Item item = itemDAO.getItemById(itemId);
int credit = item.getCredit();
if(curUser.getCredit() - credit < 0){
System.out.println(curUser.getCredit());
errors.add("Not enough credits.");
request.setAttribute("posted", item);
return "item_page.jsp";
}
userDAO.setCredit(curUser.getCredit() - credit, curUser.getUserName());
User owner = item.getOwner();
userDAO.setCredit(owner.getCredit() + credit, owner.getUserName());
itemDAO.closeItem(itemId);
curUser.setCredit(curUser.getCredit() - credit);
request.setAttribute("success", "Transaction was successfully made. Your " +
"remaining credits are " + curUser.getCredit());
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
Item item = itemDAO.getItemById(itemId);
- String url = "http://localhost:8080/Breeze/complete.do?buyType=" + buyType +
- "&buyerName=" + curUser.getUserName() + "&itemId=" + item.getId();
+ String url = "<a href="http://localhost:8080/Breeze/complete.do?buyType=" + buyType +
+ "&buyerName=" + curUser.getUserName() + "&itemId=" + item.getId() +"">link</a>";
String[] buyTypeName = {"exchange with items", "exchange for credits", "exchange with items"};
Message msg = new Message();
- String content = "Your item: " + item.getItemName() + " has been responded " +
- "by the user: " + curUser.getUserName() + ", email: " + curUser.getEmail() +
- ", who agreed to " + buyTypeName[buyType - 2] + ". Click the link below " +
- "if you want to make a transaction with him. \n" + url;
+ String content = "Your item (" + item.getItemName() + ") has been responded " +
+ "by " + curUser.getUserName() +
+ ", who agreed to " + buyTypeName[buyType - 2] + ". Click this " + url +
+ " if you want to make a transaction with him.";
+ System.out.println(content.length());
msg.setContent(content);
msg.setSender(curUser);
msg.setReceiver(item.getOwner());
msg.setTitle("Item Requested!");
msg.setSentDate(new Date());
Message msg2 = new Message();
String content2 = "The item: " + item.getItemName() + " you requested has been sent " +
"to the user: " + item.getOwner().getUserName() + ", email: " + item.getOwner().getEmail() +
". You agreed to " + buyTypeName[buyType - 2] + ". You will get automatically message notification" +
" if the item owner makes the transaction with you.";
msg2.setContent(content2);
msg2.setSender(item.getOwner());
msg2.setReceiver(curUser);
msg2.setTitle("Request Item Confirmation!");
msg2.setSentDate(new Date());
try {
messageDAO.create(msg);
messageDAO.create(msg2);
} catch (DAOException e) {
errors.add(e.getMessage());
if(item.getType() == 1)
request.setAttribute("posted", item);
else
request.setAttribute("requested", item);
return "item_page.jsp";
}
request.setAttribute("success", "Your request has been sent.");
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "showMessage.do";
}
}
| false | true | public String perform(HttpServletRequest request) {
// TODO Auto-generated method stub
BuyItemForm form = formBeanFactory.create(request);
List<String> errors = new ArrayList<String>();
request.setAttribute("errors", errors);
errors.addAll(form.getValidationErrors());
if (errors.size() != 0) return "index.jsp";
int itemId = form.getItemIdAsInt();
try {
if(itemId > itemDAO.getAllItems().length)
return "index.jsp";
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int buyType = form.getBuyTypeAsInt();
User curUser = (User) request.getSession(false).getAttribute("user");
if(buyType == 1){
try {
Item item = itemDAO.getItemById(itemId);
int credit = item.getCredit();
if(curUser.getCredit() - credit < 0){
System.out.println(curUser.getCredit());
errors.add("Not enough credits.");
request.setAttribute("posted", item);
return "item_page.jsp";
}
userDAO.setCredit(curUser.getCredit() - credit, curUser.getUserName());
User owner = item.getOwner();
userDAO.setCredit(owner.getCredit() + credit, owner.getUserName());
itemDAO.closeItem(itemId);
curUser.setCredit(curUser.getCredit() - credit);
request.setAttribute("success", "Transaction was successfully made. Your " +
"remaining credits are " + curUser.getCredit());
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
Item item = itemDAO.getItemById(itemId);
String url = "http://localhost:8080/Breeze/complete.do?buyType=" + buyType +
"&buyerName=" + curUser.getUserName() + "&itemId=" + item.getId();
String[] buyTypeName = {"exchange with items", "exchange for credits", "exchange with items"};
Message msg = new Message();
String content = "Your item: " + item.getItemName() + " has been responded " +
"by the user: " + curUser.getUserName() + ", email: " + curUser.getEmail() +
", who agreed to " + buyTypeName[buyType - 2] + ". Click the link below " +
"if you want to make a transaction with him. \n" + url;
msg.setContent(content);
msg.setSender(curUser);
msg.setReceiver(item.getOwner());
msg.setTitle("Item Requested!");
msg.setSentDate(new Date());
Message msg2 = new Message();
String content2 = "The item: " + item.getItemName() + " you requested has been sent " +
"to the user: " + item.getOwner().getUserName() + ", email: " + item.getOwner().getEmail() +
". You agreed to " + buyTypeName[buyType - 2] + ". You will get automatically message notification" +
" if the item owner makes the transaction with you.";
msg2.setContent(content2);
msg2.setSender(item.getOwner());
msg2.setReceiver(curUser);
msg2.setTitle("Request Item Confirmation!");
msg2.setSentDate(new Date());
try {
messageDAO.create(msg);
messageDAO.create(msg2);
} catch (DAOException e) {
errors.add(e.getMessage());
if(item.getType() == 1)
request.setAttribute("posted", item);
else
request.setAttribute("requested", item);
return "item_page.jsp";
}
request.setAttribute("success", "Your request has been sent.");
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "showMessage.do";
}
| public String perform(HttpServletRequest request) {
// TODO Auto-generated method stub
BuyItemForm form = formBeanFactory.create(request);
List<String> errors = new ArrayList<String>();
request.setAttribute("errors", errors);
errors.addAll(form.getValidationErrors());
if (errors.size() != 0) return "index.jsp";
int itemId = form.getItemIdAsInt();
try {
if(itemId > itemDAO.getAllItems().length)
return "index.jsp";
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int buyType = form.getBuyTypeAsInt();
User curUser = (User) request.getSession(false).getAttribute("user");
if(buyType == 1){
try {
Item item = itemDAO.getItemById(itemId);
int credit = item.getCredit();
if(curUser.getCredit() - credit < 0){
System.out.println(curUser.getCredit());
errors.add("Not enough credits.");
request.setAttribute("posted", item);
return "item_page.jsp";
}
userDAO.setCredit(curUser.getCredit() - credit, curUser.getUserName());
User owner = item.getOwner();
userDAO.setCredit(owner.getCredit() + credit, owner.getUserName());
itemDAO.closeItem(itemId);
curUser.setCredit(curUser.getCredit() - credit);
request.setAttribute("success", "Transaction was successfully made. Your " +
"remaining credits are " + curUser.getCredit());
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
Item item = itemDAO.getItemById(itemId);
String url = "<a href="http://localhost:8080/Breeze/complete.do?buyType=" + buyType +
"&buyerName=" + curUser.getUserName() + "&itemId=" + item.getId() +"">link</a>";
String[] buyTypeName = {"exchange with items", "exchange for credits", "exchange with items"};
Message msg = new Message();
String content = "Your item (" + item.getItemName() + ") has been responded " +
"by " + curUser.getUserName() +
", who agreed to " + buyTypeName[buyType - 2] + ". Click this " + url +
" if you want to make a transaction with him.";
System.out.println(content.length());
msg.setContent(content);
msg.setSender(curUser);
msg.setReceiver(item.getOwner());
msg.setTitle("Item Requested!");
msg.setSentDate(new Date());
Message msg2 = new Message();
String content2 = "The item: " + item.getItemName() + " you requested has been sent " +
"to the user: " + item.getOwner().getUserName() + ", email: " + item.getOwner().getEmail() +
". You agreed to " + buyTypeName[buyType - 2] + ". You will get automatically message notification" +
" if the item owner makes the transaction with you.";
msg2.setContent(content2);
msg2.setSender(item.getOwner());
msg2.setReceiver(curUser);
msg2.setTitle("Request Item Confirmation!");
msg2.setSentDate(new Date());
try {
messageDAO.create(msg);
messageDAO.create(msg2);
} catch (DAOException e) {
errors.add(e.getMessage());
if(item.getType() == 1)
request.setAttribute("posted", item);
else
request.setAttribute("requested", item);
return "item_page.jsp";
}
request.setAttribute("success", "Your request has been sent.");
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "showMessage.do";
}
|
diff --git a/src/com/redhat/ceylon/compiler/java/tools/LanguageCompiler.java b/src/com/redhat/ceylon/compiler/java/tools/LanguageCompiler.java
index db9bd05fb..839d81b5b 100755
--- a/src/com/redhat/ceylon/compiler/java/tools/LanguageCompiler.java
+++ b/src/com/redhat/ceylon/compiler/java/tools/LanguageCompiler.java
@@ -1,656 +1,656 @@
/*
* Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*/
package com.redhat.ceylon.compiler.java.tools;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import javax.annotation.processing.Processor;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardLocation;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import com.redhat.ceylon.compiler.java.codegen.CeylonClassWriter;
import com.redhat.ceylon.compiler.java.codegen.CeylonCompilationUnit;
import com.redhat.ceylon.compiler.java.codegen.CeylonFileObject;
import com.redhat.ceylon.compiler.java.codegen.CeylonTransformer;
import com.redhat.ceylon.compiler.java.loader.CeylonEnter;
import com.redhat.ceylon.compiler.java.loader.CeylonModelLoader;
import com.redhat.ceylon.compiler.java.loader.model.CompilerModuleManager;
import com.redhat.ceylon.compiler.java.util.Timer;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager;
import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleValidator;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits;
import com.redhat.ceylon.compiler.typechecker.io.VFS;
import com.redhat.ceylon.compiler.typechecker.io.VirtualFile;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Modules;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonParser;
import com.redhat.ceylon.compiler.typechecker.parser.LexError;
import com.redhat.ceylon.compiler.typechecker.parser.ParseError;
import com.redhat.ceylon.compiler.typechecker.parser.RecognitionError;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit;
import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.CompletionFailure;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.jvm.ClassWriter;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.main.OptionName;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Context.SourceLanguage.Language;
import com.sun.tools.javac.util.Convert;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.util.Pair;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.util.Position.LineMap;
public class LanguageCompiler extends JavaCompiler {
/** The context key for the phasedUnits. */
protected static final Context.Key<PhasedUnits> phasedUnitsKey = new Context.Key<PhasedUnits>();
public static final Context.Key<PhasedUnitsManager> phasedUnitsManagerKey = new Context.Key<PhasedUnitsManager>();
/** The context key for the ceylon context. */
public static final Context.Key<com.redhat.ceylon.compiler.typechecker.context.Context> ceylonContextKey = new Context.Key<com.redhat.ceylon.compiler.typechecker.context.Context>();
private final CeylonTransformer gen;
private final PhasedUnits phasedUnits;
private final PhasedUnitsManager phasedUnitsManager;
private final com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext;
private final VFS vfs;
private CeylonModelLoader modelLoader;
private CeylonEnter ceylonEnter;
private Options options;
private Timer timer;
private boolean isBootstrap;
private boolean addedDefaultModuleToClassPath;
/** Get the PhasedUnits instance for this context. */
public static PhasedUnits getPhasedUnitsInstance(final Context context) {
PhasedUnits phasedUnits = context.get(phasedUnitsKey);
if (phasedUnits == null) {
com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext = getCeylonContextInstance(context);
phasedUnits = new PhasedUnits(ceylonContext, new ModuleManagerFactory(){
@Override
public ModuleManager createModuleManager(com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext) {
PhasedUnitsManager phasedUnitsManager = getPhasedUnitsManagerInstance(context);
return phasedUnitsManager.getModuleManager();
}
});
context.put(phasedUnitsKey, phasedUnits);
}
return phasedUnits;
}
public static PhasedUnitsManager getPhasedUnitsManagerInstance(final Context context) {
PhasedUnitsManager phasedUnitsManager = context.get(phasedUnitsManagerKey);
if (phasedUnitsManager == null) {
return new PhasedUnitsManager() {
@Override
public ModuleManager getModuleManager() {
com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext = getCeylonContextInstance(context);
return new CompilerModuleManager(ceylonContext, context);
}
@Override
public void resolveDependencies() {
com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext = getCeylonContextInstance(context);
PhasedUnits phasedUnits = getPhasedUnitsInstance(context);
ModuleValidator validator = new ModuleValidator(ceylonContext, phasedUnits);
validator.verifyModuleDependencyTree();
}
@Override
public PhasedUnit getExternalSourcePhasedUnit(
VirtualFile srcDir, VirtualFile file) {
return null;
}
@Override
public Iterable<PhasedUnit> getPhasedUnitsForExtraPhase(
java.util.List<PhasedUnit> sourceUnits) {
return sourceUnits;
}
@Override
public void extraPhasesApplied() {
}
};
}
return phasedUnitsManager;
}
/** Get the Ceylon context instance for this context. */
public static com.redhat.ceylon.compiler.typechecker.context.Context getCeylonContextInstance(Context context) {
com.redhat.ceylon.compiler.typechecker.context.Context ceylonContext = context.get(ceylonContextKey);
if (ceylonContext == null) {
CeyloncFileManager fileManager = (CeyloncFileManager) context.get(JavaFileManager.class);
VFS vfs = new VFS();
ceylonContext = new com.redhat.ceylon.compiler.typechecker.context.Context(fileManager.getRepositoryManager(), vfs);
context.put(ceylonContextKey, ceylonContext);
}
return ceylonContext;
}
/** Get the JavaCompiler instance for this context. */
public static JavaCompiler instance(Context context) {
Options options = Options.instance(context);
options.put("-Xprefer", "source");
// make sure it's registered
CeylonLog.instance(context);
CeylonEnter.instance(context);
CeylonClassWriter.instance(context);
JavaCompiler instance = context.get(compilerKey);
if (instance == null)
instance = new LanguageCompiler(context);
return instance;
}
public LanguageCompiler(Context context) {
super(context);
ceylonContext = getCeylonContextInstance(context);
vfs = ceylonContext.getVfs();
phasedUnitsManager = getPhasedUnitsManagerInstance(context);
phasedUnits = getPhasedUnitsInstance(context);
try {
gen = CeylonTransformer.getInstance(context);
} catch (Exception e) {
throw new RuntimeException(e);
}
modelLoader = (CeylonModelLoader) CeylonModelLoader.instance(context);
ceylonEnter = CeylonEnter.instance(context);
options = Options.instance(context);
isBootstrap = options.get(OptionName.BOOTSTRAPCEYLON) != null;
timer = Timer.instance(context);
}
/**
* Parse contents of file.
* @param filename The name of the file to be parsed.
*/
public JCTree.JCCompilationUnit parse(JavaFileObject filename) {
JavaFileObject prev = log.useSource(filename);
try {
JCTree.JCCompilationUnit t;
if (filename.getName().endsWith(".java")) {
t = parse(filename, readSource(filename));
} else {
t = ceylonParse(filename, readSource(filename));
}
if (t.endPositions != null)
log.setEndPosTable(filename, t.endPositions);
return t;
} finally {
log.useSource(prev);
}
}
protected JCCompilationUnit parse(JavaFileObject filename, CharSequence readSource) {
// FIXME
if (filename instanceof CeylonFileObject)
return ceylonParse(filename, readSource);
else
return super.parse(filename, readSource);
}
public static interface PhasedUnitsManager {
ModuleManager getModuleManager();
void resolveDependencies();
PhasedUnit getExternalSourcePhasedUnit(VirtualFile srcDir, VirtualFile file);
Iterable<PhasedUnit> getPhasedUnitsForExtraPhase(java.util.List<PhasedUnit> sourceUnits);
void extraPhasesApplied();
}
private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) {
if(ceylonEnter.hasRun())
throw new RuntimeException("Trying to load new source file after CeylonEnter has been called: "+filename);
try {
ModuleManager moduleManager = phasedUnits.getModuleManager();
File sourceFile = new File(filename.getName());
// FIXME: temporary solution
VirtualFile file = vfs.getFromFile(sourceFile);
VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile));
String source = readSource.toString();
char[] chars = source.toCharArray();
LineMap map = Position.makeLineMap(chars, chars.length, false);
PhasedUnit phasedUnit = null;
PhasedUnit externalPhasedUnit = phasedUnitsManager.getExternalSourcePhasedUnit(srcDir, file);
if (externalPhasedUnit != null) {
phasedUnit = new CeylonPhasedUnit(externalPhasedUnit, filename, map);
phasedUnits.addPhasedUnit(externalPhasedUnit.getUnitFile(), phasedUnit);
gen.setMap(map);
String pkgName = phasedUnit.getPackage().getQualifiedNameString();
if ("".equals(pkgName)) {
pkgName = null;
}
return gen.makeJCCompilationUnitPlaceholder(phasedUnit.getCompilationUnit(), filename, pkgName, phasedUnit);
}
if (phasedUnit == null) {
ANTLRStringStream input = new ANTLRStringStream(source);
CeylonLexer lexer = new CeylonLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CeylonParser parser = new CeylonParser(tokens);
CompilationUnit cu = parser.compilationUnit();
java.util.List<LexError> lexerErrors = lexer.getErrors();
for (LexError le : lexerErrors) {
printError(le, le.getMessage(), "ceylon.lexer", map);
}
java.util.List<ParseError> parserErrors = parser.getErrors();
for (ParseError pe : parserErrors) {
printError(pe, pe.getMessage(), "ceylon.parser", map);
}
if (lexer.getNumberOfSyntaxErrors() != 0) {
log.printErrLines("ceylon.lexer.failed");
} else if (parser.getNumberOfSyntaxErrors() != 0) {
log.printErrLines("ceylon.parser.failed");
} else {
// FIXME: this is bad in many ways
String pkgName = getPackage(filename);
// make a Package with no module yet, we will resolve them later
/*
* Stef: see javadoc for findOrCreateModulelessPackage() for why this is here.
*/
com.redhat.ceylon.compiler.typechecker.model.Package p = modelLoader.findOrCreateModulelessPackage(pkgName == null ? "" : pkgName);
phasedUnit = new CeylonPhasedUnit(file, srcDir, cu, p, moduleManager, ceylonContext, filename, map);
phasedUnits.addPhasedUnit(file, phasedUnit);
gen.setMap(map);
return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName, phasedUnit);
}
}
- } catch (CompilerErrorException e) {
- log.error("ceylon", e.getMessage());
+ } catch (RuntimeException e) {
+ throw e;
} catch (Exception e) {
- log.error("ceylon", e);
+ throw new RuntimeException(e);
}
JCCompilationUnit result = make.TopLevel(List.<JCAnnotation> nil(), null, List.<JCTree> of(make.Erroneous()));
result.sourcefile = filename;
return result;
}
@Override
public List<JCCompilationUnit> parseFiles(Iterable<JavaFileObject> fileObjects) {
timer.startTask("parse");
/*
* Stef: see javadoc for fixDefaultPackage() for why this is here.
*/
modelLoader.fixDefaultPackage();
List<JCCompilationUnit> trees = super.parseFiles(fileObjects);
timer.startTask("loadCompiledModules");
LinkedList<JCCompilationUnit> moduleTrees = new LinkedList<JCCompilationUnit>();
// now load modules and associate their moduleless packages with the corresponding modules
loadCompiledModules(trees, moduleTrees);
for (JCCompilationUnit moduleTree : moduleTrees) {
trees = trees.append(moduleTree);
}
/*
* Stef: see javadoc for cacheModulelessPackages() for why this is here.
*/
modelLoader.cacheModulelessPackages();
timer.endTask();
return trees;
}
private void loadCompiledModules(List<JCCompilationUnit> trees, LinkedList<JCCompilationUnit> moduleTrees) {
phasedUnits.visitModules();
Modules modules = ceylonContext.getModules();
// now make sure the phase units have their modules and packages set correctly
for (PhasedUnit pu : phasedUnits.getPhasedUnits()) {
Package pkg = pu.getPackage();
loadModuleFromSource(pkg, modules, moduleTrees, trees);
}
// also make sure we have packages and modules set up for every Java file we compile
for(JCCompilationUnit cu : trees){
// skip Ceylon CUs
if(cu instanceof CeylonCompilationUnit)
continue;
String packageName = "";
if(cu.pid != null)
packageName = TreeInfo.fullName(cu.pid).toString();
/*
* Stef: see javadoc for findOrCreateModulelessPackage() for why this is here.
*/
Package pkg = modelLoader.findOrCreateModulelessPackage(packageName);
loadModuleFromSource(pkg, modules, moduleTrees, trees);
}
}
private void loadModuleFromSource(Package pkg, Modules modules, LinkedList<JCCompilationUnit> moduleTrees, List<JCCompilationUnit> parsedTrees) {
// skip it if we already resolved the package
if(pkg.getModule() != null){
// make sure the default module is always added to the classpath, it will be the only one to have a module
if(!addedDefaultModuleToClassPath && pkg.getModule().isDefault()){
addedDefaultModuleToClassPath = true;
ceylonEnter.addOutputModuleToClassPath(pkg.getModule());
}
return;
}
String pkgName = pkg.getQualifiedNameString();
Module module = null;
// do we have a module for this package?
// FIXME: is this true? what if we have a module.ceylon at toplevel?
if(pkgName.isEmpty())
module = modules.getDefaultModule();
else{
for(Module m : modules.getListOfModules()){
if(Util.isSubPackage(m.getNameAsString(), pkgName)){
module = m;
break;
}
}
if(module == null){
module = loadModuleFromSource(pkgName, moduleTrees, parsedTrees);
}
else if (! module.isAvailable()) {
loadModuleFromSource(pkgName, moduleTrees, parsedTrees);
}
if(module == null){
// no declaration for it, must be the default module, unless we're bootstrapping the language module,
// because we have some com.redhat.ceylon packages that must go in the language module
if(isBootstrap)
module = modules.getLanguageModule();
else
module = modules.getDefaultModule();
}
}
// bind module and package together
pkg.setModule(module);
module.getPackages().add(pkg);
// automatically add this module's jar to the classpath if it exists
ceylonEnter.addOutputModuleToClassPath(module);
}
private Module loadModuleFromSource(String pkgName, LinkedList<JCCompilationUnit> moduleTrees, List<JCCompilationUnit> parsedTrees) {
if(pkgName.isEmpty())
return null;
String moduleClassName = pkgName + ".module";
JavaFileObject fileObject;
try {
if(options.get(OptionName.VERBOSE) != null){
Log.printLines(log.noticeWriter, "[Trying to load module "+moduleClassName+"]");
}
fileObject = fileManager.getJavaFileForInput(StandardLocation.SOURCE_PATH, moduleClassName, Kind.SOURCE);
if(options.get(OptionName.VERBOSE) != null){
Log.printLines(log.noticeWriter, "[Got file object: "+fileObject+"]");
}
} catch (IOException e) {
e.printStackTrace();
return loadModuleFromSource(getParentPackage(pkgName), moduleTrees, parsedTrees);
}
if(fileObject != null){
// first make sure we're not already compiling it: this can happen if we have several versions of the
// same module already loaded: we will get one which isn't the one we compile, but that's not the one
// we really want to compile.
for(JCCompilationUnit parsedTree : parsedTrees){
if(parsedTree.sourcefile.equals(fileObject)
&& parsedTree instanceof CeylonCompilationUnit){
// same file! we already parsed it, let's return this one's module
return ((CeylonCompilationUnit)parsedTree).phasedUnit.getPackage().getModule();
}
}
CeylonCompilationUnit ceylonCompilationUnit = (CeylonCompilationUnit) parse(fileObject);
moduleTrees.add(ceylonCompilationUnit);
// parse the module info from there
Module module = ceylonCompilationUnit.phasedUnit.visitSrcModulePhase();
ceylonCompilationUnit.phasedUnit.visitRemainingModulePhase();
// now try to obtain the parsed module
if(module != null){
ceylonCompilationUnit.phasedUnit.getPackage().setModule(module);
return module;
}
}
return loadModuleFromSource(getParentPackage(pkgName), moduleTrees, parsedTrees);
}
private String getParentPackage(String pkgName) {
int lastDot = pkgName.lastIndexOf(".");
if(lastDot == -1)
return "";
return pkgName.substring(0, lastDot);
}
// FIXME: this function is terrible, possibly refactor it with getPackage?
private File getSrcDir(File sourceFile) throws IOException {
String name;
try {
name = sourceFile.getCanonicalPath();
} catch (IOException e) {
// FIXME
throw new RuntimeException(e);
}
Iterable<? extends File> prefixes = ((JavacFileManager)fileManager).getLocation(StandardLocation.SOURCE_PATH);
int maxPrefixLength = 0;
File srcDirFile = null;
for (File prefixFile : prefixes) {
String path = prefixFile.getCanonicalPath();
if (name.startsWith(path) && path.length() > maxPrefixLength) {
maxPrefixLength = path.length();
srcDirFile = prefixFile;
}
}
if (srcDirFile != null) {
return srcDirFile;
}
String srcPath = ((JavacFileManager)fileManager).getLocation(StandardLocation.SOURCE_PATH).toString();
String msg = sourceFile.getPath() + " is not in the current source path: " + srcPath + "\n"
+ "Either move the sources into that path or add a --src argument to specify their actual location.";
throw new CompilerErrorException(msg);
}
private String getPackage(JavaFileObject file) throws IOException{
Iterable<? extends File> prefixes = ((JavacFileManager)fileManager).getLocation(StandardLocation.SOURCE_PATH);
// Figure out the package name by stripping the "-src" prefix and
// extracting
// the package part of the fullname.
String filePath = file.toUri().getPath();
// go absolute
filePath = new File(filePath).getCanonicalPath();
int srcDirLength = 0;
for (File prefixFile : prefixes) {
String prefix = prefixFile.getCanonicalPath();
if (filePath.startsWith(prefix) && prefix.length() > srcDirLength) {
srcDirLength = prefix.length();
}
}
if (srcDirLength > 0) {
String fullname = filePath.substring(srcDirLength);
assert fullname.endsWith(".ceylon");
fullname = fullname.substring(0, fullname.length() - ".ceylon".length());
fullname = fullname.replace(File.separator, ".");
if(fullname.startsWith("."))
fullname = fullname.substring(1);
String packageName = Convert.packagePart(fullname);
if (!packageName.equals(""))
return packageName;
}
return null;
}
private void printError(RecognitionError le, String message, String key, LineMap map) {
int pos = -1;
if (le.getLine() > 0) {
/* does not seem to be a way to determine the max line number so we do an ugly try-catch */
try {
pos = map.getStartPosition(le.getLine()) + le.getCharacterInLine();
} catch (Exception e) { }
}
log.error(pos, key, message);
}
public Env<AttrContext> attribute(Env<AttrContext> env) {
if (env.toplevel.sourcefile instanceof CeylonFileObject || isBootstrap) {
try {
Context.SourceLanguage.push(Language.CEYLON);
return super.attribute(env);
} finally {
Context.SourceLanguage.pop();
}
}
return super.attribute(env);
}
@Override
protected JavaFileObject genCode(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
if (env.toplevel.sourcefile instanceof CeylonFileObject) {
try {
Context.SourceLanguage.push(Language.CEYLON);
// call our own genCode
return genCodeUnlessError(env, cdef);
} finally {
Context.SourceLanguage.pop();
}
}
return super.genCode(env, cdef);
}
@Override
protected boolean shouldStop(CompileState cs) {
// we override this to make sure we don't stop because of errors, because we want to generate
// code for classes with no errors
if (shouldStopPolicy == null)
return false;
else
return cs.ordinal() > shouldStopPolicy.ordinal();
}
private JavaFileObject genCodeUnlessError(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
CeylonFileObject sourcefile = (CeylonFileObject) env.toplevel.sourcefile;
try {
// do not look at the global number of errors but only those for this file
if (super.gen.genClass(env, cdef) && sourcefile.errors == 0)
return writer.writeClass(cdef.sym);
} catch (ClassWriter.PoolOverflow ex) {
log.error(cdef.pos(), "limit.pool");
} catch (ClassWriter.StringOverflow ex) {
log.error(cdef.pos(), "limit.string.overflow",
ex.value.substring(0, 20));
} catch (CompletionFailure ex) {
chk.completionError(cdef.pos(), ex);
} catch (AssertionError e) {
throw new RuntimeException("Error generating bytecode for " + sourcefile.getName(), e);
}
return null;
}
protected void desugar(final Env<AttrContext> env, Queue<Pair<Env<AttrContext>, JCClassDecl>> results) {
if (env.toplevel.sourcefile instanceof CeylonFileObject) {
try {
Context.SourceLanguage.push(Language.CEYLON);
super.desugar(env, results);
return;
} finally {
Context.SourceLanguage.pop();
}
}
super.desugar(env, results);
}
protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
if (env.toplevel.sourcefile instanceof CeylonFileObject) {
try {
Context.SourceLanguage.push(Language.CEYLON);
super.flow(env, results);
return;
} finally {
Context.SourceLanguage.pop();
}
}
super.flow(env, results);
}
@Override
public void initProcessAnnotations(Iterable<? extends Processor> processors) {
// don't do anything, which will leave the "processAnnotations" field to false
}
@Override
public void complete(ClassSymbol c) throws CompletionFailure {
try {
Context.SourceLanguage.push(Language.JAVA);
super.complete(c);
} finally {
Context.SourceLanguage.pop();
}
}
@Override
public void generate(Queue<Pair<Env<AttrContext>, JCClassDecl>> queue, Queue<JavaFileObject> results) {
timer.startTask("Generate");
super.generate(queue, results);
timer.endTask();
}
}
| false | true | private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) {
if(ceylonEnter.hasRun())
throw new RuntimeException("Trying to load new source file after CeylonEnter has been called: "+filename);
try {
ModuleManager moduleManager = phasedUnits.getModuleManager();
File sourceFile = new File(filename.getName());
// FIXME: temporary solution
VirtualFile file = vfs.getFromFile(sourceFile);
VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile));
String source = readSource.toString();
char[] chars = source.toCharArray();
LineMap map = Position.makeLineMap(chars, chars.length, false);
PhasedUnit phasedUnit = null;
PhasedUnit externalPhasedUnit = phasedUnitsManager.getExternalSourcePhasedUnit(srcDir, file);
if (externalPhasedUnit != null) {
phasedUnit = new CeylonPhasedUnit(externalPhasedUnit, filename, map);
phasedUnits.addPhasedUnit(externalPhasedUnit.getUnitFile(), phasedUnit);
gen.setMap(map);
String pkgName = phasedUnit.getPackage().getQualifiedNameString();
if ("".equals(pkgName)) {
pkgName = null;
}
return gen.makeJCCompilationUnitPlaceholder(phasedUnit.getCompilationUnit(), filename, pkgName, phasedUnit);
}
if (phasedUnit == null) {
ANTLRStringStream input = new ANTLRStringStream(source);
CeylonLexer lexer = new CeylonLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CeylonParser parser = new CeylonParser(tokens);
CompilationUnit cu = parser.compilationUnit();
java.util.List<LexError> lexerErrors = lexer.getErrors();
for (LexError le : lexerErrors) {
printError(le, le.getMessage(), "ceylon.lexer", map);
}
java.util.List<ParseError> parserErrors = parser.getErrors();
for (ParseError pe : parserErrors) {
printError(pe, pe.getMessage(), "ceylon.parser", map);
}
if (lexer.getNumberOfSyntaxErrors() != 0) {
log.printErrLines("ceylon.lexer.failed");
} else if (parser.getNumberOfSyntaxErrors() != 0) {
log.printErrLines("ceylon.parser.failed");
} else {
// FIXME: this is bad in many ways
String pkgName = getPackage(filename);
// make a Package with no module yet, we will resolve them later
/*
* Stef: see javadoc for findOrCreateModulelessPackage() for why this is here.
*/
com.redhat.ceylon.compiler.typechecker.model.Package p = modelLoader.findOrCreateModulelessPackage(pkgName == null ? "" : pkgName);
phasedUnit = new CeylonPhasedUnit(file, srcDir, cu, p, moduleManager, ceylonContext, filename, map);
phasedUnits.addPhasedUnit(file, phasedUnit);
gen.setMap(map);
return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName, phasedUnit);
}
}
} catch (CompilerErrorException e) {
log.error("ceylon", e.getMessage());
} catch (Exception e) {
log.error("ceylon", e);
}
JCCompilationUnit result = make.TopLevel(List.<JCAnnotation> nil(), null, List.<JCTree> of(make.Erroneous()));
result.sourcefile = filename;
return result;
}
| private JCCompilationUnit ceylonParse(JavaFileObject filename, CharSequence readSource) {
if(ceylonEnter.hasRun())
throw new RuntimeException("Trying to load new source file after CeylonEnter has been called: "+filename);
try {
ModuleManager moduleManager = phasedUnits.getModuleManager();
File sourceFile = new File(filename.getName());
// FIXME: temporary solution
VirtualFile file = vfs.getFromFile(sourceFile);
VirtualFile srcDir = vfs.getFromFile(getSrcDir(sourceFile));
String source = readSource.toString();
char[] chars = source.toCharArray();
LineMap map = Position.makeLineMap(chars, chars.length, false);
PhasedUnit phasedUnit = null;
PhasedUnit externalPhasedUnit = phasedUnitsManager.getExternalSourcePhasedUnit(srcDir, file);
if (externalPhasedUnit != null) {
phasedUnit = new CeylonPhasedUnit(externalPhasedUnit, filename, map);
phasedUnits.addPhasedUnit(externalPhasedUnit.getUnitFile(), phasedUnit);
gen.setMap(map);
String pkgName = phasedUnit.getPackage().getQualifiedNameString();
if ("".equals(pkgName)) {
pkgName = null;
}
return gen.makeJCCompilationUnitPlaceholder(phasedUnit.getCompilationUnit(), filename, pkgName, phasedUnit);
}
if (phasedUnit == null) {
ANTLRStringStream input = new ANTLRStringStream(source);
CeylonLexer lexer = new CeylonLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
CeylonParser parser = new CeylonParser(tokens);
CompilationUnit cu = parser.compilationUnit();
java.util.List<LexError> lexerErrors = lexer.getErrors();
for (LexError le : lexerErrors) {
printError(le, le.getMessage(), "ceylon.lexer", map);
}
java.util.List<ParseError> parserErrors = parser.getErrors();
for (ParseError pe : parserErrors) {
printError(pe, pe.getMessage(), "ceylon.parser", map);
}
if (lexer.getNumberOfSyntaxErrors() != 0) {
log.printErrLines("ceylon.lexer.failed");
} else if (parser.getNumberOfSyntaxErrors() != 0) {
log.printErrLines("ceylon.parser.failed");
} else {
// FIXME: this is bad in many ways
String pkgName = getPackage(filename);
// make a Package with no module yet, we will resolve them later
/*
* Stef: see javadoc for findOrCreateModulelessPackage() for why this is here.
*/
com.redhat.ceylon.compiler.typechecker.model.Package p = modelLoader.findOrCreateModulelessPackage(pkgName == null ? "" : pkgName);
phasedUnit = new CeylonPhasedUnit(file, srcDir, cu, p, moduleManager, ceylonContext, filename, map);
phasedUnits.addPhasedUnit(file, phasedUnit);
gen.setMap(map);
return gen.makeJCCompilationUnitPlaceholder(cu, filename, pkgName, phasedUnit);
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
JCCompilationUnit result = make.TopLevel(List.<JCAnnotation> nil(), null, List.<JCTree> of(make.Erroneous()));
result.sourcefile = filename;
return result;
}
|
diff --git a/Wable/src/com/thx/bizcat/http/apiproxy/JSONParser/sp_UserGetUpdatedContents_Items.java b/Wable/src/com/thx/bizcat/http/apiproxy/JSONParser/sp_UserGetUpdatedContents_Items.java
index 5fd727c..ef59291 100644
--- a/Wable/src/com/thx/bizcat/http/apiproxy/JSONParser/sp_UserGetUpdatedContents_Items.java
+++ b/Wable/src/com/thx/bizcat/http/apiproxy/JSONParser/sp_UserGetUpdatedContents_Items.java
@@ -1,118 +1,119 @@
package com.thx.bizcat.http.apiproxy.JSONParser;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.thx.bizcat.http.apiproxy.JSONParser.Result.sp_GetMyUpdatedBiddings_Result;
import com.thx.bizcat.http.apiproxy.JSONParser.Result.sp_GetMyUpdatedMatch_Result;
import com.thx.bizcat.http.apiproxy.JSONParser.Result.sp_GetMyUpdatedProvides_Result;
import com.thx.bizcat.http.apiproxy.JSONParser.Result.sp_GetMyUpdatedRequests_Result;
import com.thx.bizcat.http.apiproxy.JSONParser.Result.sp_GetNewMessage_Result;
import com.thx.bizcat.util.Logger;
public class sp_UserGetUpdatedContents_Items {
public List<sp_GetMyUpdatedRequests_Result> newrequests;
public List<sp_GetMyUpdatedProvides_Result> newprovides;
public List<sp_GetMyUpdatedBiddings_Result> newbiddings;
public List<sp_GetNewMessage_Result> newbiddingmessages;
public List<sp_GetMyUpdatedMatch_Result> newmatches;
public String last_modified_time_request;
public String last_modified_time_provide;
public String last_modified_time_bidding;
public String last_modified_time_biddingmessage;
public String last_modified_time_match;
public boolean bsuccess = false;
public ResultCode resultCode = ResultCode.NONE;
public sp_UserGetUpdatedContents_Items(JSONObject obj) {
try {
bsuccess = obj.getBoolean("success");
if(bsuccess)
{
- JSONObject requests = obj.getJSONObject("newrequests");
+ JSONObject data = obj.getJSONObject("data");
+ JSONObject requests = data.getJSONObject("newrequests");
if(requests != null)//
{
newrequests = new ArrayList<sp_GetMyUpdatedRequests_Result>();
JSONArray array = requests.getJSONArray("requests");
for(int i=0;i<array.length();i++)
{
newrequests.add(new sp_GetMyUpdatedRequests_Result(array.getJSONObject(i)));
}
last_modified_time_request = requests.getString("latest_modified_time");
}
- JSONObject provides = obj.getJSONObject("newprovides");
+ JSONObject provides = data.getJSONObject("newprovides");
if(provides != null)//
{
newprovides = new ArrayList<sp_GetMyUpdatedProvides_Result>();
JSONArray array = provides.getJSONArray("provides");
for(int i=0;i<array.length();i++)
{
newprovides.add(new sp_GetMyUpdatedProvides_Result(array.getJSONObject(i)));
}
last_modified_time_provide = provides.getString("latest_modified_time");
}
- JSONObject biddings = obj.getJSONObject("newbidding");
+ JSONObject biddings = data.getJSONObject("newbidding");
if(biddings != null)//
{
newbiddings = new ArrayList<sp_GetMyUpdatedBiddings_Result>();
JSONArray array = biddings.getJSONArray("biddings");
for(int i=0;i<array.length();i++)
{
newbiddings.add(new sp_GetMyUpdatedBiddings_Result(array.getJSONObject(i)));
}
last_modified_time_bidding = biddings.getString("latest_modified_time");
}
- JSONObject biddingmessages = obj.getJSONObject("newbiddingmessage");
+ JSONObject biddingmessages = data.getJSONObject("newbiddingmessage");
if(biddingmessages != null)//
{
newbiddingmessages = new ArrayList<sp_GetNewMessage_Result>();
JSONArray array = biddingmessages.getJSONArray("biddingmessages");
for(int i=0;i<array.length();i++)
{
newbiddingmessages.add(new sp_GetNewMessage_Result(array.getJSONObject(i)));
}
last_modified_time_biddingmessage = biddingmessages.getString("latest_modified_time");
}
- JSONObject matches = obj.getJSONObject("newmatch");
+ JSONObject matches = data.getJSONObject("newmatch");
if(matches != null)//
{
newmatches = new ArrayList<sp_GetMyUpdatedMatch_Result>();
JSONArray array = matches.getJSONArray("matches");
for(int i=0;i<array.length();i++)
{
newmatches.add(new sp_GetMyUpdatedMatch_Result(array.getJSONObject(i)));
}
last_modified_time_match = matches.getString("latest_modified_time");
}
}
else//실패시는 errorcode입력
{
try
{
resultCode = ResultCode.valueOf(obj.getString("data"));
} catch (JSONException e) {
Logger.Instance().Write(e);
}
}
} catch (JSONException e) {
Logger.Instance().Write(e);
}
}
}
| false | true | public sp_UserGetUpdatedContents_Items(JSONObject obj) {
try {
bsuccess = obj.getBoolean("success");
if(bsuccess)
{
JSONObject requests = obj.getJSONObject("newrequests");
if(requests != null)//
{
newrequests = new ArrayList<sp_GetMyUpdatedRequests_Result>();
JSONArray array = requests.getJSONArray("requests");
for(int i=0;i<array.length();i++)
{
newrequests.add(new sp_GetMyUpdatedRequests_Result(array.getJSONObject(i)));
}
last_modified_time_request = requests.getString("latest_modified_time");
}
JSONObject provides = obj.getJSONObject("newprovides");
if(provides != null)//
{
newprovides = new ArrayList<sp_GetMyUpdatedProvides_Result>();
JSONArray array = provides.getJSONArray("provides");
for(int i=0;i<array.length();i++)
{
newprovides.add(new sp_GetMyUpdatedProvides_Result(array.getJSONObject(i)));
}
last_modified_time_provide = provides.getString("latest_modified_time");
}
JSONObject biddings = obj.getJSONObject("newbidding");
if(biddings != null)//
{
newbiddings = new ArrayList<sp_GetMyUpdatedBiddings_Result>();
JSONArray array = biddings.getJSONArray("biddings");
for(int i=0;i<array.length();i++)
{
newbiddings.add(new sp_GetMyUpdatedBiddings_Result(array.getJSONObject(i)));
}
last_modified_time_bidding = biddings.getString("latest_modified_time");
}
JSONObject biddingmessages = obj.getJSONObject("newbiddingmessage");
if(biddingmessages != null)//
{
newbiddingmessages = new ArrayList<sp_GetNewMessage_Result>();
JSONArray array = biddingmessages.getJSONArray("biddingmessages");
for(int i=0;i<array.length();i++)
{
newbiddingmessages.add(new sp_GetNewMessage_Result(array.getJSONObject(i)));
}
last_modified_time_biddingmessage = biddingmessages.getString("latest_modified_time");
}
JSONObject matches = obj.getJSONObject("newmatch");
if(matches != null)//
{
newmatches = new ArrayList<sp_GetMyUpdatedMatch_Result>();
JSONArray array = matches.getJSONArray("matches");
for(int i=0;i<array.length();i++)
{
newmatches.add(new sp_GetMyUpdatedMatch_Result(array.getJSONObject(i)));
}
last_modified_time_match = matches.getString("latest_modified_time");
}
}
else//실패시는 errorcode입력
{
try
{
resultCode = ResultCode.valueOf(obj.getString("data"));
} catch (JSONException e) {
Logger.Instance().Write(e);
}
}
} catch (JSONException e) {
Logger.Instance().Write(e);
}
}
| public sp_UserGetUpdatedContents_Items(JSONObject obj) {
try {
bsuccess = obj.getBoolean("success");
if(bsuccess)
{
JSONObject data = obj.getJSONObject("data");
JSONObject requests = data.getJSONObject("newrequests");
if(requests != null)//
{
newrequests = new ArrayList<sp_GetMyUpdatedRequests_Result>();
JSONArray array = requests.getJSONArray("requests");
for(int i=0;i<array.length();i++)
{
newrequests.add(new sp_GetMyUpdatedRequests_Result(array.getJSONObject(i)));
}
last_modified_time_request = requests.getString("latest_modified_time");
}
JSONObject provides = data.getJSONObject("newprovides");
if(provides != null)//
{
newprovides = new ArrayList<sp_GetMyUpdatedProvides_Result>();
JSONArray array = provides.getJSONArray("provides");
for(int i=0;i<array.length();i++)
{
newprovides.add(new sp_GetMyUpdatedProvides_Result(array.getJSONObject(i)));
}
last_modified_time_provide = provides.getString("latest_modified_time");
}
JSONObject biddings = data.getJSONObject("newbidding");
if(biddings != null)//
{
newbiddings = new ArrayList<sp_GetMyUpdatedBiddings_Result>();
JSONArray array = biddings.getJSONArray("biddings");
for(int i=0;i<array.length();i++)
{
newbiddings.add(new sp_GetMyUpdatedBiddings_Result(array.getJSONObject(i)));
}
last_modified_time_bidding = biddings.getString("latest_modified_time");
}
JSONObject biddingmessages = data.getJSONObject("newbiddingmessage");
if(biddingmessages != null)//
{
newbiddingmessages = new ArrayList<sp_GetNewMessage_Result>();
JSONArray array = biddingmessages.getJSONArray("biddingmessages");
for(int i=0;i<array.length();i++)
{
newbiddingmessages.add(new sp_GetNewMessage_Result(array.getJSONObject(i)));
}
last_modified_time_biddingmessage = biddingmessages.getString("latest_modified_time");
}
JSONObject matches = data.getJSONObject("newmatch");
if(matches != null)//
{
newmatches = new ArrayList<sp_GetMyUpdatedMatch_Result>();
JSONArray array = matches.getJSONArray("matches");
for(int i=0;i<array.length();i++)
{
newmatches.add(new sp_GetMyUpdatedMatch_Result(array.getJSONObject(i)));
}
last_modified_time_match = matches.getString("latest_modified_time");
}
}
else//실패시는 errorcode입력
{
try
{
resultCode = ResultCode.valueOf(obj.getString("data"));
} catch (JSONException e) {
Logger.Instance().Write(e);
}
}
} catch (JSONException e) {
Logger.Instance().Write(e);
}
}
|
diff --git a/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationProblemStatistic.java b/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationProblemStatistic.java
index 422fa0f7a..a6c139506 100644
--- a/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationProblemStatistic.java
+++ b/optaplanner-benchmark/src/main/java/org/optaplanner/benchmark/impl/statistic/bestsolutionmutation/BestSolutionMutationProblemStatistic.java
@@ -1,125 +1,125 @@
/*
* Copyright 2013 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.optaplanner.benchmark.impl.statistic.bestsolutionmutation;
import java.awt.BasicStroke;
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYStepRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.optaplanner.benchmark.impl.DefaultPlannerBenchmark;
import org.optaplanner.benchmark.impl.ProblemBenchmark;
import org.optaplanner.benchmark.impl.SingleBenchmark;
import org.optaplanner.benchmark.impl.report.BenchmarkReport;
import org.optaplanner.benchmark.impl.statistic.AbstractProblemStatistic;
import org.optaplanner.benchmark.impl.statistic.MillisecondsSpendNumberFormat;
import org.optaplanner.benchmark.impl.statistic.ProblemStatisticType;
import org.optaplanner.benchmark.impl.statistic.SingleStatistic;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.impl.score.ScoreUtils;
public class BestSolutionMutationProblemStatistic extends AbstractProblemStatistic {
protected File graphStatisticFile = null;
public BestSolutionMutationProblemStatistic(ProblemBenchmark problemBenchmark) {
super(problemBenchmark, ProblemStatisticType.BEST_SOLUTION_MUTATION);
}
public SingleStatistic createSingleStatistic() {
return new BestSolutionMutationSingleStatistic();
}
/**
* @return never null, relative to the {@link DefaultPlannerBenchmark#benchmarkReportDirectory}
* (not {@link ProblemBenchmark#problemReportDirectory})
*/
public String getGraphFilePath() {
return toFilePath(graphStatisticFile);
}
// ************************************************************************
// Write methods
// ************************************************************************
protected void writeCsvStatistic() {
ProblemStatisticCsv csv = new ProblemStatisticCsv();
for (SingleBenchmark singleBenchmark : problemBenchmark.getSingleBenchmarkList()) {
if (singleBenchmark.isSuccess()) {
BestSolutionMutationSingleStatistic singleStatistic = (BestSolutionMutationSingleStatistic)
singleBenchmark.getSingleStatistic(problemStatisticType);
for (BestSolutionMutationSingleStatisticPoint point : singleStatistic.getPointList()) {
long timeMillisSpend = point.getTimeMillisSpend();
csv.addPoint(singleBenchmark, timeMillisSpend, point.getMutationCount());
}
} else {
csv.addPoint(singleBenchmark, 0L, "Failed");
}
}
csvStatisticFile = new File(problemBenchmark.getProblemReportDirectory(),
problemBenchmark.getName() + "BestSolutionMutationStatistic.csv");
csv.writeCsvStatisticFile();
}
protected void writeGraphStatistic() {
Locale locale = problemBenchmark.getPlannerBenchmark().getBenchmarkReport().getLocale();
NumberAxis xAxis = new NumberAxis("Time spend");
xAxis.setNumberFormatOverride(new MillisecondsSpendNumberFormat(locale));
NumberAxis yAxis = new NumberAxis("Best solution mutation count");
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
yAxis.setAutoRangeIncludesZero(true);
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
int seriesIndex = 0;
for (SingleBenchmark singleBenchmark : problemBenchmark.getSingleBenchmarkList()) {
XYSeries series = new XYSeries(singleBenchmark.getSolverBenchmark().getNameWithFavoriteSuffix());
XYItemRenderer renderer = new XYLineAndShapeRenderer();
if (singleBenchmark.isSuccess()) {
BestSolutionMutationSingleStatistic singleStatistic = (BestSolutionMutationSingleStatistic)
singleBenchmark.getSingleStatistic(problemStatisticType);
for (BestSolutionMutationSingleStatisticPoint point : singleStatistic.getPointList()) {
long timeMillisSpend = point.getTimeMillisSpend();
long mutationCount = point.getMutationCount();
series.add(timeMillisSpend, mutationCount);
}
}
plot.setDataset(seriesIndex, new XYSeriesCollection(series));
if (singleBenchmark.getSolverBenchmark().isFavorite()) {
// Make the favorite more obvious
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
}
plot.setRenderer(seriesIndex, renderer);
seriesIndex++;
}
JFreeChart chart = new JFreeChart(problemBenchmark.getName() + " best solution mutation statistic",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
- graphStatisticFile = writeChartToImageFile(chart, problemBenchmark.getName() + "CalculateCountStatistic");
+ graphStatisticFile = writeChartToImageFile(chart, problemBenchmark.getName() + "BestSolutionMutationStatistic");
}
}
| true | true | protected void writeGraphStatistic() {
Locale locale = problemBenchmark.getPlannerBenchmark().getBenchmarkReport().getLocale();
NumberAxis xAxis = new NumberAxis("Time spend");
xAxis.setNumberFormatOverride(new MillisecondsSpendNumberFormat(locale));
NumberAxis yAxis = new NumberAxis("Best solution mutation count");
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
yAxis.setAutoRangeIncludesZero(true);
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
int seriesIndex = 0;
for (SingleBenchmark singleBenchmark : problemBenchmark.getSingleBenchmarkList()) {
XYSeries series = new XYSeries(singleBenchmark.getSolverBenchmark().getNameWithFavoriteSuffix());
XYItemRenderer renderer = new XYLineAndShapeRenderer();
if (singleBenchmark.isSuccess()) {
BestSolutionMutationSingleStatistic singleStatistic = (BestSolutionMutationSingleStatistic)
singleBenchmark.getSingleStatistic(problemStatisticType);
for (BestSolutionMutationSingleStatisticPoint point : singleStatistic.getPointList()) {
long timeMillisSpend = point.getTimeMillisSpend();
long mutationCount = point.getMutationCount();
series.add(timeMillisSpend, mutationCount);
}
}
plot.setDataset(seriesIndex, new XYSeriesCollection(series));
if (singleBenchmark.getSolverBenchmark().isFavorite()) {
// Make the favorite more obvious
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
}
plot.setRenderer(seriesIndex, renderer);
seriesIndex++;
}
JFreeChart chart = new JFreeChart(problemBenchmark.getName() + " best solution mutation statistic",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
graphStatisticFile = writeChartToImageFile(chart, problemBenchmark.getName() + "CalculateCountStatistic");
}
| protected void writeGraphStatistic() {
Locale locale = problemBenchmark.getPlannerBenchmark().getBenchmarkReport().getLocale();
NumberAxis xAxis = new NumberAxis("Time spend");
xAxis.setNumberFormatOverride(new MillisecondsSpendNumberFormat(locale));
NumberAxis yAxis = new NumberAxis("Best solution mutation count");
yAxis.setNumberFormatOverride(NumberFormat.getInstance(locale));
yAxis.setAutoRangeIncludesZero(true);
XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
plot.setOrientation(PlotOrientation.VERTICAL);
int seriesIndex = 0;
for (SingleBenchmark singleBenchmark : problemBenchmark.getSingleBenchmarkList()) {
XYSeries series = new XYSeries(singleBenchmark.getSolverBenchmark().getNameWithFavoriteSuffix());
XYItemRenderer renderer = new XYLineAndShapeRenderer();
if (singleBenchmark.isSuccess()) {
BestSolutionMutationSingleStatistic singleStatistic = (BestSolutionMutationSingleStatistic)
singleBenchmark.getSingleStatistic(problemStatisticType);
for (BestSolutionMutationSingleStatisticPoint point : singleStatistic.getPointList()) {
long timeMillisSpend = point.getTimeMillisSpend();
long mutationCount = point.getMutationCount();
series.add(timeMillisSpend, mutationCount);
}
}
plot.setDataset(seriesIndex, new XYSeriesCollection(series));
if (singleBenchmark.getSolverBenchmark().isFavorite()) {
// Make the favorite more obvious
renderer.setSeriesStroke(0, new BasicStroke(2.0f));
}
plot.setRenderer(seriesIndex, renderer);
seriesIndex++;
}
JFreeChart chart = new JFreeChart(problemBenchmark.getName() + " best solution mutation statistic",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
graphStatisticFile = writeChartToImageFile(chart, problemBenchmark.getName() + "BestSolutionMutationStatistic");
}
|
diff --git a/src/powercrystals/minefactoryreloaded/entity/EntityNeedle.java b/src/powercrystals/minefactoryreloaded/entity/EntityNeedle.java
index 025868f5..b8fb5eeb 100644
--- a/src/powercrystals/minefactoryreloaded/entity/EntityNeedle.java
+++ b/src/powercrystals/minefactoryreloaded/entity/EntityNeedle.java
@@ -1,284 +1,284 @@
package powercrystals.minefactoryreloaded.entity;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List;
import powercrystals.minefactoryreloaded.MFRRegistry;
import net.minecraft.entity.Entity;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
public class EntityNeedle extends Entity implements IProjectile
{
private EntityPlayer _owner;
private int ticksInAir = 0;
private int _ammoItemId;
private double _xStart;
private double _yStart;
private double _zStart;
public EntityNeedle(World world)
{
super(world);
this.renderDistanceWeight = 10.0D;
this.setSize(0.5F, 0.5F);
}
public EntityNeedle(World world, double x, double y, double z)
{
this(world);
this.setPosition(x, y, z);
this.yOffset = 0.0F;
}
public EntityNeedle(World world, EntityPlayer owner, ItemStack ammoSource, float spread)
{
this(world);
_owner = owner;
_ammoItemId = ammoSource.itemID;
this.setLocationAndAngles(owner.posX, owner.posY + owner.getEyeHeight(), owner.posZ, owner.rotationYaw, owner.rotationPitch);
this.posX -= (MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
this.posY -= 0.1D;
this.posZ -= (MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
this.setPosition(this.posX, this.posY, this.posZ);
this.yOffset = 0.0F;
this.motionX = (-MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionZ = (MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionY = (-MathHelper.sin(this.rotationPitch / 180.0F * (float)Math.PI));
this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, 1.5F, spread);
}
@Override
protected void entityInit()
{
this.dataWatcher.addObject(16, Byte.valueOf((byte)0));
}
@Override
public void setThrowableHeading(double x, double y, double z, float speedMult, float spreadConst)
{
double normal = MathHelper.sqrt_double(x * x + y * y + z * z);
x /= normal;
y /= normal;
z /= normal;
x += this.rand.nextGaussian() * (this.rand.nextBoolean() ? -1D : 1D) * 0.0075D * spreadConst;
y += this.rand.nextGaussian() * (this.rand.nextBoolean() ? -1D : 1D) * 0.0075D * spreadConst;
z += this.rand.nextGaussian() * (this.rand.nextBoolean() ? -1D : 1D) * 0.0075D * spreadConst;
x *= speedMult;
y *= speedMult;
z *= speedMult;
this.motionX = x;
this.motionY = y;
this.motionZ = z;
float horizSpeed = MathHelper.sqrt_double(x * x + z * z);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(x, z) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(y, horizSpeed) * 180.0D / Math.PI);
}
@Override
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int unknown)
{
this.setPosition(x, y, z);
this.setRotation(yaw, pitch);
}
@Override
@SideOnly(Side.CLIENT)
public void setVelocity(double x, double y, double z)
{
this.motionX = x;
this.motionY = y;
this.motionZ = z;
if(this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(x * x + z * z);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(x, z) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(y, f) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch;
this.prevRotationYaw = this.rotationYaw;
this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch);
}
}
@Override
public void onUpdate()
{
super.onUpdate();
if(this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, f) * 180.0D / Math.PI);
}
++this.ticksInAir;
Vec3 pos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
Vec3 nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
MovingObjectPosition hit = this.worldObj.rayTraceBlocks_do_do(pos, nextPos, false, true);
pos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if(hit != null)
{
nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(hit.hitVec.xCoord, hit.hitVec.yCoord, hit.hitVec.zCoord);
}
Entity entityHit = null;
List<?> list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
double closestRange = 0.0D;
double collisionRange = 0.3D;
for(int l = 0; l < list.size(); ++l)
{
Entity e = (Entity)list.get(l);
if(e.canBeCollidedWith() && (e != _owner || this.ticksInAir >= 5))
{
AxisAlignedBB entitybb = e.boundingBox.expand(collisionRange, collisionRange, collisionRange);
MovingObjectPosition entityHitPos = entitybb.calculateIntercept(pos, nextPos);
if(entityHitPos != null)
{
double range = pos.distanceTo(entityHitPos.hitVec);
if(range < closestRange || closestRange == 0.0D)
{
entityHit = e;
closestRange = range;
}
}
}
}
if(entityHit != null)
{
hit = new MovingObjectPosition(entityHit);
}
if(hit != null && hit.entityHit != null && hit.entityHit instanceof EntityPlayer)
{
EntityPlayer entityplayer = (EntityPlayer)hit.entityHit;
- if(entityplayer.capabilities.disableDamage || !_owner.func_96122_a(entityplayer))
+ if(entityplayer.capabilities.disableDamage || (_owner != null && !_owner.func_96122_a(entityplayer)))
{
hit = null;
}
}
float speed = 0.0F;
if(hit != null && !worldObj.isRemote)
{
if(hit.entityHit != null && MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId) != null)
{
MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId).onHitEntity(_owner, hit.entityHit, Math.sqrt((_xStart - hit.blockX) * (_yStart - hit.blockY) * (_zStart - hit.blockZ)));
}
else
{
MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId).onHitBlock(_owner, worldObj, hit.blockX, hit.blockY, hit.blockZ, hit.sideHit,
Math.sqrt((_xStart - hit.blockX) * (_yStart - hit.blockY) * (_zStart - hit.blockZ)));
}
setDead();
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
speed = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
for(this.rotationPitch = (float)(Math.atan2(this.motionY, speed) * 180.0D / Math.PI); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
;
}
while(this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while(this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while(this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float speedDropoff = 0.99F;
collisionRange = 0.05F;
if(this.isInWater())
{
double particleOffset = 0.25D;
for(int i = 0; i < 4; ++i)
{
this.worldObj.spawnParticle("bubble", this.posX - this.motionX * particleOffset, this.posY - this.motionY * particleOffset, this.posZ - this.motionZ * particleOffset, this.motionX, this.motionY, this.motionZ);
}
speedDropoff = 0.8F;
}
this.motionX *= speedDropoff;
this.motionY *= speedDropoff;
this.motionZ *= speedDropoff;
this.setPosition(this.posX, this.posY, this.posZ);
this.doBlockCollisions();
}
@Override
public void writeEntityToNBT(NBTTagCompound nbttagcompound)
{
nbttagcompound.setInteger("ammoItemId", _ammoItemId);
nbttagcompound.setDouble("", _xStart);
nbttagcompound.setDouble("yStart", _yStart);
nbttagcompound.setDouble("zStart", _zStart);
}
@Override
public void readEntityFromNBT(NBTTagCompound nbttagcompound)
{
if(nbttagcompound.hasKey("ammoItemId"))
{
_ammoItemId = nbttagcompound.getInteger("ammoItemId");
_xStart = nbttagcompound.getInteger("xStart");
_yStart = nbttagcompound.getInteger("yStart");
_zStart = nbttagcompound.getInteger("zStart");
}
}
@Override
protected boolean canTriggerWalking()
{
return false;
}
@Override
@SideOnly(Side.CLIENT)
public float getShadowSize()
{
return 0.0F;
}
@Override
public boolean canAttackWithItem()
{
return false;
}
}
| true | true | public void onUpdate()
{
super.onUpdate();
if(this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, f) * 180.0D / Math.PI);
}
++this.ticksInAir;
Vec3 pos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
Vec3 nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
MovingObjectPosition hit = this.worldObj.rayTraceBlocks_do_do(pos, nextPos, false, true);
pos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if(hit != null)
{
nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(hit.hitVec.xCoord, hit.hitVec.yCoord, hit.hitVec.zCoord);
}
Entity entityHit = null;
List<?> list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
double closestRange = 0.0D;
double collisionRange = 0.3D;
for(int l = 0; l < list.size(); ++l)
{
Entity e = (Entity)list.get(l);
if(e.canBeCollidedWith() && (e != _owner || this.ticksInAir >= 5))
{
AxisAlignedBB entitybb = e.boundingBox.expand(collisionRange, collisionRange, collisionRange);
MovingObjectPosition entityHitPos = entitybb.calculateIntercept(pos, nextPos);
if(entityHitPos != null)
{
double range = pos.distanceTo(entityHitPos.hitVec);
if(range < closestRange || closestRange == 0.0D)
{
entityHit = e;
closestRange = range;
}
}
}
}
if(entityHit != null)
{
hit = new MovingObjectPosition(entityHit);
}
if(hit != null && hit.entityHit != null && hit.entityHit instanceof EntityPlayer)
{
EntityPlayer entityplayer = (EntityPlayer)hit.entityHit;
if(entityplayer.capabilities.disableDamage || !_owner.func_96122_a(entityplayer))
{
hit = null;
}
}
float speed = 0.0F;
if(hit != null && !worldObj.isRemote)
{
if(hit.entityHit != null && MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId) != null)
{
MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId).onHitEntity(_owner, hit.entityHit, Math.sqrt((_xStart - hit.blockX) * (_yStart - hit.blockY) * (_zStart - hit.blockZ)));
}
else
{
MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId).onHitBlock(_owner, worldObj, hit.blockX, hit.blockY, hit.blockZ, hit.sideHit,
Math.sqrt((_xStart - hit.blockX) * (_yStart - hit.blockY) * (_zStart - hit.blockZ)));
}
setDead();
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
speed = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
for(this.rotationPitch = (float)(Math.atan2(this.motionY, speed) * 180.0D / Math.PI); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
;
}
while(this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while(this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while(this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float speedDropoff = 0.99F;
collisionRange = 0.05F;
if(this.isInWater())
{
double particleOffset = 0.25D;
for(int i = 0; i < 4; ++i)
{
this.worldObj.spawnParticle("bubble", this.posX - this.motionX * particleOffset, this.posY - this.motionY * particleOffset, this.posZ - this.motionZ * particleOffset, this.motionX, this.motionY, this.motionZ);
}
speedDropoff = 0.8F;
}
this.motionX *= speedDropoff;
this.motionY *= speedDropoff;
this.motionZ *= speedDropoff;
this.setPosition(this.posX, this.posY, this.posZ);
this.doBlockCollisions();
}
| public void onUpdate()
{
super.onUpdate();
if(this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, f) * 180.0D / Math.PI);
}
++this.ticksInAir;
Vec3 pos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
Vec3 nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
MovingObjectPosition hit = this.worldObj.rayTraceBlocks_do_do(pos, nextPos, false, true);
pos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if(hit != null)
{
nextPos = this.worldObj.getWorldVec3Pool().getVecFromPool(hit.hitVec.xCoord, hit.hitVec.yCoord, hit.hitVec.zCoord);
}
Entity entityHit = null;
List<?> list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
double closestRange = 0.0D;
double collisionRange = 0.3D;
for(int l = 0; l < list.size(); ++l)
{
Entity e = (Entity)list.get(l);
if(e.canBeCollidedWith() && (e != _owner || this.ticksInAir >= 5))
{
AxisAlignedBB entitybb = e.boundingBox.expand(collisionRange, collisionRange, collisionRange);
MovingObjectPosition entityHitPos = entitybb.calculateIntercept(pos, nextPos);
if(entityHitPos != null)
{
double range = pos.distanceTo(entityHitPos.hitVec);
if(range < closestRange || closestRange == 0.0D)
{
entityHit = e;
closestRange = range;
}
}
}
}
if(entityHit != null)
{
hit = new MovingObjectPosition(entityHit);
}
if(hit != null && hit.entityHit != null && hit.entityHit instanceof EntityPlayer)
{
EntityPlayer entityplayer = (EntityPlayer)hit.entityHit;
if(entityplayer.capabilities.disableDamage || (_owner != null && !_owner.func_96122_a(entityplayer)))
{
hit = null;
}
}
float speed = 0.0F;
if(hit != null && !worldObj.isRemote)
{
if(hit.entityHit != null && MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId) != null)
{
MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId).onHitEntity(_owner, hit.entityHit, Math.sqrt((_xStart - hit.blockX) * (_yStart - hit.blockY) * (_zStart - hit.blockZ)));
}
else
{
MFRRegistry.getNeedleAmmoTypes().get(_ammoItemId).onHitBlock(_owner, worldObj, hit.blockX, hit.blockY, hit.blockZ, hit.sideHit,
Math.sqrt((_xStart - hit.blockX) * (_yStart - hit.blockY) * (_zStart - hit.blockZ)));
}
setDead();
}
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
speed = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
for(this.rotationPitch = (float)(Math.atan2(this.motionY, speed) * 180.0D / Math.PI); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
;
}
while(this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while(this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while(this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float speedDropoff = 0.99F;
collisionRange = 0.05F;
if(this.isInWater())
{
double particleOffset = 0.25D;
for(int i = 0; i < 4; ++i)
{
this.worldObj.spawnParticle("bubble", this.posX - this.motionX * particleOffset, this.posY - this.motionY * particleOffset, this.posZ - this.motionZ * particleOffset, this.motionX, this.motionY, this.motionZ);
}
speedDropoff = 0.8F;
}
this.motionX *= speedDropoff;
this.motionY *= speedDropoff;
this.motionZ *= speedDropoff;
this.setPosition(this.posX, this.posY, this.posZ);
this.doBlockCollisions();
}
|
diff --git a/core/PFont.java b/core/PFont.java
index 920ea2590..c2d8ec48c 100644
--- a/core/PFont.java
+++ b/core/PFont.java
@@ -1,1256 +1,1256 @@
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
PFont - font object for text rendering
Part of the Processing project - http://processing.org
Copyright (c) 2004 Ben Fry & Casey Reas
Portions Copyright (c) 2001-04 Massachusetts Institute of Technology
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import java.awt.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
/*
awful ascii (non)art for how this works
|
| height is the full used height of the image
|
| ..XX.. }
| ..XX.. }
| ...... }
| XXXX.. } topExtent (top y is baseline - topExtent)
| ..XX.. }
| ..XX.. } dotted areas are where the image data
| ..XX.. } is actually located for the character
+---XXXXXX---- } (it extends to the right & down for pow of 2 textures)
|
^^^^ leftExtent (amount to move over before drawing the image
^^^^^^^^^^^^^^ setWidth (width displaced by char)
*/
public class PFont implements PConstants {
//int firstChar = 33; // always
public int charCount;
public PImage images[];
// image width, a power of 2
// note! these will always be the same
public int twidth, theight;
// float versions of the above
//float twidthf, theightf;
// formerly iwidthf, iheightf.. but that's wrong
// actually should be mbox, the font size
float fwidth, fheight;
// mbox is just the font size (i.e. 48 for most vlw fonts)
public int mbox2; // next power of 2 over the max image size
public int mbox; // actual "font size" of source font
public int value[]; // char code
public int height[]; // height of the bitmap data
public int width[]; // width of bitmap data
public int setWidth[]; // width displaced by the char
public int topExtent[]; // offset for the top
public int leftExtent[]; // offset for the left
public int ascent;
public int descent;
// scaling, for convenience
public float size;
public float leading;
public int align;
public int space;
int ascii[]; // quick lookup for the ascii chars
boolean cached;
// used by the text() functions to avoid over-allocation of memory
private char textBuffer[] = new char[8 * 1024];
private char widthBuffer[] = new char[8 * 1024];
public PFont() { } // for PFontAI subclass and font builder
public PFont(InputStream input) throws IOException {
DataInputStream is = new DataInputStream(input);
// number of character images stored in this font
charCount = is.readInt();
// bit count is ignored since this is always 8
int numBits = is.readInt();
// this was formerly ignored, now it's the actual font size
mbox = is.readInt();
// this was formerly mboxY, the one that was used
// this will make new fonts downward compatible
mbox2 = is.readInt();
fwidth = mbox;
fheight = mbox;
// size for image ("texture") is next power of 2
// over the font size. for most vlw fonts, the size is 48
// so the next power of 2 is 64.
// double-check to make sure that mbox2 is a power of 2
// there was a bug in the old font generator that broke this
mbox2 = (int) Math.pow(2, Math.ceil(Math.log(mbox2) / Math.log(2)));
// size for the texture is stored in the font
twidth = theight = mbox2;
ascent = is.readInt(); // formerly baseHt (zero/ignored)
descent = is.readInt(); // formerly ignored struct padding
//System.out.println("found mbox = " + mbox);
//System.out.println("found ascent/descent = " + ascent + " " + descent);
// allocate enough space for the character info
value = new int[charCount];
height = new int[charCount];
width = new int[charCount];
setWidth = new int[charCount];
topExtent = new int[charCount];
leftExtent = new int[charCount];
ascii = new int[128];
for (int i = 0; i < 128; i++) ascii[i] = -1;
// read the information about the individual characters
for (int i = 0; i < charCount; i++) {
value[i] = is.readInt();
height[i] = is.readInt();
width[i] = is.readInt();
setWidth[i] = is.readInt();
topExtent[i] = is.readInt();
leftExtent[i] = is.readInt();
// pointer in the c version, ignored
is.readInt();
// cache locations of the ascii charset
if (value[i] < 128) ascii[value[i]] = i;
// the values for getAscent() and getDescent() from FontMetrics
// seem to be way too large.. perhaps they're the max?
// as such, use a more traditional marker for ascent/descent
if (value[i] == 'd') {
if (ascent == 0) ascent = topExtent[i];
}
if (value[i] == 'p') {
if (descent == 0) descent = -topExtent[i] + height[i];
}
}
// not a roman font, so throw an error and ask to re-build.
// that way can avoid a bunch of error checking hacks in here.
if ((ascent == 0) && (descent == 0)) {
throw new RuntimeException("Please use \"Create Font\" to " +
"re-create this font.");
}
images = new PImage[charCount];
for (int i = 0; i < charCount; i++) {
//int pixels[] = new int[64 * 64];
int pixels[] = new int[twidth * theight];
//images[i] = new PImage(pixels, 64, 64, ALPHA);
images[i] = new PImage(pixels, twidth, theight, ALPHA);
int bitmapSize = height[i] * width[i];
byte temp[] = new byte[bitmapSize];
is.readFully(temp);
// convert the bitmap to an alpha channel
int w = width[i];
int h = height[i];
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int valu = temp[y*w + x] & 0xff;
//images[i].pixels[y*64 + x] = valu;
images[i].pixels[y * twidth + x] = valu;
// the following makes javagl more happy..
// not sure what's going on
//(valu << 24) | (valu << 16) | (valu << 8) | valu; //0xffffff;
//System.out.print((images[i].pixels[y*64+x] > 128) ? "*" : ".");
}
//System.out.println();
}
//System.out.println();
}
cached = false;
resetSize();
//resetLeading(); // ??
space = OBJECT_SPACE;
align = ALIGN_LEFT;
}
//static boolean isSpace(int c) {
//return (Character.isWhitespace((char) c) ||
// (c == '\u00A0') || (c == '\u2007') || (c == '\u202F'));
//}
public void write(OutputStream output) throws IOException {
DataOutputStream os = new DataOutputStream(output);
os.writeInt(charCount);
os.writeInt(8); // numBits
os.writeInt(mbox); // formerly mboxX (was 64, now 48)
os.writeInt(mbox2); // formerly mboxY (was 64, still 64)
os.writeInt(ascent); // formerly baseHt (was ignored)
os.writeInt(descent); // formerly struct padding for c version
for (int i = 0; i < charCount; i++) {
os.writeInt(value[i]);
os.writeInt(height[i]);
os.writeInt(width[i]);
os.writeInt(setWidth[i]);
os.writeInt(topExtent[i]);
os.writeInt(leftExtent[i]);
os.writeInt(0); // padding
}
for (int i = 0; i < charCount; i++) {
//int bitmapSize = height[i] * width[i];
//byte bitmap[] = new byte[bitmapSize];
for (int y = 0; y < height[i]; y++) {
for (int x = 0; x < width[i]; x++) {
//os.write(images[i].pixels[y * width[i] + x] & 0xff);
os.write(images[i].pixels[y * mbox2 + x] & 0xff);
}
}
}
os.flush();
os.close(); // can/should i do this?
}
/**
* Get index for the char (convert from unicode to bagel charset).
* @return index into arrays or -1 if not found
*/
public int index(char c) {
// these chars required in all fonts
//if ((c >= 33) && (c <= 126)) {
//return c - 33;
//}
// quicker lookup for the ascii fellers
if (c < 128) return ascii[c];
// some other unicode char, hunt it out
return index_hunt(c, 0, value.length-1);
}
// whups, this used the p5 charset rather than what was inside the font
// meaning that old fonts would crash.. fixed for 0069
private int index_hunt(int c, int start, int stop) {
//System.err.println("checking between " + start + " and " + stop);
int pivot = (start + stop) / 2;
// if this is the char, then return it
if (c == value[pivot]) return pivot;
// char doesn't exist, otherwise would have been the pivot
//if (start == stop) return -1;
if (start >= stop) return -1;
// if it's in the lower half, continue searching that
if (c < value[pivot]) return index_hunt(c, start, pivot-1);
// if it's in the upper half, continue there
return index_hunt(c, pivot+1, stop);
}
public void space(int which) {
this.space = which;
if (space == SCREEN_SPACE) {
resetSize();
//resetLeading();
}
}
public void align(int which) {
this.align = which;
}
public float kern(char a, char b) {
return 0; // * size, but since zero..
}
public void resetSize() {
//size = 12;
size = mbox; // default size for the font
resetLeading(); // has to happen with the resize
}
public void size(float isize) {
size = isize;
}
public void resetLeading() {
// by trial & error, this seems close to illustrator
leading = (ascent() + descent()) * 1.275f;
}
public void leading(float ileading) {
leading = ileading;
}
public float ascent() {
return ((float)ascent / fheight) * size;
}
public float descent() {
return ((float)descent / fheight) * size;
}
public float width(char c) {
if (c == 32) return width('i');
int cc = index(c);
if (cc == -1) return 0;
return ((float)setWidth[cc] / fwidth) * size;
}
public float width(String str) {
int length = str.length();
if (length > widthBuffer.length) {
widthBuffer = new char[length + 10];
}
str.getChars(0, length, widthBuffer, 0);
float wide = 0;
//float pwide = 0;
int index = 0;
int start = 0;
while (index < length) {
if (widthBuffer[index] == '\n') {
wide = Math.max(wide, calcWidth(widthBuffer, start, index));
start = index+1;
}
index++;
}
//System.out.println(start + " " + length + " " + index);
if (start < length) {
wide = Math.max(wide, calcWidth(widthBuffer, start, index));
}
return wide;
}
private float calcWidth(char buffer[], int start, int stop) {
float wide = 0;
for (int i = start; i < stop; i++) {
wide += width(buffer[i]);
}
return wide;
}
public void text(char c, float x, float y, PGraphics parent) {
text(c, x, y, 0, parent);
}
public void text(char c, float x, float y, float z, PGraphics parent) {
//if (!valid) return;
//if (!exists(c)) return;
// eventually replace this with a table
// to convert the > 127 coded chars
//int glyph = c - 33;
int glyph = index(c);
if (glyph == -1) return;
if (!cached) {
// cache on first run, to ensure a graphics context exists
parent.cache(images);
cached = true;
}
if (space == OBJECT_SPACE) {
float high = (float) height[glyph] / fheight;
float bwidth = (float) width[glyph] / fwidth;
float lextent = (float) leftExtent[glyph] / fwidth;
float textent = (float) topExtent[glyph] / fheight;
int savedTextureMode = parent.textureMode;
boolean savedStroke = parent.stroke;
parent.textureMode = IMAGE_SPACE;
//parent.drawing_text = true;
parent.stroke = false;
float x1 = x + lextent * size;
float y1 = y - textent * size;
float x2 = x1 + bwidth * size;
float y2 = y1 + high * size;
// this code was moved here (instead of using parent.image)
// because now images use tint() for their coloring, which
// internally is kind of a hack because it temporarily sets
// the fill color to the tint values when drawing text.
// rather than doubling up the hack with this hack, the code
// is just included here instead.
//System.out.println(x1 + " " + y1 + " " + x2 + " " + y2);
parent.beginShape(QUADS);
parent.texture(images[glyph]);
parent.vertex(x1, y1, z, 0, 0);
parent.vertex(x1, y2, z, 0, height[glyph]);
parent.vertex(x2, y2, z, width[glyph], height[glyph]);
parent.vertex(x2, y1, z, width[glyph], 0);
parent.endShape();
parent.textureMode = savedTextureMode;
//parent.drawing_text = false;
parent.stroke = savedStroke;
} else { // SCREEN_SPACE
int xx = (int) x + leftExtent[glyph];;
int yy = (int) y - topExtent[glyph];
int x0 = 0;
int y0 = 0;
int w0 = width[glyph];
int h0 = height[glyph];
if ((xx >= parent.width) || (yy >= parent.height) ||
(xx + w0 < 0) || (yy + h0 < 0)) return;
if (xx < 0) {
x0 -= xx;
w0 += xx;
//System.out.println("x " + xx + " " + x0 + " " + w0);
xx = 0;
}
if (yy < 0) {
y0 -= yy;
h0 += yy;
//System.out.println("y " + yy + " " + y0 + " " + h0);
yy = 0;
}
if (xx + w0 > parent.width) {
//System.out.println("wide " + x0 + " " + w0);
w0 -= ((xx + w0) - parent.width);
}
if (yy + h0 > parent.height) {
h0 -= ((yy + h0) - parent.height);
}
int fr = parent.fillRi;
int fg = parent.fillGi;
int fb = parent.fillBi;
int fa = parent.fillAi;
int pixels1[] = images[glyph].pixels;
int pixels2[] = parent.pixels;
for (int row = y0; row < y0 + h0; row++) {
for (int col = x0; col < x0 + w0; col++) {
int a1 = (fa * pixels1[row * twidth + col]) >> 8;
int a2 = a1 ^ 0xff;
int p1 = pixels1[row * width[glyph] + col];
int p2 = pixels2[(yy + row-y0)*parent.width + (xx+col-x0)];
pixels2[(yy + row-y0)*parent.width + xx+col-x0] =
(0xff000000 |
(((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) |
(( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) |
(( a1 * fb + a2 * ( p2 & 0xff)) >> 8));
}
}
}
}
public void text(String str, float x, float y, PGraphics parent) {
text(str, x, y, 0, parent);
}
public void text(String str, float x, float y, float z, PGraphics parent) {
int length = str.length();
if (length > textBuffer.length) {
textBuffer = new char[length + 10];
}
str.getChars(0, length, textBuffer, 0);
int start = 0;
int index = 0;
while (index < length) {
if (textBuffer[index] == '\n') {
textLine(start, index, x, y, z, parent);
start = index + 1;
y += leading;
}
index++;
}
if (start < length) {
textLine(start, index, x, y, z, parent);
}
}
private void textLine(int start, int stop,
float x, float y, float z,
PGraphics parent) {
//float startX = x;
//int index = 0;
//char previous = 0;
if (align == ALIGN_CENTER) {
x -= calcWidth(textBuffer, start, stop) / 2f;
} else if (align == ALIGN_RIGHT) {
x -= calcWidth(textBuffer, start, stop);
}
for (int index = start; index < stop; index++) {
text(textBuffer[index], x, y, z, parent);
x += width(textBuffer[index]);
}
}
/**
* Same as below, just without a z coordinate.
*/
public void text(String str, float x, float y,
float w, float h, PGraphics parent) {
text(str, x, y, 0, w, h, parent);
}
/**
* Draw text in a box that is constrained to a particular size.
* The current rectMode() determines what the coordinates mean
* (whether x1/y1/x2/y2 or x/y/w/h).
*
* Note that the x,y coords of the start of the box
* will align with the *ascent* of the text, not the baseline,
* as is the case for the other text() functions.
*/
public void text(String str, float boxX1, float boxY1, float boxZ,
float boxX2, float boxY2, PGraphics parent) {
float spaceWidth = width(' ');
float runningX = boxX1;
float currentY = boxY1;
float boxWidth = boxX2 - boxX1;
//float right = x + w;
float lineX = boxX1;
if (align == ALIGN_CENTER) {
lineX = lineX + boxWidth/2f;
} else if (align == ALIGN_RIGHT) {
lineX = boxX2;
}
// ala illustrator, the text itself must fit inside the box
currentY += ascent();
// if the box is already too small, tell em to f off
if (currentY > boxY2) return;
int length = str.length();
if (length > textBuffer.length) {
textBuffer = new char[length + 10];
}
str.getChars(0, length, textBuffer, 0);
int wordStart = 0;
int wordStop = 0;
int lineStart = 0;
int index = 0;
while (index < length) {
if ((textBuffer[index] == ' ') ||
(index == length-1)) {
// boundary of a word
float wordWidth = calcWidth(textBuffer, wordStart, index);
if (runningX + wordWidth > boxX2) {
if (runningX == boxX1) {
// if this is the first word, and its width is
// greater than the width of the text box,
// then break the word where at the max width,
// and send the rest of the word to the next line.
do {
index--;
if (index == wordStart) {
// not a single char will fit on this line. screw 'em.
return;
}
wordWidth = calcWidth(textBuffer, wordStart, index);
} while (wordWidth > boxWidth);
textLine(lineStart, index, lineX, currentY, boxZ, parent);
} else {
// next word is too big, output current line
// and advance to the next line
textLine(lineStart, wordStop, lineX, currentY, boxZ, parent);
// only increment index if a word wasn't broken inside the
// do/while loop above.. also, this is a while() loop too,
// because multiple spaces don't count for shit when they're
// at the end of a line like this.
index = wordStop; // back that ass up
while ((index < length) &&
(textBuffer[index] == ' ')) {
index++;
}
}
lineStart = index;
wordStart = index;
wordStop = index;
runningX = boxX1;
currentY += leading;
if (currentY > boxY2) return; // box is now full
} else {
runningX += wordWidth + spaceWidth;
// on to the next word
wordStop = index;
wordStart = index + 1;
}
} else if (textBuffer[index] == '\n') {
if (lineStart != index) { // if line is not empty
textLine(lineStart, index, lineX, currentY, boxZ, parent);
}
lineStart = index + 1;
wordStart = lineStart;
currentY += leading;
if (currentY > boxY2) return; // box is now full
}
index++;
}
if ((lineStart < length) &&
(lineStart != index)) { // if line is not empty
//System.out.println("line not empty " +
// new String(textBuffer, lineStart, index));
textLine(lineStart, index, lineX, currentY, boxZ, parent);
}
}
// .................................................................
/**
* Draw SCREEN_SPACE text on its left edge.
* This method is incomplete and should not be used.
*/
public void ltext(String str, float x, float y, PGraphics parent) {
float startY = y;
int index = 0;
char previous = 0;
int length = str.length();
if (length > textBuffer.length) {
textBuffer = new char[length + 10];
}
str.getChars(0, length, textBuffer, 0);
while (index < length) {
if (textBuffer[index] == '\n') {
y = startY;
x += leading;
previous = 0;
} else {
ltext(textBuffer[index], x, y, parent);
y -= width(textBuffer[index]);
if (previous != 0)
y -= kern(previous, textBuffer[index]);
previous = textBuffer[index];
}
index++;
}
}
/**
* Draw SCREEN_SPACE text on its left edge.
* This method is incomplete and should not be used.
*/
public void ltext(char c, float x, float y, PGraphics parent) {
int glyph = index(c);
if (glyph == -1) return;
// top-lefthand corner of the char
int sx = (int) x - topExtent[glyph];
int sy = (int) y - leftExtent[glyph];
// boundary of the character's pixel buffer to copy
int px = 0;
int py = 0;
int pw = width[glyph];
int ph = height[glyph];
// if the character is off the screen
if ((sx >= parent.width) || // top of letter past width
(sy - pw >= parent.height) ||
(sy + pw < 0) ||
(sx + ph < 0)) return;
if (sx < 0) { // if starting x is off screen
py -= sx;
ph += sx;
sx = 0;
}
if (sx + ph >= parent.width) {
ph -= ((sx + ph) - parent.width);
}
if (sy < pw) {
//int extra = pw - sy;
pw -= -1 + pw - sy;
//px -= sy;
//pw += sy;
//sy = 0;
}
if (sy >= parent.height) { // off bottom edge
int extra = 1 + sy - parent.height;
pw -= extra;
px += extra;
sy -= extra;
//pw -= ((sy + pw) - parent.height);
}
int fr = parent.fillRi;
int fg = parent.fillGi;
int fb = parent.fillBi;
int fa = parent.fillAi;
int pixels1[] = images[glyph].pixels;
int pixels2[] = parent.pixels;
// loop over the source pixels in the character image
// row & col is the row and column of the source image
// (but they become col & row in the target image)
for (int row = py; row < py + ph; row++) {
for (int col = px; col < px + pw; col++) {
int a1 = (fa * pixels1[row * twidth + col]) >> 8;
int a2 = a1 ^ 0xff;
int p1 = pixels1[row * width[glyph] + col];
try {
int index = (sy + px-col)*parent.width + (sx+row-py);
int p2 = pixels2[index];
pixels2[index] =
(0xff000000 |
(((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) |
(( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) |
(( a1 * fb + a2 * ( p2 & 0xff)) >> 8));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of bounds " + sy + " " + px + " " + col);
}
}
}
}
// .................................................................
/**
* Draw SCREEN_SPACE text on its right edge.
* This method is incomplete and should not be used.
*/
public void rtext(String str, float x, float y, PGraphics parent) {
float startY = y;
int index = 0;
char previous = 0;
int length = str.length();
if (length > textBuffer.length) {
textBuffer = new char[length + 10];
}
str.getChars(0, length, textBuffer, 0);
while (index < length) {
if (textBuffer[index] == '\n') {
y = startY;
x += leading;
previous = 0;
} else {
rtext(textBuffer[index], x, y, parent);
y += width(textBuffer[index]);
if (previous != 0)
y += kern(previous, textBuffer[index]);
previous = textBuffer[index];
}
index++;
}
}
/**
* Draw SCREEN_SPACE text on its right edge.
* This method is incomplete and should not be used.
*/
public void rtext(char c, float x, float y, PGraphics parent) {
int glyph = index(c);
if (glyph == -1) return;
// starting point on the screen
int sx = (int) x + topExtent[glyph];
int sy = (int) y + leftExtent[glyph];
// boundary of the character's pixel buffer to copy
int px = 0;
int py = 0;
int pw = width[glyph];
int ph = height[glyph];
// if the character is off the screen
if ((sx - ph >= parent.width) || (sy >= parent.height) ||
(sy + pw < 0) || (sx < 0)) return;
// off the left of screen, cut off bottom of letter
if (sx < ph) {
//x0 -= xx; // chop that amount off of the image area to be copied
//w0 += xx; // and reduce the width by that (negative) amount
//py0 -= xx; // if x = -3, cut off 3 pixels from the bottom
//ph0 += xx;
ph -= (ph - sx) - 1;
//sx = 0;
}
// off the right of the screen, cut off top of the letter
if (sx >= parent.width) {
int extra = sx - (parent.width-1);
py += extra;
ph -= extra;
//sx = parent.width-1;
}
// off the top, cut off left edge of letter
if (sy < 0) {
int extra = -sy;
px += extra;
pw -= extra;
sy = 0;
}
// off the bottom, cut off right edge of letter
if (sy + pw >= parent.height-1) {
int extra = (sy + pw) - parent.height;
pw -= extra;
}
int fr = parent.fillRi;
int fg = parent.fillGi;
int fb = parent.fillBi;
int fa = parent.fillAi;
int fpixels[] = images[glyph].pixels;
int spixels[] = parent.pixels;
// loop over the source pixels in the character image
// row & col is the row and column of the source image
// (but they become col & row in the target image)
for (int row = py; row < py + ph; row++) {
for (int col = px; col < px + pw; col++) {
int a1 = (fa * fpixels[row * twidth + col]) >> 8;
int a2 = a1 ^ 0xff;
int p1 = fpixels[row * width[glyph] + col];
try {
//int index = (yy + x0-col)*parent.width + (xx+row-y0);
//int index = (sy + px-col)*parent.width + (sx+row-py);
int index = (sy + px+col)*parent.width + (sx-row);
int p2 = spixels[index];
// x coord is backwards
spixels[index] =
(0xff000000 |
(((a1 * fr + a2 * ((p2 >> 16) & 0xff)) & 0xff00) << 8) |
(( a1 * fg + a2 * ((p2 >> 8) & 0xff)) & 0xff00) |
(( a1 * fb + a2 * ( p2 & 0xff)) >> 8));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("out of bounds " + sy + " " + px + " " + col);
}
}
}
}
// ....................................................................
/**
* This is the union of the Mac Roman and Windows ANSI
* character sets. ISO Latin 1 would be Unicode characters
* 0x80 -> 0xFF, but in practice, it would seem that most
* designers using P5 would rather have the characters
* that they expect from their platform's fonts.
*
* This is more of an interim solution until a much better
* font solution can be determined. (i.e. create fonts on
* the fly from some sort of vector format).
*
* Not that I expect that to happen.
*/
static final char[] EXTRA_CHARS = {
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F,
0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
0x00B0, 0x00B1, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00BA,
0x00BB, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5,
0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD,
0x00CE, 0x00CF, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6,
0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DF,
0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,
0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8,
0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FF, 0x0102, 0x0103,
0x0104, 0x0105, 0x0106, 0x0107, 0x010C, 0x010D, 0x010E, 0x010F,
0x0110, 0x0111, 0x0118, 0x0119, 0x011A, 0x011B, 0x0131, 0x0139,
0x013A, 0x013D, 0x013E, 0x0141, 0x0142, 0x0143, 0x0144, 0x0147,
0x0148, 0x0150, 0x0151, 0x0152, 0x0153, 0x0154, 0x0155, 0x0158,
0x0159, 0x015A, 0x015B, 0x015E, 0x015F, 0x0160, 0x0161, 0x0162,
0x0163, 0x0164, 0x0165, 0x016E, 0x016F, 0x0170, 0x0171, 0x0178,
0x0179, 0x017A, 0x017B, 0x017C, 0x017D, 0x017E, 0x0192, 0x02C6,
0x02C7, 0x02D8, 0x02D9, 0x02DA, 0x02DB, 0x02DC, 0x02DD, 0x03A9,
0x03C0, 0x2013, 0x2014, 0x2018, 0x2019, 0x201A, 0x201C, 0x201D,
0x201E, 0x2020, 0x2021, 0x2022, 0x2026, 0x2030, 0x2039, 0x203A,
0x2044, 0x20AC, 0x2122, 0x2202, 0x2206, 0x220F, 0x2211, 0x221A,
0x221E, 0x222B, 0x2248, 0x2260, 0x2264, 0x2265, 0x25CA, 0xF8FF,
0xFB01, 0xFB02
};
static char[] charset;
static {
charset = new char[126-33+1 + EXTRA_CHARS.length];
int index = 0;
for (int i = 33; i <= 126; i++) {
charset[index++] = (char)i;
}
for (int i = 0; i < EXTRA_CHARS.length; i++) {
charset[index++] = EXTRA_CHARS[i];
}
};
public PFont(String name, int size) {
this(new Font(name, Font.PLAIN, size), false, true);
}
public PFont(String name, int size, boolean smooth) {
this(new Font(name, Font.PLAIN, size), false, smooth);
}
public PFont(Font font, boolean all, boolean smooth) {
try {
this.charCount = all ? 65536 : charset.length;
this.mbox = font.getSize();
fwidth = fheight = mbox;
PImage bitmaps[] = new PImage[charCount];
// allocate enough space for the character info
value = new int[charCount];
height = new int[charCount];
width = new int[charCount];
setWidth = new int[charCount];
topExtent = new int[charCount];
leftExtent = new int[charCount];
ascii = new int[128];
for (int i = 0; i < 128; i++) ascii[i] = -1;
int mbox3 = mbox * 3;
/*
BufferedImage playground =
new BufferedImage(mbox3, mbox3, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) playground.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
smooth ?
RenderingHints.VALUE_ANTIALIAS_ON :
RenderingHints.VALUE_ANTIALIAS_OFF);
*/
Class bufferedImageClass =
Class.forName("java.awt.image.BufferedImage");
Constructor bufferedImageConstructor =
bufferedImageClass.getConstructor(new Class[] {
Integer.TYPE,
Integer.TYPE,
Integer.TYPE });
Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB");
int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField);
Object playground =
bufferedImageConstructor.newInstance(new Object[] {
new Integer(mbox3),
new Integer(mbox3),
new Integer(typeIntRgb) });
Class graphicsClass =
Class.forName("java.awt.Graphics2D");
Method getGraphicsMethod =
bufferedImageClass.getMethod("getGraphics", new Class[] { });
//Object g = getGraphicsMethod.invoke(playground, new Object[] { });
Graphics g = (Graphics)
getGraphicsMethod.invoke(playground, new Object[] { });
Class renderingHintsClass =
Class.forName("java.awt.RenderingHints");
Class renderingHintsKeyClass =
Class.forName("java.awt.RenderingHints$Key");
//PApplet.printarr(renderingHintsClass.getFields());
Field antialiasingKeyField =
- renderingHintsClass.getDeclaredField("KEY_ANTIALIASING");
+ renderingHintsClass.getDeclaredField("KEY_TEXT_ANTIALIASING");
Object antialiasingKey =
antialiasingKeyField.get(renderingHintsClass);
Field antialiasField = smooth ?
- renderingHintsClass.getField("VALUE_ANTIALIAS_ON") :
- renderingHintsClass.getField("VALUE_ANTIALIAS_OFF");
+ renderingHintsClass.getField("VALUE_TEXT_ANTIALIAS_ON") :
+ renderingHintsClass.getField("VALUE_TEXT_ANTIALIAS_OFF");
Object antialiasState =
antialiasField.get(renderingHintsClass);
Method setRenderingHintMethod =
graphicsClass.getMethod("setRenderingHint",
new Class[] { renderingHintsKeyClass,
Object.class });
setRenderingHintMethod.invoke(g, new Object[] {
antialiasingKey,
antialiasState
});
g.setFont(font);
FontMetrics metrics = g.getFontMetrics();
Method canDisplayMethod = null;
Method getDataMethod = null;
Method getSamplesMethod = null;
int samples[] = new int[mbox3 * mbox3];
canDisplayMethod =
Font.class.getMethod("canDisplay", new Class[] { Character.TYPE });
getDataMethod =
bufferedImageClass.getMethod("getData", new Class[] { });
Class rasterClass = Class.forName("java.awt.image.Raster");
getSamplesMethod = rasterClass.getMethod("getSamples", new Class[] {
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
// integer array type?
//Array.class
samples.getClass()
});
//} catch (Exception e) {
//e.printStackTrace();
//return;
//}
//Array samples = Array.newInstance(Integer.TYPE, mbox3*mbox3);
int maxWidthHeight = 0;
int index = 0;
for (int i = 0; i < charCount; i++) {
char c = all ? (char)i : charset[i];
//if (!font.canDisplay(c)) { // skip chars not in the font
try {
Character ch = new Character(c);
Boolean canDisplay = (Boolean)
canDisplayMethod.invoke(font, new Object[] { ch });
if (canDisplay.booleanValue() == false) {
continue;
}
} catch (Exception e) {
e.printStackTrace();
return;
}
g.setColor(Color.white);
g.fillRect(0, 0, mbox3, mbox3);
g.setColor(Color.black);
g.drawString(String.valueOf(c), mbox, mbox * 2);
// grabs copy of the current data.. so no updates (do each time)
/*
Raster raster = playground.getData();
raster.getSamples(0, 0, mbox3, mbox3, 0, samples);
*/
Object raster = getDataMethod.invoke(playground, new Object[] {});
getSamplesMethod.invoke(raster, new Object[] {
new Integer(0),
new Integer(0),
new Integer(mbox3),
new Integer(mbox3),
new Integer(0),
samples
});
//int w = metrics.charWidth(c);
int minX = 1000, maxX = 0;
int minY = 1000, maxY = 0;
boolean pixelFound = false;
for (int y = 0; y < mbox3; y++) {
for (int x = 0; x < mbox3; x++) {
//int sample = raster.getSample(x, y, 0); // maybe?
int sample = samples[y * mbox3 + x] & 0xff;
// or int samples[] = raster.getPixel(x, y, null);
//if (sample == 0) { // or just not white? hmm
if (sample != 255) {
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
pixelFound = true;
//System.out.println(x + " " + y + " = " + sample);
}
}
}
if (!pixelFound) {
//System.out.println("no pixels found in char " + ((char)i));
// this was dumb that it was set to 20 & 30, because for small
// fonts, those guys don't exist
minX = minY = 0; //20;
maxX = maxY = 0; //30;
// this will create a 1 pixel white (clear) character..
// maybe better to set one to -1 so nothing is added?
}
value[index] = c;
height[index] = (maxY - minY) + 1;
width[index] = (maxX - minX) + 1;
setWidth[index] = metrics.charWidth(c);
//System.out.println((char)c + " " + setWidth[index]);
// cache locations of the ascii charset
//if (value[i] < 128) ascii[value[i]] = i;
if (c < 128) ascii[c] = index;
// offset from vertical location of baseline
// of where the char was drawn (mbox*2)
topExtent[index] = mbox*2 - minY;
// offset from left of where coord was drawn
leftExtent[index] = minX - mbox;
if (c == 'd') {
ascent = topExtent[index];
}
if (c == 'p') {
descent = -topExtent[index] + height[index];
}
if (width[index] > maxWidthHeight) maxWidthHeight = width[index];
if (height[index] > maxWidthHeight) maxWidthHeight = height[index];
bitmaps[index] = new PImage(new int[width[index] * height[index]],
width[index], height[index], ALPHA);
for (int y = minY; y <= maxY; y++) {
for (int x = minX; x <= maxX; x++) {
int value = 255 - (samples[y * mbox3 + x] & 0xff);
//int value = 255 - raster.getSample(x, y, 0);
int pindex = (y - minY) * width[index] + (x - minX);
bitmaps[index].pixels[pindex] = value;
}
}
index++;
}
charCount = index;
// foreign font, so just make ascent the max topExtent
if ((ascent == 0) && (descent == 0)) {
for (int i = 0; i < charCount; i++) {
char cc = (char) value[i];
if (Character.isWhitespace(cc) ||
(cc == '\u00A0') || (cc == '\u2007') || (cc == '\u202F')) {
continue;
}
if (topExtent[i] > ascent) {
ascent = topExtent[i];
}
int d = -topExtent[i] + height[i];
if (d > descent) {
descent = d;
}
}
}
// size for image/texture is next power of 2 over largest char
mbox2 = (int)
Math.pow(2, Math.ceil(Math.log(maxWidthHeight) / Math.log(2)));
twidth = theight = mbox2;
// shove the smaller PImage data into textures of next-power-of-2 size,
// so that this font can be used immediately by p5.
images = new PImage[charCount];
for (int i = 0; i < charCount; i++) {
images[i] = new PImage(new int[mbox2*mbox2], mbox2, mbox2, ALPHA);
for (int y = 0; y < height[i]; y++) {
System.arraycopy(bitmaps[i].pixels, y*width[i],
images[i].pixels, y*mbox2,
width[i]);
}
bitmaps[i] = null;
}
} catch (Exception e) { // catch-all for reflection stuff
e.printStackTrace();
return;
}
}
}
| false | true | public PFont(Font font, boolean all, boolean smooth) {
try {
this.charCount = all ? 65536 : charset.length;
this.mbox = font.getSize();
fwidth = fheight = mbox;
PImage bitmaps[] = new PImage[charCount];
// allocate enough space for the character info
value = new int[charCount];
height = new int[charCount];
width = new int[charCount];
setWidth = new int[charCount];
topExtent = new int[charCount];
leftExtent = new int[charCount];
ascii = new int[128];
for (int i = 0; i < 128; i++) ascii[i] = -1;
int mbox3 = mbox * 3;
/*
BufferedImage playground =
new BufferedImage(mbox3, mbox3, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) playground.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
smooth ?
RenderingHints.VALUE_ANTIALIAS_ON :
RenderingHints.VALUE_ANTIALIAS_OFF);
*/
Class bufferedImageClass =
Class.forName("java.awt.image.BufferedImage");
Constructor bufferedImageConstructor =
bufferedImageClass.getConstructor(new Class[] {
Integer.TYPE,
Integer.TYPE,
Integer.TYPE });
Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB");
int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField);
Object playground =
bufferedImageConstructor.newInstance(new Object[] {
new Integer(mbox3),
new Integer(mbox3),
new Integer(typeIntRgb) });
Class graphicsClass =
Class.forName("java.awt.Graphics2D");
Method getGraphicsMethod =
bufferedImageClass.getMethod("getGraphics", new Class[] { });
//Object g = getGraphicsMethod.invoke(playground, new Object[] { });
Graphics g = (Graphics)
getGraphicsMethod.invoke(playground, new Object[] { });
Class renderingHintsClass =
Class.forName("java.awt.RenderingHints");
Class renderingHintsKeyClass =
Class.forName("java.awt.RenderingHints$Key");
//PApplet.printarr(renderingHintsClass.getFields());
Field antialiasingKeyField =
renderingHintsClass.getDeclaredField("KEY_ANTIALIASING");
Object antialiasingKey =
antialiasingKeyField.get(renderingHintsClass);
Field antialiasField = smooth ?
renderingHintsClass.getField("VALUE_ANTIALIAS_ON") :
renderingHintsClass.getField("VALUE_ANTIALIAS_OFF");
Object antialiasState =
antialiasField.get(renderingHintsClass);
Method setRenderingHintMethod =
graphicsClass.getMethod("setRenderingHint",
new Class[] { renderingHintsKeyClass,
Object.class });
setRenderingHintMethod.invoke(g, new Object[] {
antialiasingKey,
antialiasState
});
g.setFont(font);
FontMetrics metrics = g.getFontMetrics();
Method canDisplayMethod = null;
Method getDataMethod = null;
Method getSamplesMethod = null;
int samples[] = new int[mbox3 * mbox3];
canDisplayMethod =
Font.class.getMethod("canDisplay", new Class[] { Character.TYPE });
getDataMethod =
bufferedImageClass.getMethod("getData", new Class[] { });
Class rasterClass = Class.forName("java.awt.image.Raster");
getSamplesMethod = rasterClass.getMethod("getSamples", new Class[] {
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
// integer array type?
//Array.class
samples.getClass()
});
//} catch (Exception e) {
//e.printStackTrace();
//return;
//}
//Array samples = Array.newInstance(Integer.TYPE, mbox3*mbox3);
int maxWidthHeight = 0;
int index = 0;
for (int i = 0; i < charCount; i++) {
char c = all ? (char)i : charset[i];
//if (!font.canDisplay(c)) { // skip chars not in the font
try {
Character ch = new Character(c);
Boolean canDisplay = (Boolean)
canDisplayMethod.invoke(font, new Object[] { ch });
if (canDisplay.booleanValue() == false) {
continue;
}
} catch (Exception e) {
e.printStackTrace();
return;
}
g.setColor(Color.white);
g.fillRect(0, 0, mbox3, mbox3);
g.setColor(Color.black);
g.drawString(String.valueOf(c), mbox, mbox * 2);
// grabs copy of the current data.. so no updates (do each time)
/*
Raster raster = playground.getData();
raster.getSamples(0, 0, mbox3, mbox3, 0, samples);
*/
Object raster = getDataMethod.invoke(playground, new Object[] {});
getSamplesMethod.invoke(raster, new Object[] {
new Integer(0),
new Integer(0),
new Integer(mbox3),
new Integer(mbox3),
new Integer(0),
samples
});
//int w = metrics.charWidth(c);
int minX = 1000, maxX = 0;
int minY = 1000, maxY = 0;
boolean pixelFound = false;
for (int y = 0; y < mbox3; y++) {
for (int x = 0; x < mbox3; x++) {
//int sample = raster.getSample(x, y, 0); // maybe?
int sample = samples[y * mbox3 + x] & 0xff;
// or int samples[] = raster.getPixel(x, y, null);
//if (sample == 0) { // or just not white? hmm
if (sample != 255) {
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
pixelFound = true;
//System.out.println(x + " " + y + " = " + sample);
}
}
}
if (!pixelFound) {
//System.out.println("no pixels found in char " + ((char)i));
// this was dumb that it was set to 20 & 30, because for small
// fonts, those guys don't exist
minX = minY = 0; //20;
maxX = maxY = 0; //30;
// this will create a 1 pixel white (clear) character..
// maybe better to set one to -1 so nothing is added?
}
value[index] = c;
height[index] = (maxY - minY) + 1;
width[index] = (maxX - minX) + 1;
setWidth[index] = metrics.charWidth(c);
//System.out.println((char)c + " " + setWidth[index]);
// cache locations of the ascii charset
//if (value[i] < 128) ascii[value[i]] = i;
if (c < 128) ascii[c] = index;
// offset from vertical location of baseline
// of where the char was drawn (mbox*2)
topExtent[index] = mbox*2 - minY;
// offset from left of where coord was drawn
leftExtent[index] = minX - mbox;
if (c == 'd') {
ascent = topExtent[index];
}
if (c == 'p') {
descent = -topExtent[index] + height[index];
}
if (width[index] > maxWidthHeight) maxWidthHeight = width[index];
if (height[index] > maxWidthHeight) maxWidthHeight = height[index];
bitmaps[index] = new PImage(new int[width[index] * height[index]],
width[index], height[index], ALPHA);
for (int y = minY; y <= maxY; y++) {
for (int x = minX; x <= maxX; x++) {
int value = 255 - (samples[y * mbox3 + x] & 0xff);
//int value = 255 - raster.getSample(x, y, 0);
int pindex = (y - minY) * width[index] + (x - minX);
bitmaps[index].pixels[pindex] = value;
}
}
index++;
}
charCount = index;
// foreign font, so just make ascent the max topExtent
if ((ascent == 0) && (descent == 0)) {
for (int i = 0; i < charCount; i++) {
char cc = (char) value[i];
if (Character.isWhitespace(cc) ||
(cc == '\u00A0') || (cc == '\u2007') || (cc == '\u202F')) {
continue;
}
if (topExtent[i] > ascent) {
ascent = topExtent[i];
}
int d = -topExtent[i] + height[i];
if (d > descent) {
descent = d;
}
}
}
// size for image/texture is next power of 2 over largest char
mbox2 = (int)
Math.pow(2, Math.ceil(Math.log(maxWidthHeight) / Math.log(2)));
twidth = theight = mbox2;
// shove the smaller PImage data into textures of next-power-of-2 size,
// so that this font can be used immediately by p5.
images = new PImage[charCount];
for (int i = 0; i < charCount; i++) {
images[i] = new PImage(new int[mbox2*mbox2], mbox2, mbox2, ALPHA);
for (int y = 0; y < height[i]; y++) {
System.arraycopy(bitmaps[i].pixels, y*width[i],
images[i].pixels, y*mbox2,
width[i]);
}
bitmaps[i] = null;
}
} catch (Exception e) { // catch-all for reflection stuff
e.printStackTrace();
return;
}
}
| public PFont(Font font, boolean all, boolean smooth) {
try {
this.charCount = all ? 65536 : charset.length;
this.mbox = font.getSize();
fwidth = fheight = mbox;
PImage bitmaps[] = new PImage[charCount];
// allocate enough space for the character info
value = new int[charCount];
height = new int[charCount];
width = new int[charCount];
setWidth = new int[charCount];
topExtent = new int[charCount];
leftExtent = new int[charCount];
ascii = new int[128];
for (int i = 0; i < 128; i++) ascii[i] = -1;
int mbox3 = mbox * 3;
/*
BufferedImage playground =
new BufferedImage(mbox3, mbox3, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) playground.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
smooth ?
RenderingHints.VALUE_ANTIALIAS_ON :
RenderingHints.VALUE_ANTIALIAS_OFF);
*/
Class bufferedImageClass =
Class.forName("java.awt.image.BufferedImage");
Constructor bufferedImageConstructor =
bufferedImageClass.getConstructor(new Class[] {
Integer.TYPE,
Integer.TYPE,
Integer.TYPE });
Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB");
int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField);
Object playground =
bufferedImageConstructor.newInstance(new Object[] {
new Integer(mbox3),
new Integer(mbox3),
new Integer(typeIntRgb) });
Class graphicsClass =
Class.forName("java.awt.Graphics2D");
Method getGraphicsMethod =
bufferedImageClass.getMethod("getGraphics", new Class[] { });
//Object g = getGraphicsMethod.invoke(playground, new Object[] { });
Graphics g = (Graphics)
getGraphicsMethod.invoke(playground, new Object[] { });
Class renderingHintsClass =
Class.forName("java.awt.RenderingHints");
Class renderingHintsKeyClass =
Class.forName("java.awt.RenderingHints$Key");
//PApplet.printarr(renderingHintsClass.getFields());
Field antialiasingKeyField =
renderingHintsClass.getDeclaredField("KEY_TEXT_ANTIALIASING");
Object antialiasingKey =
antialiasingKeyField.get(renderingHintsClass);
Field antialiasField = smooth ?
renderingHintsClass.getField("VALUE_TEXT_ANTIALIAS_ON") :
renderingHintsClass.getField("VALUE_TEXT_ANTIALIAS_OFF");
Object antialiasState =
antialiasField.get(renderingHintsClass);
Method setRenderingHintMethod =
graphicsClass.getMethod("setRenderingHint",
new Class[] { renderingHintsKeyClass,
Object.class });
setRenderingHintMethod.invoke(g, new Object[] {
antialiasingKey,
antialiasState
});
g.setFont(font);
FontMetrics metrics = g.getFontMetrics();
Method canDisplayMethod = null;
Method getDataMethod = null;
Method getSamplesMethod = null;
int samples[] = new int[mbox3 * mbox3];
canDisplayMethod =
Font.class.getMethod("canDisplay", new Class[] { Character.TYPE });
getDataMethod =
bufferedImageClass.getMethod("getData", new Class[] { });
Class rasterClass = Class.forName("java.awt.image.Raster");
getSamplesMethod = rasterClass.getMethod("getSamples", new Class[] {
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
Integer.TYPE,
// integer array type?
//Array.class
samples.getClass()
});
//} catch (Exception e) {
//e.printStackTrace();
//return;
//}
//Array samples = Array.newInstance(Integer.TYPE, mbox3*mbox3);
int maxWidthHeight = 0;
int index = 0;
for (int i = 0; i < charCount; i++) {
char c = all ? (char)i : charset[i];
//if (!font.canDisplay(c)) { // skip chars not in the font
try {
Character ch = new Character(c);
Boolean canDisplay = (Boolean)
canDisplayMethod.invoke(font, new Object[] { ch });
if (canDisplay.booleanValue() == false) {
continue;
}
} catch (Exception e) {
e.printStackTrace();
return;
}
g.setColor(Color.white);
g.fillRect(0, 0, mbox3, mbox3);
g.setColor(Color.black);
g.drawString(String.valueOf(c), mbox, mbox * 2);
// grabs copy of the current data.. so no updates (do each time)
/*
Raster raster = playground.getData();
raster.getSamples(0, 0, mbox3, mbox3, 0, samples);
*/
Object raster = getDataMethod.invoke(playground, new Object[] {});
getSamplesMethod.invoke(raster, new Object[] {
new Integer(0),
new Integer(0),
new Integer(mbox3),
new Integer(mbox3),
new Integer(0),
samples
});
//int w = metrics.charWidth(c);
int minX = 1000, maxX = 0;
int minY = 1000, maxY = 0;
boolean pixelFound = false;
for (int y = 0; y < mbox3; y++) {
for (int x = 0; x < mbox3; x++) {
//int sample = raster.getSample(x, y, 0); // maybe?
int sample = samples[y * mbox3 + x] & 0xff;
// or int samples[] = raster.getPixel(x, y, null);
//if (sample == 0) { // or just not white? hmm
if (sample != 255) {
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
pixelFound = true;
//System.out.println(x + " " + y + " = " + sample);
}
}
}
if (!pixelFound) {
//System.out.println("no pixels found in char " + ((char)i));
// this was dumb that it was set to 20 & 30, because for small
// fonts, those guys don't exist
minX = minY = 0; //20;
maxX = maxY = 0; //30;
// this will create a 1 pixel white (clear) character..
// maybe better to set one to -1 so nothing is added?
}
value[index] = c;
height[index] = (maxY - minY) + 1;
width[index] = (maxX - minX) + 1;
setWidth[index] = metrics.charWidth(c);
//System.out.println((char)c + " " + setWidth[index]);
// cache locations of the ascii charset
//if (value[i] < 128) ascii[value[i]] = i;
if (c < 128) ascii[c] = index;
// offset from vertical location of baseline
// of where the char was drawn (mbox*2)
topExtent[index] = mbox*2 - minY;
// offset from left of where coord was drawn
leftExtent[index] = minX - mbox;
if (c == 'd') {
ascent = topExtent[index];
}
if (c == 'p') {
descent = -topExtent[index] + height[index];
}
if (width[index] > maxWidthHeight) maxWidthHeight = width[index];
if (height[index] > maxWidthHeight) maxWidthHeight = height[index];
bitmaps[index] = new PImage(new int[width[index] * height[index]],
width[index], height[index], ALPHA);
for (int y = minY; y <= maxY; y++) {
for (int x = minX; x <= maxX; x++) {
int value = 255 - (samples[y * mbox3 + x] & 0xff);
//int value = 255 - raster.getSample(x, y, 0);
int pindex = (y - minY) * width[index] + (x - minX);
bitmaps[index].pixels[pindex] = value;
}
}
index++;
}
charCount = index;
// foreign font, so just make ascent the max topExtent
if ((ascent == 0) && (descent == 0)) {
for (int i = 0; i < charCount; i++) {
char cc = (char) value[i];
if (Character.isWhitespace(cc) ||
(cc == '\u00A0') || (cc == '\u2007') || (cc == '\u202F')) {
continue;
}
if (topExtent[i] > ascent) {
ascent = topExtent[i];
}
int d = -topExtent[i] + height[i];
if (d > descent) {
descent = d;
}
}
}
// size for image/texture is next power of 2 over largest char
mbox2 = (int)
Math.pow(2, Math.ceil(Math.log(maxWidthHeight) / Math.log(2)));
twidth = theight = mbox2;
// shove the smaller PImage data into textures of next-power-of-2 size,
// so that this font can be used immediately by p5.
images = new PImage[charCount];
for (int i = 0; i < charCount; i++) {
images[i] = new PImage(new int[mbox2*mbox2], mbox2, mbox2, ALPHA);
for (int y = 0; y < height[i]; y++) {
System.arraycopy(bitmaps[i].pixels, y*width[i],
images[i].pixels, y*mbox2,
width[i]);
}
bitmaps[i] = null;
}
} catch (Exception e) { // catch-all for reflection stuff
e.printStackTrace();
return;
}
}
|
diff --git a/demo/org/achartengine/chartdemo/demo/chart/PieChartBuilder.java b/demo/org/achartengine/chartdemo/demo/chart/PieChartBuilder.java
index 0ac50c1..1cd9dfa 100644
--- a/demo/org/achartengine/chartdemo/demo/chart/PieChartBuilder.java
+++ b/demo/org/achartengine/chartdemo/demo/chart/PieChartBuilder.java
@@ -1,158 +1,160 @@
/**
* Copyright (C) 2009, 2010 SC 4ViewSoft SRL
*
* 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.achartengine.chartdemo.demo.chart;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chartdemo.demo.R;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.SeriesSelection;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PieChartBuilder extends Activity {
public static final String TYPE = "type";
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN };
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private String mDateFormat;
private Button mAdd;
private EditText mX;
private GraphicalView mChartView;
@Override
protected void onRestoreInstanceState(Bundle savedState) {
super.onRestoreInstanceState(savedState);
mSeries = (CategorySeries) savedState.getSerializable("current_series");
mRenderer = (DefaultRenderer) savedState.getSerializable("current_renderer");
mDateFormat = savedState.getString("date_format");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("current_series", mSeries);
outState.putSerializable("current_renderer", mRenderer);
outState.putString("date_format", mDateFormat);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xy_chart);
mX = (EditText) findViewById(R.id.xValue);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
mAdd = (Button) findViewById(R.id.add);
mAdd.setEnabled(true);
mX.setEnabled(true);
mAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
double x = 0;
try {
x = Double.parseDouble(mX.getText().toString());
} catch (NumberFormatException e) {
// TODO
mX.requestFocus();
return;
}
mSeries.add("Series " + (mSeries.getItemCount() + 1), x);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
mX.setText("");
mX.requestFocus();
if (mChartView != null) {
mChartView.repaint();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast
.makeText(PieChartBuilder.this, "No chart element was clicked", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
PieChartBuilder.this,
"Chart element data point index " + seriesSelection.getPointIndex()
+ " was clicked" + " point value=" + seriesSelection.getValue(),
Toast.LENGTH_SHORT).show();
}
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(PieChartBuilder.this, "No chart element was long pressed",
- Toast.LENGTH_SHORT);
+ Toast.LENGTH_SHORT).show();
return false; // no chart element was long pressed, so let something
// else handle the event
} else {
- Toast.makeText(PieChartBuilder.this, "Chart element data point index "
- + seriesSelection.getPointIndex() + " was long pressed", Toast.LENGTH_SHORT);
+ Toast.makeText(
+ PieChartBuilder.this,
+ "Chart element data point index " + seriesSelection.getPointIndex()
+ + " was long pressed", Toast.LENGTH_SHORT).show();
return true; // the element was long pressed - the event has been
// handled
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
mChartView.repaint();
}
}
}
| false | true | protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast
.makeText(PieChartBuilder.this, "No chart element was clicked", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
PieChartBuilder.this,
"Chart element data point index " + seriesSelection.getPointIndex()
+ " was clicked" + " point value=" + seriesSelection.getValue(),
Toast.LENGTH_SHORT).show();
}
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(PieChartBuilder.this, "No chart element was long pressed",
Toast.LENGTH_SHORT);
return false; // no chart element was long pressed, so let something
// else handle the event
} else {
Toast.makeText(PieChartBuilder.this, "Chart element data point index "
+ seriesSelection.getPointIndex() + " was long pressed", Toast.LENGTH_SHORT);
return true; // the element was long pressed - the event has been
// handled
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
mChartView.repaint();
}
}
| protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);
mChartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast
.makeText(PieChartBuilder.this, "No chart element was clicked", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(
PieChartBuilder.this,
"Chart element data point index " + seriesSelection.getPointIndex()
+ " was clicked" + " point value=" + seriesSelection.getValue(),
Toast.LENGTH_SHORT).show();
}
}
});
mChartView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(PieChartBuilder.this, "No chart element was long pressed",
Toast.LENGTH_SHORT).show();
return false; // no chart element was long pressed, so let something
// else handle the event
} else {
Toast.makeText(
PieChartBuilder.this,
"Chart element data point index " + seriesSelection.getPointIndex()
+ " was long pressed", Toast.LENGTH_SHORT).show();
return true; // the element was long pressed - the event has been
// handled
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
} else {
mChartView.repaint();
}
}
|
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transformations/LocalArrayRemoval.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transformations/LocalArrayRemoval.java
index 91a0e2b6d..70f2858ab 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transformations/LocalArrayRemoval.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/xlim/transformations/LocalArrayRemoval.java
@@ -1,70 +1,71 @@
/*
* Copyright (c) 2011, IRISA
* 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 IRISA 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.backends.xlim.transformations;
import java.util.ArrayList;
import net.sf.orcc.ir.Actor;
import net.sf.orcc.ir.IrFactory;
import net.sf.orcc.ir.Procedure;
import net.sf.orcc.ir.Use;
import net.sf.orcc.ir.Var;
import net.sf.orcc.ir.util.AbstractActorVisitor;
import net.sf.orcc.ir.util.EcoreHelper;
import org.eclipse.emf.common.util.EList;
/**
* Replace local arrays by global ones.
*
* @author Herve Yviquel
*
*/
public class LocalArrayRemoval extends AbstractActorVisitor<Object> {
@Override
public Object caseProcedure(Procedure procedure) {
Actor actor = EcoreHelper.getContainerOfType(procedure, Actor.class);
EList<Var> stateVars = actor.getStateVars();
for (Var var : new ArrayList<Var>(procedure.getLocals())) {
if (var.getType().isList()) {
Var newVar = IrFactory.eINSTANCE.createVar(var.getType(),
var.getName(), true, var.getIndex());
newVar.setInitialValue(var.getInitialValue());
+ newVar.setGlobal(true);
EList<Use> uses = var.getUses();
while (!uses.isEmpty()) {
uses.get(0).setVariable(newVar);
}
EcoreHelper.delete(var);
stateVars.add(newVar);
}
}
return null;
}
}
| true | true | public Object caseProcedure(Procedure procedure) {
Actor actor = EcoreHelper.getContainerOfType(procedure, Actor.class);
EList<Var> stateVars = actor.getStateVars();
for (Var var : new ArrayList<Var>(procedure.getLocals())) {
if (var.getType().isList()) {
Var newVar = IrFactory.eINSTANCE.createVar(var.getType(),
var.getName(), true, var.getIndex());
newVar.setInitialValue(var.getInitialValue());
EList<Use> uses = var.getUses();
while (!uses.isEmpty()) {
uses.get(0).setVariable(newVar);
}
EcoreHelper.delete(var);
stateVars.add(newVar);
}
}
return null;
}
| public Object caseProcedure(Procedure procedure) {
Actor actor = EcoreHelper.getContainerOfType(procedure, Actor.class);
EList<Var> stateVars = actor.getStateVars();
for (Var var : new ArrayList<Var>(procedure.getLocals())) {
if (var.getType().isList()) {
Var newVar = IrFactory.eINSTANCE.createVar(var.getType(),
var.getName(), true, var.getIndex());
newVar.setInitialValue(var.getInitialValue());
newVar.setGlobal(true);
EList<Use> uses = var.getUses();
while (!uses.isEmpty()) {
uses.get(0).setVariable(newVar);
}
EcoreHelper.delete(var);
stateVars.add(newVar);
}
}
return null;
}
|
diff --git a/aop/src/main/org/jboss/aop/classpool/AOPClassPool.java b/aop/src/main/org/jboss/aop/classpool/AOPClassPool.java
index 93cdcf3a..ff8ba922 100644
--- a/aop/src/main/org/jboss/aop/classpool/AOPClassPool.java
+++ b/aop/src/main/org/jboss/aop/classpool/AOPClassPool.java
@@ -1,206 +1,197 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.aop.classpool;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Map;
import org.jboss.aop.AspectManager;
import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import javassist.scopedpool.ScopedClassPool;
import javassist.scopedpool.ScopedClassPoolRepository;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision$
*/
public class AOPClassPool extends ScopedClassPool
{
/** Classnames of classes that will be created - we do not want to look for these in other pools */
protected ConcurrentReaderHashMap generatedClasses = new ConcurrentReaderHashMap();
protected ConcurrentReaderHashMap localResources = new ConcurrentReaderHashMap();
static
{
ClassPool.doPruning = false;
ClassPool.releaseUnmodifiedClassFile = false;
}
public AOPClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository)
{
super(cl, src, repository);
}
protected AOPClassPool(ClassPool src, ScopedClassPoolRepository repository)
{
this(null, src, repository);
}
public void setClassLoader(ClassLoader cl)
{
classLoader = new WeakReference(cl);
}
public void registerGeneratedClass(String className)
{
generatedClasses.put(className, className);
}
public void close()
{
super.close();
AOPClassPoolRepository.getInstance().perfomUnregisterClassLoader(getClassLoader());
}
public CtClass getCached(String classname)
{
CtClass clazz = getCachedLocally(classname);
if (clazz == null)
{
boolean isLocal = false;
- //FIXME - Once Javassist > 3.3.0 is out use getClassLoader0() and get rid of try/catch
- ClassLoader cl = null;
- try
- {
- cl = getClassLoader();
- }
- catch (RuntimeException e)
- {
- //Ignore, the ScopedClassPoll throws an exception if pool is not associated with a cl
- }
+ ClassLoader cl = getClassLoader0();
if (cl != null)
{
String classResourceName = getResourceName(classname);
isLocal = isLocalResource(classResourceName);
}
if (!isLocal)
{
Object o = generatedClasses.get(classname);
if (o == null)
{
Map registeredCLs = AspectManager.getRegisteredCLs();
synchronized (registeredCLs)
{
Iterator it = registeredCLs.values().iterator();
while (it.hasNext())
{
AOPClassPool pool = (AOPClassPool) it.next();
if (pool.isUnloadedClassLoader())
{
AspectManager.instance().unregisterClassLoader(pool.getClassLoader());
continue;
}
//Do not check classpools for scoped classloaders
if (pool.getClass().getName().equals("org.jboss.aop.deployment.ScopedJBossClassPool"))
{
continue;
}
clazz = pool.getCachedLocally(classname);
if (clazz != null)
{
return clazz;
}
}
}
}
}
}
// *NOTE* NEED TO TEST WHEN SUPERCLASS IS IN ANOTHER UCL!!!!!!
return clazz;
}
protected String getResourceName(String classname)
{
final int lastIndex = classname.lastIndexOf('$');
if (lastIndex < 0)
{
return classname.replaceAll("[\\.]", "/") + ".class";
}
else
{
return classname.substring(0, lastIndex).replaceAll("[\\.]", "/") + classname.substring(lastIndex) + ".class";
}
}
protected boolean isLocalResource(String resourceName)
{
String classResourceName = getResourceName(resourceName);
Boolean isLocal = (Boolean)localResources.get(classResourceName);
if (isLocal != null)
{
return isLocal.booleanValue();
}
boolean localResource = getClassLoader().getResource(classResourceName) != null;
localResources.put(classResourceName, localResource ? Boolean.TRUE : Boolean.FALSE);
return localResource;
}
public synchronized CtClass getLocally(String classname)
throws NotFoundException
{
softcache.remove(classname);
CtClass clazz = (CtClass) classes.get(classname);
if (clazz == null)
{
clazz = createCtClass(classname, true);
if (clazz == null) throw new NotFoundException(classname);
lockInCache(clazz);//Avoid use of the softclasscache
}
return clazz;
}
public static AOPClassPool createAOPClassPool(ClassLoader cl, ClassPool src, ScopedClassPoolRepository repository)
{
return (AOPClassPool)AspectManager.getClassPoolFactory().create(cl, src, repository);
}
public static AOPClassPool createAOPClassPool(ClassPool src, ScopedClassPoolRepository repository)
{
return (AOPClassPool)AspectManager.getClassPoolFactory().create(src, repository);
}
public String toString()
{
ClassLoader cl = null;
try
{
cl = getClassLoader();
}
catch(IllegalStateException ignore)
{
}
return super.toString() + " - dcl " + cl;
}
}
| true | true | public CtClass getCached(String classname)
{
CtClass clazz = getCachedLocally(classname);
if (clazz == null)
{
boolean isLocal = false;
//FIXME - Once Javassist > 3.3.0 is out use getClassLoader0() and get rid of try/catch
ClassLoader cl = null;
try
{
cl = getClassLoader();
}
catch (RuntimeException e)
{
//Ignore, the ScopedClassPoll throws an exception if pool is not associated with a cl
}
if (cl != null)
{
String classResourceName = getResourceName(classname);
isLocal = isLocalResource(classResourceName);
}
if (!isLocal)
{
Object o = generatedClasses.get(classname);
if (o == null)
{
Map registeredCLs = AspectManager.getRegisteredCLs();
synchronized (registeredCLs)
{
Iterator it = registeredCLs.values().iterator();
while (it.hasNext())
{
AOPClassPool pool = (AOPClassPool) it.next();
if (pool.isUnloadedClassLoader())
{
AspectManager.instance().unregisterClassLoader(pool.getClassLoader());
continue;
}
//Do not check classpools for scoped classloaders
if (pool.getClass().getName().equals("org.jboss.aop.deployment.ScopedJBossClassPool"))
{
continue;
}
clazz = pool.getCachedLocally(classname);
if (clazz != null)
{
return clazz;
}
}
}
}
}
}
// *NOTE* NEED TO TEST WHEN SUPERCLASS IS IN ANOTHER UCL!!!!!!
return clazz;
}
| public CtClass getCached(String classname)
{
CtClass clazz = getCachedLocally(classname);
if (clazz == null)
{
boolean isLocal = false;
ClassLoader cl = getClassLoader0();
if (cl != null)
{
String classResourceName = getResourceName(classname);
isLocal = isLocalResource(classResourceName);
}
if (!isLocal)
{
Object o = generatedClasses.get(classname);
if (o == null)
{
Map registeredCLs = AspectManager.getRegisteredCLs();
synchronized (registeredCLs)
{
Iterator it = registeredCLs.values().iterator();
while (it.hasNext())
{
AOPClassPool pool = (AOPClassPool) it.next();
if (pool.isUnloadedClassLoader())
{
AspectManager.instance().unregisterClassLoader(pool.getClassLoader());
continue;
}
//Do not check classpools for scoped classloaders
if (pool.getClass().getName().equals("org.jboss.aop.deployment.ScopedJBossClassPool"))
{
continue;
}
clazz = pool.getCachedLocally(classname);
if (clazz != null)
{
return clazz;
}
}
}
}
}
}
// *NOTE* NEED TO TEST WHEN SUPERCLASS IS IN ANOTHER UCL!!!!!!
return clazz;
}
|
diff --git a/src/MRDriver.java b/src/MRDriver.java
index 9f0e6c4..011c7f8 100644
--- a/src/MRDriver.java
+++ b/src/MRDriver.java
@@ -1,233 +1,231 @@
/**************************************************************************************************************************
* File: MRDriver.java
* Authors: Justin A. DeBrabant ([email protected])
Matteo Riondato ([email protected])
* Last Modified: 12/27/2011
* Description:
Driver for Hadoop implementation of parallel association rule mining.
* Usage: java MRDriver <mapper id> <path to input database> <path to output local FIs> <path to output global FIs>
* mapper id - specifies which Map method should be used
1 for partition mapper, 2 for binomial mapper, 3 for weighted coin flip sampler
* path to input database - path to file containing transactions in .dat format (1 transaction per line)
* local FI output - path to directory to write local (per-reducer) FIs
* global FI output - path to directory to write global FIs (combined from all local FIs)
***************************************************************************************************************************/
import java.net.URI;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Random;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.lib.IdentityMapper;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hadoop.mapred.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class MRDriver extends Configured implements Tool
{
public final int MR_TIMEOUT_MILLI = 60000000;
public static void main(String args[]) throws Exception
{
if (args.length != 10)
{
System.out.println("usage: java MRDriver <epsilon> <delta> <minFreqPercent> <d> <datasetSize> <nodes> <mapper id> <path to input database> " +
"<path to output local FIs> <path to output global FIs>");
System.exit(1);
}
int res = ToolRunner.run(new MRDriver(), args);
System.exit(res);
}
public int run(String args[]) throws Exception
{
long job_start_time, job_end_time;
long job_runtime;
float epsilon = Float.parseFloat(args[0]);
double delta = Double.parseDouble(args[1]);
int minFreqPercent = Integer.parseInt(args[2]);
int d = Integer.parseInt(args[3]);
int datasetSize = Integer.parseInt(args[4]);
int nodes = Integer.parseInt(args[5]);
/************************ Job 1 (local FIM) Configuration ************************/
JobConf conf = new JobConf(getConf());
int numSamples = (int) Math.floor(0.95 * nodes * conf.getInt("mapred.tasktracker.reduce.tasks.maximum", nodes * 2));
- double phi = 1 + (2 * Math.log(delta) / numSamples) + Math.sqrt(Math.pow(2 * Math.log(delta) / numSamples , 2) - (6 * Math.log(delta) / numSamples));
+ double phi = 1 + (2 * Math.log(delta) / numSamples) + Math.sqrt(Math.pow(2 * Math.log(delta) / numSamples , 2) - (2 * Math.log(delta) / numSamples));
- // XXX There shouldn't be any problem in doing this, but I want
- // to check with Eli. MR
if (phi > 1.0)
{
- phi = 1.0;
+ phi = 1.0 - 0.000001;
}
int sampleSize = (int) Math.ceil((2 / Math.pow(epsilon, 2))*(d + Math.log(1/ phi)));
conf.setInt("PARMM.reducersNum", numSamples);
conf.setInt("PARMM.datasetSize", datasetSize);
conf.setInt("PARMM.minFreqPercent", minFreqPercent);
conf.setFloat("PARMM.epsilon", epsilon);
conf.setNumReduceTasks(numSamples);
conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
conf.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI);
conf.setJarByClass(MRDriver.class);
conf.setMapOutputKeyClass(IntWritable.class);
conf.setMapOutputValueClass(Text.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(DoubleWritable.class);
conf.setInputFormat(SequenceFileInputFormat.class);
SequenceFileInputFormat.addInputPath(conf, new Path(args[7]));
conf.setOutputFormat(SequenceFileOutputFormat.class);
SequenceFileOutputFormat.setOutputPath(conf, new Path(args[8]));
// set the mapper class based on command line option
if(args[6].equals("1"))
{
System.out.println("running partition mapper...");
conf.setMapperClass(PartitionMapper.class);
}
else if(args[6].equals("2"))
{
System.out.println("running binomial mapper...");
conf.setMapperClass(BinomialSamplerMapper.class);
}
else if(args[6].equals("3"))
{
System.out.println("running coin mapper...");
conf.setMapperClass(CoinFlipSamplerMapper.class);
}
else if(args[6].equals("4"))
{
System.out.println("running sampler mapper...");
conf.setMapperClass(InputSamplerMapper.class);
// create a random sample of size T*m
Random rand = new Random();
int[] samples = new int[numSamples * sampleSize];
for (int i = 0; i < numSamples * sampleSize; i++)
{
samples[i] = rand.nextInt(datasetSize);
}
// for each key in the sample, create a list of all T samples to which this key belongs
// XXX I wonder whether we could more efficiently create
// the MapWritable directly. MR
Hashtable<LongWritable, ArrayList<IntWritable>> hashTable = new Hashtable<LongWritable, ArrayList<IntWritable>>();
for (int i=0; i < numSamples * sampleSize; i++)
{
ArrayList<IntWritable> sampleIDs = null;
LongWritable key = new LongWritable(samples[i]);
if (hashTable.contains(key))
sampleIDs = hashTable.get(key);
else
sampleIDs = new ArrayList<IntWritable>();
sampleIDs.add(new IntWritable(i / sampleSize));
hashTable.put(key, sampleIDs);
}
MapWritable map = new MapWritable();
for (LongWritable key : hashTable.keySet())
{
ArrayList<IntWritable> sampleIDs = hashTable.get(key);
IntArrayWritable sampleIDsIAW = new IntArrayWritable();
sampleIDsIAW.set(sampleIDs.toArray(new IntWritable[1]));
map.put(key, sampleIDsIAW);
}
FileSystem fs = FileSystem.get(URI.create("samplesMap.ser"), conf);
FSDataOutputStream out = fs.create(new Path("samplesMap.ser"), true);
map.write(out);
out.sync();
out.close();
DistributedCache.addCacheFile(new URI(fs.getWorkingDirectory() + "/samplesMap.ser#samplesMap.ser"), conf);
}
else
{
// NOT REACHED
}
// XXX Why is it necessary to change the default hash partitioner? JD
conf.setPartitionerClass(FIMPartitioner.class);
conf.setReducerClass(FIMReducer.class);
job_start_time = System.currentTimeMillis();
JobClient.runJob(conf);
job_end_time = System.currentTimeMillis();
job_runtime = (job_end_time-job_start_time) / 1000;
System.out.println("local FIM runtime (seconds): " + job_runtime);
/************************ Job 2 (aggregation) Configuration ************************/
JobConf confAggr = new JobConf(getConf());
confAggr.setInt("PARMM.reducersNum", numSamples);
confAggr.setFloat("PARMM.epsilon", epsilon);
confAggr.setBoolean("mapred.reduce.tasks.speculative.execution", false);
confAggr.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI);
confAggr.setJarByClass(MRDriver.class);
confAggr.setMapOutputKeyClass(Text.class);
confAggr.setMapOutputValueClass(DoubleWritable.class);
confAggr.setOutputKeyClass(Text.class);
confAggr.setOutputValueClass(Text.class);
confAggr.setMapperClass(IdentityMapper.class);
confAggr.setReducerClass(AggregateReducer.class);
confAggr.setInputFormat(SequenceFileInputFormat.class);
SequenceFileInputFormat.addInputPath(confAggr, new Path(args[8]));
FileOutputFormat.setOutputPath(confAggr, new Path(args[9]));
job_start_time = System.currentTimeMillis();
JobClient.runJob(confAggr);
job_end_time = System.currentTimeMillis();
job_runtime = (job_end_time-job_start_time) / 1000;
System.out.println("aggregation runtime (seconds): " +
job_runtime);
return 0;
}
}
| false | true | public int run(String args[]) throws Exception
{
long job_start_time, job_end_time;
long job_runtime;
float epsilon = Float.parseFloat(args[0]);
double delta = Double.parseDouble(args[1]);
int minFreqPercent = Integer.parseInt(args[2]);
int d = Integer.parseInt(args[3]);
int datasetSize = Integer.parseInt(args[4]);
int nodes = Integer.parseInt(args[5]);
/************************ Job 1 (local FIM) Configuration ************************/
JobConf conf = new JobConf(getConf());
int numSamples = (int) Math.floor(0.95 * nodes * conf.getInt("mapred.tasktracker.reduce.tasks.maximum", nodes * 2));
double phi = 1 + (2 * Math.log(delta) / numSamples) + Math.sqrt(Math.pow(2 * Math.log(delta) / numSamples , 2) - (6 * Math.log(delta) / numSamples));
// XXX There shouldn't be any problem in doing this, but I want
// to check with Eli. MR
if (phi > 1.0)
{
phi = 1.0;
}
int sampleSize = (int) Math.ceil((2 / Math.pow(epsilon, 2))*(d + Math.log(1/ phi)));
conf.setInt("PARMM.reducersNum", numSamples);
conf.setInt("PARMM.datasetSize", datasetSize);
conf.setInt("PARMM.minFreqPercent", minFreqPercent);
conf.setFloat("PARMM.epsilon", epsilon);
conf.setNumReduceTasks(numSamples);
conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
conf.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI);
conf.setJarByClass(MRDriver.class);
conf.setMapOutputKeyClass(IntWritable.class);
conf.setMapOutputValueClass(Text.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(DoubleWritable.class);
conf.setInputFormat(SequenceFileInputFormat.class);
SequenceFileInputFormat.addInputPath(conf, new Path(args[7]));
conf.setOutputFormat(SequenceFileOutputFormat.class);
SequenceFileOutputFormat.setOutputPath(conf, new Path(args[8]));
// set the mapper class based on command line option
if(args[6].equals("1"))
{
System.out.println("running partition mapper...");
conf.setMapperClass(PartitionMapper.class);
}
else if(args[6].equals("2"))
{
System.out.println("running binomial mapper...");
conf.setMapperClass(BinomialSamplerMapper.class);
}
else if(args[6].equals("3"))
{
System.out.println("running coin mapper...");
conf.setMapperClass(CoinFlipSamplerMapper.class);
}
else if(args[6].equals("4"))
{
System.out.println("running sampler mapper...");
conf.setMapperClass(InputSamplerMapper.class);
// create a random sample of size T*m
Random rand = new Random();
int[] samples = new int[numSamples * sampleSize];
for (int i = 0; i < numSamples * sampleSize; i++)
{
samples[i] = rand.nextInt(datasetSize);
}
// for each key in the sample, create a list of all T samples to which this key belongs
// XXX I wonder whether we could more efficiently create
// the MapWritable directly. MR
Hashtable<LongWritable, ArrayList<IntWritable>> hashTable = new Hashtable<LongWritable, ArrayList<IntWritable>>();
for (int i=0; i < numSamples * sampleSize; i++)
{
ArrayList<IntWritable> sampleIDs = null;
LongWritable key = new LongWritable(samples[i]);
if (hashTable.contains(key))
sampleIDs = hashTable.get(key);
else
sampleIDs = new ArrayList<IntWritable>();
sampleIDs.add(new IntWritable(i / sampleSize));
hashTable.put(key, sampleIDs);
}
MapWritable map = new MapWritable();
for (LongWritable key : hashTable.keySet())
{
ArrayList<IntWritable> sampleIDs = hashTable.get(key);
IntArrayWritable sampleIDsIAW = new IntArrayWritable();
sampleIDsIAW.set(sampleIDs.toArray(new IntWritable[1]));
map.put(key, sampleIDsIAW);
}
FileSystem fs = FileSystem.get(URI.create("samplesMap.ser"), conf);
FSDataOutputStream out = fs.create(new Path("samplesMap.ser"), true);
map.write(out);
out.sync();
out.close();
DistributedCache.addCacheFile(new URI(fs.getWorkingDirectory() + "/samplesMap.ser#samplesMap.ser"), conf);
}
else
{
// NOT REACHED
}
// XXX Why is it necessary to change the default hash partitioner? JD
conf.setPartitionerClass(FIMPartitioner.class);
conf.setReducerClass(FIMReducer.class);
job_start_time = System.currentTimeMillis();
JobClient.runJob(conf);
job_end_time = System.currentTimeMillis();
job_runtime = (job_end_time-job_start_time) / 1000;
System.out.println("local FIM runtime (seconds): " + job_runtime);
/************************ Job 2 (aggregation) Configuration ************************/
JobConf confAggr = new JobConf(getConf());
confAggr.setInt("PARMM.reducersNum", numSamples);
confAggr.setFloat("PARMM.epsilon", epsilon);
confAggr.setBoolean("mapred.reduce.tasks.speculative.execution", false);
confAggr.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI);
confAggr.setJarByClass(MRDriver.class);
confAggr.setMapOutputKeyClass(Text.class);
confAggr.setMapOutputValueClass(DoubleWritable.class);
confAggr.setOutputKeyClass(Text.class);
confAggr.setOutputValueClass(Text.class);
confAggr.setMapperClass(IdentityMapper.class);
confAggr.setReducerClass(AggregateReducer.class);
confAggr.setInputFormat(SequenceFileInputFormat.class);
SequenceFileInputFormat.addInputPath(confAggr, new Path(args[8]));
FileOutputFormat.setOutputPath(confAggr, new Path(args[9]));
job_start_time = System.currentTimeMillis();
JobClient.runJob(confAggr);
job_end_time = System.currentTimeMillis();
job_runtime = (job_end_time-job_start_time) / 1000;
System.out.println("aggregation runtime (seconds): " +
job_runtime);
return 0;
}
| public int run(String args[]) throws Exception
{
long job_start_time, job_end_time;
long job_runtime;
float epsilon = Float.parseFloat(args[0]);
double delta = Double.parseDouble(args[1]);
int minFreqPercent = Integer.parseInt(args[2]);
int d = Integer.parseInt(args[3]);
int datasetSize = Integer.parseInt(args[4]);
int nodes = Integer.parseInt(args[5]);
/************************ Job 1 (local FIM) Configuration ************************/
JobConf conf = new JobConf(getConf());
int numSamples = (int) Math.floor(0.95 * nodes * conf.getInt("mapred.tasktracker.reduce.tasks.maximum", nodes * 2));
double phi = 1 + (2 * Math.log(delta) / numSamples) + Math.sqrt(Math.pow(2 * Math.log(delta) / numSamples , 2) - (2 * Math.log(delta) / numSamples));
if (phi > 1.0)
{
phi = 1.0 - 0.000001;
}
int sampleSize = (int) Math.ceil((2 / Math.pow(epsilon, 2))*(d + Math.log(1/ phi)));
conf.setInt("PARMM.reducersNum", numSamples);
conf.setInt("PARMM.datasetSize", datasetSize);
conf.setInt("PARMM.minFreqPercent", minFreqPercent);
conf.setFloat("PARMM.epsilon", epsilon);
conf.setNumReduceTasks(numSamples);
conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
conf.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI);
conf.setJarByClass(MRDriver.class);
conf.setMapOutputKeyClass(IntWritable.class);
conf.setMapOutputValueClass(Text.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(DoubleWritable.class);
conf.setInputFormat(SequenceFileInputFormat.class);
SequenceFileInputFormat.addInputPath(conf, new Path(args[7]));
conf.setOutputFormat(SequenceFileOutputFormat.class);
SequenceFileOutputFormat.setOutputPath(conf, new Path(args[8]));
// set the mapper class based on command line option
if(args[6].equals("1"))
{
System.out.println("running partition mapper...");
conf.setMapperClass(PartitionMapper.class);
}
else if(args[6].equals("2"))
{
System.out.println("running binomial mapper...");
conf.setMapperClass(BinomialSamplerMapper.class);
}
else if(args[6].equals("3"))
{
System.out.println("running coin mapper...");
conf.setMapperClass(CoinFlipSamplerMapper.class);
}
else if(args[6].equals("4"))
{
System.out.println("running sampler mapper...");
conf.setMapperClass(InputSamplerMapper.class);
// create a random sample of size T*m
Random rand = new Random();
int[] samples = new int[numSamples * sampleSize];
for (int i = 0; i < numSamples * sampleSize; i++)
{
samples[i] = rand.nextInt(datasetSize);
}
// for each key in the sample, create a list of all T samples to which this key belongs
// XXX I wonder whether we could more efficiently create
// the MapWritable directly. MR
Hashtable<LongWritable, ArrayList<IntWritable>> hashTable = new Hashtable<LongWritable, ArrayList<IntWritable>>();
for (int i=0; i < numSamples * sampleSize; i++)
{
ArrayList<IntWritable> sampleIDs = null;
LongWritable key = new LongWritable(samples[i]);
if (hashTable.contains(key))
sampleIDs = hashTable.get(key);
else
sampleIDs = new ArrayList<IntWritable>();
sampleIDs.add(new IntWritable(i / sampleSize));
hashTable.put(key, sampleIDs);
}
MapWritable map = new MapWritable();
for (LongWritable key : hashTable.keySet())
{
ArrayList<IntWritable> sampleIDs = hashTable.get(key);
IntArrayWritable sampleIDsIAW = new IntArrayWritable();
sampleIDsIAW.set(sampleIDs.toArray(new IntWritable[1]));
map.put(key, sampleIDsIAW);
}
FileSystem fs = FileSystem.get(URI.create("samplesMap.ser"), conf);
FSDataOutputStream out = fs.create(new Path("samplesMap.ser"), true);
map.write(out);
out.sync();
out.close();
DistributedCache.addCacheFile(new URI(fs.getWorkingDirectory() + "/samplesMap.ser#samplesMap.ser"), conf);
}
else
{
// NOT REACHED
}
// XXX Why is it necessary to change the default hash partitioner? JD
conf.setPartitionerClass(FIMPartitioner.class);
conf.setReducerClass(FIMReducer.class);
job_start_time = System.currentTimeMillis();
JobClient.runJob(conf);
job_end_time = System.currentTimeMillis();
job_runtime = (job_end_time-job_start_time) / 1000;
System.out.println("local FIM runtime (seconds): " + job_runtime);
/************************ Job 2 (aggregation) Configuration ************************/
JobConf confAggr = new JobConf(getConf());
confAggr.setInt("PARMM.reducersNum", numSamples);
confAggr.setFloat("PARMM.epsilon", epsilon);
confAggr.setBoolean("mapred.reduce.tasks.speculative.execution", false);
confAggr.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI);
confAggr.setJarByClass(MRDriver.class);
confAggr.setMapOutputKeyClass(Text.class);
confAggr.setMapOutputValueClass(DoubleWritable.class);
confAggr.setOutputKeyClass(Text.class);
confAggr.setOutputValueClass(Text.class);
confAggr.setMapperClass(IdentityMapper.class);
confAggr.setReducerClass(AggregateReducer.class);
confAggr.setInputFormat(SequenceFileInputFormat.class);
SequenceFileInputFormat.addInputPath(confAggr, new Path(args[8]));
FileOutputFormat.setOutputPath(confAggr, new Path(args[9]));
job_start_time = System.currentTimeMillis();
JobClient.runJob(confAggr);
job_end_time = System.currentTimeMillis();
job_runtime = (job_end_time-job_start_time) / 1000;
System.out.println("aggregation runtime (seconds): " +
job_runtime);
return 0;
}
|
diff --git a/cyni-impl/src/main/java/org/cytoscape/cyni/internal/inductionAlgorithms/HillClimbingAlgorithm/HillClimbingInductionTask.java b/cyni-impl/src/main/java/org/cytoscape/cyni/internal/inductionAlgorithms/HillClimbingAlgorithm/HillClimbingInductionTask.java
index 2f4bc89..e94836a 100644
--- a/cyni-impl/src/main/java/org/cytoscape/cyni/internal/inductionAlgorithms/HillClimbingAlgorithm/HillClimbingInductionTask.java
+++ b/cyni-impl/src/main/java/org/cytoscape/cyni/internal/inductionAlgorithms/HillClimbingAlgorithm/HillClimbingInductionTask.java
@@ -1,703 +1,705 @@
/*
* #%L
* Cyni Implementation (cyni-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* 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 2.1 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
package org.cytoscape.cyni.internal.inductionAlgorithms.HillClimbingAlgorithm;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyNetworkTableManager;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyRow;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.cyni.*;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.view.model.CyNetworkViewManager;
/**
* The BasicInduction provides a very simple Induction, suitable as
* the default Induction for Cytoscape data readers.
*/
public class HillClimbingInductionTask extends AbstractCyniTask {
private final int maxNumParents;
private final List<String> attributeArray;
private final CyTable table;
private CyLayoutAlgorithmManager layoutManager;
private CyCyniMetricsManager metricsManager;
private Map<Integer, CyNode> mapIndexNode;
private Map<CyNode, Integer> mapNodeIndex;
private boolean useNetworkAsInitialSearch;
private boolean edgesBlocked;
private boolean reversalOption;
private Map<CyNode, CyNode> orig2NewNodeMap;
private Map<CyNode, CyNode> new2OrigNodeMap;
private Operation [] [] scoreOperations;
private boolean [] [] nodeAscendantsReach;
private boolean [] [] nodeParentsMatrix;
private boolean [] [] edgeBlocked;
private CyCyniMetric selectedMetric;
private boolean removeNodes;
private TreeSet<Operation> scoreTree;
/**
* Creates a new BasicInduction object.
*/
public HillClimbingInductionTask(final String name, final HillClimbingInductionContext context, CyNetworkFactory networkFactory, CyNetworkViewFactory networkViewFactory,
CyNetworkManager networkManager,CyNetworkTableManager netTableMgr, CyRootNetworkManager rootNetMgr, VisualMappingManager vmMgr,
CyNetworkViewManager networkViewManager,CyLayoutAlgorithmManager layoutManager,
CyCyniMetricsManager metricsManager, CyTable selectedTable)
{
super(name, context,networkFactory,networkViewFactory,networkManager, networkViewManager,netTableMgr,rootNetMgr,vmMgr);
this.maxNumParents = context.maxNumParents;
this.layoutManager = layoutManager;
this.metricsManager = metricsManager;
this.attributeArray = context.attributeList.getSelectedValues();
this.table = selectedTable;
this.selectedMetric = context.measures.getSelectedValue();
this.useNetworkAsInitialSearch = context.useNetworkAsInitialSearch;
this.reversalOption = context.reversalOption;
this.removeNodes = context.removeNodes;
this.edgesBlocked = context.edgesBlocked;
mapNodeIndex = new HashMap< CyNode, Integer>();
mapIndexNode = new HashMap<Integer, CyNode>();
orig2NewNodeMap = new WeakHashMap<CyNode, CyNode>();
new2OrigNodeMap = new WeakHashMap<CyNode, CyNode>();
nodeParents = new HashMap<Integer, ArrayList<Integer>>();
}
/**
* Perform actual Induction task.
* This creates the default square Induction.
*/
@Override
final protected void doCyniTask(final TaskMonitor taskMonitor) {
String networkName;
Integer numNodes = 1;
CyTable nodeTable, edgeTable;
CyEdge edge;
CyNode newNode;
CyLayoutAlgorithm layout;
Double progress = 0.0d;
Double step = 0.0;
int i=0;
int nRows,added,removed,reversed;
CyNetwork newNetwork = netFactory.createNetwork();
CyNetworkView newNetworkView ;
CyNetwork networkSelected = null;
boolean okToProceed = true;
Operation operationAdd = new Operation("Add");
Operation operationDelete = new Operation("Delete");
Operation operationReverse = new Operation("Reverse");
Operation chosenOperation;
networkSelected = getNetworkAssociatedToTable(table);
taskMonitor.setTitle("Hill Climbing inference");
taskMonitor.setStatusMessage("Generating Hill Climbing inference...");
taskMonitor.setProgress(progress);
networkName = "HC Inference " + newNetwork.getSUID();
if (newNetwork != null && networkName != null) {
CyRow netRow = newNetwork.getRow(newNetwork);
netRow.set(CyNetwork.NAME, networkName);
}
addColumns(networkSelected,newNetwork,table,CyNode.class, CyNetwork.LOCAL_ATTRS);
for (CyRow origRow : table.getAllRows()) {
if(selectedOnly)
{
if(networkSelected != null && !origRow.get(CyNetwork.SELECTED, Boolean.class))
continue;
}
newNode = newNetwork.addNode();
if(networkSelected != null)
{
orig2NewNodeMap.put(networkSelected.getNode(origRow.get(CyNetwork.SUID,Long.class)), newNode);
new2OrigNodeMap.put(newNode, networkSelected.getNode(origRow.get(CyNetwork.SUID,Long.class)));
}
cloneRow(newNetwork, CyNode.class,origRow, newNetwork.getRow(newNode, CyNetwork.LOCAL_ATTRS));
if(!origRow.isSet(CyNetwork.NAME))
newNetwork.getRow(newNode).set(CyNetwork.NAME, "Node " + numNodes);
numNodes++;
}
nodeTable = newNetwork.getDefaultNodeTable();
edgeTable = newNetwork.getDefaultEdgeTable();
// Create the CyniTable
CyniTable data = new CyniTable(nodeTable,attributeArray.toArray(new String[0]), false, false, selectedOnly);
if(data.hasAnyMissingValue())
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected contains missing values.\n " +
"Therefore, this algorithm can not proceed with these conditions.", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
nRows = data.nRows();
step = 1.0 / nRows;
progress = progress + step;
taskMonitor.setProgress(progress);
for (i = 0; i< nRows;i++){
nodeParents.put(i, new ArrayList<Integer>());
/*if(!data.rowHasMissingValue(i))
{*/
mapNodeIndex.put( newNetwork.getNode(nodeTable.getRow(data.getRowLabel(i)).get(CyNetwork.SUID, Long.class)) ,i);
mapIndexNode.put( i, newNetwork.getNode(nodeTable.getRow(data.getRowLabel(i)).get(CyNetwork.SUID, Long.class)));
//}
}
scoreTree = new TreeSet<Operation>( new Comparator<Operation>() {
public int compare(Operation op1, Operation op2) {
if(op1.score > op2.score)
return -1;
if(op1.score < op2.score)
return 1;
if(op1.nodeChild > op2.nodeChild)
return -1;
if(op1.nodeChild < op2.nodeChild)
return 1;
if(op1.nodeParent > op2.nodeParent)
return -1;
if(op1.nodeParent < op2.nodeParent)
return 1;
return 0;
}
});
edgeBlocked = new boolean [nRows][nRows];
nodeParentsMatrix = new boolean [nRows][nRows];
nodeAscendantsReach = new boolean [nRows][nRows];
if(networkSelected != null && useNetworkAsInitialSearch)
{
addColumns(networkSelected,newNetwork,table,CyEdge.class, CyNetwork.LOCAL_ATTRS);
for (final CyEdge origEdge : networkSelected.getEdgeList()) {
final CyNode newSource = orig2NewNodeMap.get(origEdge.getSource());
final CyNode newTarget = orig2NewNodeMap.get(origEdge.getTarget());
if(newSource != null && newTarget != null)
{
final boolean newDirected = origEdge.isDirected();
final CyEdge newEdge = newNetwork.addEdge(newSource, newTarget, newDirected);
cloneRow(newNetwork, CyEdge.class, networkSelected.getRow(origEdge, CyNetwork.LOCAL_ATTRS), newNetwork.getRow(newEdge, CyNetwork.LOCAL_ATTRS));
if(edgesBlocked)
{
if(networkSelected.getRow(origEdge, CyNetwork.LOCAL_ATTRS).get(CyNetwork.SELECTED, Boolean.class))
edgeBlocked[mapNodeIndex.get(newSource)][mapNodeIndex.get(newTarget)] = true;
}
if(!newDirected )
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected belongs to a network that is not directed.\n " +
"Therefore, this algorithm is not able to proceed with parameters requested", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
}
}
initParentsMap(newNetwork);
for ( i=0;i<nRows;i++)
{
updateAscendantsOfNode(i);
}
for ( i = 0; i< nRows; i++) {
if(isGraphCyclic( i))
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected belongs to a network that is not acyclic.\n " +
"This algorithm is a bayesian network algorithm and requires a Directed Acyclic Graph(DAG) to perform", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
}
}
scoreOperations = new Operation [nRows][nRows];
selectedMetric.resetParameters();
taskMonitor.setStatusMessage("Initializing Cache..." );
initCache(data, selectedMetric, taskMonitor);
taskMonitor.setStatusMessage("Cache Initialized\n Looking for optimal solution..." );
- edgeTable.createColumn("Probability", Double.class, false);
+ edgeTable.createColumn("Score", Double.class, false);
progress += 0.5;
added = 0;
removed = 0;
reversed = 0;
while(okToProceed)
{
operationAdd.resetParameters();
operationDelete.resetParameters();
operationReverse.resetParameters();
taskMonitor.setStatusMessage("Cache Initialized\nLooking for optimal solution by performing the following operations:\n" +
"Added edges: " + added + "\nRemoved edges: " + removed + "\nReversed edges: " + reversed );
chosenOperation=findBestOperation(data, operationAdd);
if(reversalOption)
findBestReverseEdge(data, operationReverse);
if (cancelled)
break;
if(reversalOption)
{
if(operationReverse.score > chosenOperation.score)
{
chosenOperation = operationReverse;
}
}
if(chosenOperation.score > 0.0)
{
if(chosenOperation.type == "Add")
{
edge = newNetwork.addEdge( mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), true);
newNetwork.getRow(edge).set("name", newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeParent)).get("name", String.class)
+ " (HC) " + newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeChild)).get("name", String.class));
nodeParents.get(chosenOperation.nodeChild).add(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = true;
updateCache(data, selectedMetric,chosenOperation.nodeChild);
updateAscendantsAfterAdd(chosenOperation.nodeParent,chosenOperation.nodeChild);
added++;
+ newNetwork.getRow(edge).set("Score", chosenOperation.score);
}
if(chosenOperation.type == "Delete")
{
newNetwork.removeEdges(newNetwork.getConnectingEdgeList(mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), CyEdge.Type.DIRECTED));
nodeParents.get(chosenOperation.nodeChild).remove(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = false;
updateCache(data, selectedMetric,chosenOperation.nodeChild);
updateAscendantsAfterDelete(chosenOperation.nodeParent,chosenOperation.nodeChild);
removed++;
}
if(chosenOperation.type == "Reverse")
{
newNetwork.removeEdges(newNetwork.getConnectingEdgeList(mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), CyEdge.Type.DIRECTED));
edge = newNetwork.addEdge( mapIndexNode.get(chosenOperation.nodeChild), mapIndexNode.get(chosenOperation.nodeParent), true);
newNetwork.getRow(edge).set("name", newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeChild)).get("name", String.class)
+ " (HC) " + newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeParent)).get("name", String.class));
nodeParents.get(chosenOperation.nodeChild).remove(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = false;
updateAscendantsAfterDelete(chosenOperation.nodeParent,chosenOperation.nodeChild);
updateCache(data, selectedMetric,chosenOperation.nodeChild);
nodeParents.get(chosenOperation.nodeParent).add(Integer.valueOf(chosenOperation.nodeChild));
nodeParentsMatrix[chosenOperation.nodeParent][chosenOperation.nodeChild] = true;
updateCache(data, selectedMetric,chosenOperation.nodeParent);
updateAscendantsAfterAdd(chosenOperation.nodeChild,chosenOperation.nodeParent);
reversed++;
- }
+ newNetwork.getRow(edge).set("Score", chosenOperation.score);
+ }
}
else
okToProceed = false;
progress = progress + step;
taskMonitor.setProgress(progress);
}
scoreTree.clear();
if (!cancelled)
{
if(removeNodes)
removeNodesWithoutEdges(newNetwork);
newNetworkView = displayNewNetwork(newNetwork,networkSelected, true);
taskMonitor.setProgress(1.0d);
layout = layoutManager.getDefaultLayout();
Object context = layout.getDefaultLayoutContext();
insertTasksAfterCurrentTask(layout.createTaskIterator(newNetworkView, context, CyLayoutAlgorithm.ALL_NODE_VIEWS,""));
}
}
/*
* Initialize the list of parents and the parents matrix for each node. The parents matrix is the fast way to know if
* a node is a parent of another node
*/
private void initParentsMap(CyNetwork network)
{
for ( CyEdge edge : network.getEdgeList()) {
nodeParents.get(mapNodeIndex.get(edge.getTarget())).add(Integer.valueOf(mapNodeIndex.get(edge.getSource())));
nodeParentsMatrix[mapNodeIndex.get(edge.getTarget())][mapNodeIndex.get(edge.getSource())] = true;
}
}
/*
* Update the matrix that allows to know for each node which other nodes are its ascendants
*/
private void updateAscendantsOfNode(int nodeToUpdate )
{
ArrayList<Integer> ascendantsList = new ArrayList<Integer>(nodeParents.size());
int pos = -1;
boolean [] nodeCheckList = new boolean [nodeParents.size()];
int nodeToCheck = nodeToUpdate;
nodeCheckList[nodeToUpdate] = true;
while(pos != ascendantsList.size())
{
for(int node : nodeParents.get(nodeToCheck))
{
nodeAscendantsReach[nodeToUpdate][node] = true;
if(!nodeCheckList[node])
{
ascendantsList.add(node);
nodeCheckList[node] = true;
}
}
pos++;
if(pos < ascendantsList.size())
nodeToCheck = ascendantsList.get(pos);
}
}
/*
* Update the ascendants matrix after adding a new edge
*/
private void updateAscendantsAfterAdd(int parent , int child)
{
ArrayList<Integer> parentsList = new ArrayList<Integer>();
ArrayList<Integer> childsList = new ArrayList<Integer>();
int i;
for(i=0;i<nodeParents.size();i++)
{
if(nodeAscendantsReach[i][child])
childsList.add(i);
if(nodeAscendantsReach[parent][i])
parentsList.add(i);
}
parentsList.add(parent);
childsList.add(child);
for(int c: childsList)
{
for(int p: parentsList)
{
nodeAscendantsReach[c][p] = true;
}
}
}
/*
* Update the ascendants matrix after deleting an existing edge
*/
private void updateAscendantsAfterDelete(int parent , int child)
{
ArrayList<Integer> childsList = new ArrayList<Integer>();
int i;
for(i=0;i<nodeParents.size();i++)
{
if(nodeAscendantsReach[i][child])
childsList.add(i);
}
childsList.add(child);
for(int c: childsList)
{
updateAscendantsOfNode(c);
}
}
private void initCache(CyniTable data, CyCyniMetric metric, TaskMonitor taskMonitor)
{
double[] baseScores = new double[data.nRows()];
int nRows = data.nRows();
int nodeIndex,i;
Double progress = 0.0d;
Double step = 0.0;
ArrayList<Integer> parents = new ArrayList<Integer>();
// Create the thread pools
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
step = 1.0 / (nRows*2.0);
for(i = 0;i<nRows;i++) {
nodeIndex =i;
parents.clear();
if(nodeParents.get(nodeIndex).size() > 0)
parents.addAll(nodeParents.get(nodeIndex));
else
parents.add(nodeIndex);
baseScores[nodeIndex] = metric.getMetric(data, data, nodeIndex,parents);
}
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
for (int nodeEnd = 0; nodeEnd < nRows; nodeEnd++)
{
if (nodeStart != nodeEnd)
{
executor.execute(new ThreadedGetMetric(data,nodeStart,nodeEnd,baseScores[nodeEnd]));
}
}
executor.shutdown();
// Wait until all threads are finish
try {
executor.awaitTermination(7, TimeUnit.DAYS);
} catch (Exception e) {}
executor = Executors.newFixedThreadPool(nThreads);
progress = progress + step;
taskMonitor.setProgress(progress);
}
}
private void updateCache(CyniTable data, CyCyniMetric metric, int nodeEnd)
{
int nRows = data.nRows();
ArrayList<Integer> parents = new ArrayList<Integer>();
double baseScore ;
// Create the thread pools
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
if(nodeParents.get(nodeEnd).size() > 0)
parents.addAll(nodeParents.get(nodeEnd));
else
parents.add(nodeEnd);
baseScore = metric.getMetric(data, data, nodeEnd, parents);
removeElements(nodeEnd,nRows);
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
if (nodeStart != nodeEnd) {
executor.execute(new ThreadedGetMetric(data,nodeStart,nodeEnd,baseScore));
}
}
executor.shutdown();
// Wait until all threads are finish
try {
executor.awaitTermination(7, TimeUnit.DAYS);
} catch (Exception e) {}
}
private Operation findBestOperation(CyniTable data, Operation operation)
{
boolean notFound = true;
ArrayList<Operation> opList = new ArrayList<Operation>();
Operation opTemp = new Operation();
while(notFound)
{
opTemp = scoreTree.pollFirst();
opList.add(opTemp);
if(opTemp.type == "Add")
{
if (nodeParents.get(opTemp.nodeChild).size() <= maxNumParents && !nodeAscendantsReach[opTemp.nodeParent][opTemp.nodeChild])
{
operation = opTemp;
notFound = false;
}
}
if(opTemp.type == "Delete")
{
if(!edgeBlocked[opTemp.nodeParent][opTemp.nodeChild])
{
operation = opTemp;
notFound = false;
}
}
}
scoreTree.addAll(opList);
return opTemp;
}
private void removeElements(int nodeEnd, int nRows)
{
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
if (nodeStart != nodeEnd)
scoreTree.remove(scoreOperations[nodeStart][nodeEnd]);
}
}
@SuppressWarnings("unchecked")
private void findBestReverseEdge(CyniTable data, Operation operation)
{
int nRows = data.nRows();
int nodeParent;
ArrayList<Integer> tempList;
for (int nodeChild = 0; nodeChild < nRows; nodeChild++) {
tempList = (ArrayList<Integer>)nodeParents.get(nodeChild).clone();
for (Iterator<Integer> it = tempList.iterator(); it.hasNext();) {
nodeParent = it.next();
if((scoreOperations[nodeParent][nodeChild].score + scoreOperations[nodeChild][nodeParent].score) > operation.score)
{
nodeParents.get(nodeChild).remove(Integer.valueOf(nodeParent));
nodeParents.get(nodeParent).add(Integer.valueOf(nodeChild));
if(!isGraphCyclic( nodeParent) )
{
operation.score = scoreOperations[nodeParent][nodeChild].score + scoreOperations[nodeChild][nodeParent].score;
operation.nodeParent = nodeParent;
operation.nodeChild = nodeChild;
}
nodeParents.get(nodeParent).remove(Integer.valueOf(nodeChild));
nodeParents.get(nodeChild).add(Integer.valueOf(nodeParent));
}
}
}
}
class Operation{
public Operation()
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
}
public Operation(String type)
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
this.type = type;
}
public int nodeParent;
public int nodeChild;
public double score;
public String type;
public void resetParameters()
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
}
}
private class ThreadedGetMetric implements Runnable {
private int nodeStart, nodeEnd;
private double baseScore;
private CyniTable tableData;
private ArrayList<Integer> parents = new ArrayList<Integer>();
ThreadedGetMetric(CyniTable data,int nodeStart, int nodeEnd, double baseScore)
{
this.nodeStart = nodeStart;
this.nodeEnd = nodeEnd;
this.tableData = data;
this.baseScore = baseScore;
}
public void run() {
if(!nodeParentsMatrix[nodeEnd][nodeStart])
{
if (nodeParents.get(nodeEnd).size() < maxNumParents)
{
Operation op = new Operation ("Add");
parents.addAll(nodeParents.get(nodeEnd));
parents.add(nodeStart);
op.score = selectedMetric.getMetric(tableData, tableData, nodeEnd, parents) - baseScore;
op.nodeChild = nodeEnd;
op.nodeParent = nodeStart;
scoreOperations[nodeStart][nodeEnd] = op;
synchronized (scoreTree){
scoreTree.add(op);
}
}
}
else
{
if(nodeParents.get(nodeEnd).size() > 0)
{
parents.addAll(nodeParents.get(nodeEnd));
parents.remove(Integer.valueOf(nodeStart));
}
if(parents.size() == 0)
parents.add(nodeEnd);
Operation op = new Operation ("Delete");
op.score = selectedMetric.getMetric(tableData, tableData, nodeEnd, parents) - baseScore;
op.nodeChild = nodeEnd;
op.nodeParent = nodeStart;
scoreOperations[nodeStart][nodeEnd] = op;
synchronized (scoreTree){
scoreTree.add(op);
}
}
parents.clear();
}
}
}
| false | true | final protected void doCyniTask(final TaskMonitor taskMonitor) {
String networkName;
Integer numNodes = 1;
CyTable nodeTable, edgeTable;
CyEdge edge;
CyNode newNode;
CyLayoutAlgorithm layout;
Double progress = 0.0d;
Double step = 0.0;
int i=0;
int nRows,added,removed,reversed;
CyNetwork newNetwork = netFactory.createNetwork();
CyNetworkView newNetworkView ;
CyNetwork networkSelected = null;
boolean okToProceed = true;
Operation operationAdd = new Operation("Add");
Operation operationDelete = new Operation("Delete");
Operation operationReverse = new Operation("Reverse");
Operation chosenOperation;
networkSelected = getNetworkAssociatedToTable(table);
taskMonitor.setTitle("Hill Climbing inference");
taskMonitor.setStatusMessage("Generating Hill Climbing inference...");
taskMonitor.setProgress(progress);
networkName = "HC Inference " + newNetwork.getSUID();
if (newNetwork != null && networkName != null) {
CyRow netRow = newNetwork.getRow(newNetwork);
netRow.set(CyNetwork.NAME, networkName);
}
addColumns(networkSelected,newNetwork,table,CyNode.class, CyNetwork.LOCAL_ATTRS);
for (CyRow origRow : table.getAllRows()) {
if(selectedOnly)
{
if(networkSelected != null && !origRow.get(CyNetwork.SELECTED, Boolean.class))
continue;
}
newNode = newNetwork.addNode();
if(networkSelected != null)
{
orig2NewNodeMap.put(networkSelected.getNode(origRow.get(CyNetwork.SUID,Long.class)), newNode);
new2OrigNodeMap.put(newNode, networkSelected.getNode(origRow.get(CyNetwork.SUID,Long.class)));
}
cloneRow(newNetwork, CyNode.class,origRow, newNetwork.getRow(newNode, CyNetwork.LOCAL_ATTRS));
if(!origRow.isSet(CyNetwork.NAME))
newNetwork.getRow(newNode).set(CyNetwork.NAME, "Node " + numNodes);
numNodes++;
}
nodeTable = newNetwork.getDefaultNodeTable();
edgeTable = newNetwork.getDefaultEdgeTable();
// Create the CyniTable
CyniTable data = new CyniTable(nodeTable,attributeArray.toArray(new String[0]), false, false, selectedOnly);
if(data.hasAnyMissingValue())
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected contains missing values.\n " +
"Therefore, this algorithm can not proceed with these conditions.", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
nRows = data.nRows();
step = 1.0 / nRows;
progress = progress + step;
taskMonitor.setProgress(progress);
for (i = 0; i< nRows;i++){
nodeParents.put(i, new ArrayList<Integer>());
/*if(!data.rowHasMissingValue(i))
{*/
mapNodeIndex.put( newNetwork.getNode(nodeTable.getRow(data.getRowLabel(i)).get(CyNetwork.SUID, Long.class)) ,i);
mapIndexNode.put( i, newNetwork.getNode(nodeTable.getRow(data.getRowLabel(i)).get(CyNetwork.SUID, Long.class)));
//}
}
scoreTree = new TreeSet<Operation>( new Comparator<Operation>() {
public int compare(Operation op1, Operation op2) {
if(op1.score > op2.score)
return -1;
if(op1.score < op2.score)
return 1;
if(op1.nodeChild > op2.nodeChild)
return -1;
if(op1.nodeChild < op2.nodeChild)
return 1;
if(op1.nodeParent > op2.nodeParent)
return -1;
if(op1.nodeParent < op2.nodeParent)
return 1;
return 0;
}
});
edgeBlocked = new boolean [nRows][nRows];
nodeParentsMatrix = new boolean [nRows][nRows];
nodeAscendantsReach = new boolean [nRows][nRows];
if(networkSelected != null && useNetworkAsInitialSearch)
{
addColumns(networkSelected,newNetwork,table,CyEdge.class, CyNetwork.LOCAL_ATTRS);
for (final CyEdge origEdge : networkSelected.getEdgeList()) {
final CyNode newSource = orig2NewNodeMap.get(origEdge.getSource());
final CyNode newTarget = orig2NewNodeMap.get(origEdge.getTarget());
if(newSource != null && newTarget != null)
{
final boolean newDirected = origEdge.isDirected();
final CyEdge newEdge = newNetwork.addEdge(newSource, newTarget, newDirected);
cloneRow(newNetwork, CyEdge.class, networkSelected.getRow(origEdge, CyNetwork.LOCAL_ATTRS), newNetwork.getRow(newEdge, CyNetwork.LOCAL_ATTRS));
if(edgesBlocked)
{
if(networkSelected.getRow(origEdge, CyNetwork.LOCAL_ATTRS).get(CyNetwork.SELECTED, Boolean.class))
edgeBlocked[mapNodeIndex.get(newSource)][mapNodeIndex.get(newTarget)] = true;
}
if(!newDirected )
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected belongs to a network that is not directed.\n " +
"Therefore, this algorithm is not able to proceed with parameters requested", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
}
}
initParentsMap(newNetwork);
for ( i=0;i<nRows;i++)
{
updateAscendantsOfNode(i);
}
for ( i = 0; i< nRows; i++) {
if(isGraphCyclic( i))
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected belongs to a network that is not acyclic.\n " +
"This algorithm is a bayesian network algorithm and requires a Directed Acyclic Graph(DAG) to perform", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
}
}
scoreOperations = new Operation [nRows][nRows];
selectedMetric.resetParameters();
taskMonitor.setStatusMessage("Initializing Cache..." );
initCache(data, selectedMetric, taskMonitor);
taskMonitor.setStatusMessage("Cache Initialized\n Looking for optimal solution..." );
edgeTable.createColumn("Probability", Double.class, false);
progress += 0.5;
added = 0;
removed = 0;
reversed = 0;
while(okToProceed)
{
operationAdd.resetParameters();
operationDelete.resetParameters();
operationReverse.resetParameters();
taskMonitor.setStatusMessage("Cache Initialized\nLooking for optimal solution by performing the following operations:\n" +
"Added edges: " + added + "\nRemoved edges: " + removed + "\nReversed edges: " + reversed );
chosenOperation=findBestOperation(data, operationAdd);
if(reversalOption)
findBestReverseEdge(data, operationReverse);
if (cancelled)
break;
if(reversalOption)
{
if(operationReverse.score > chosenOperation.score)
{
chosenOperation = operationReverse;
}
}
if(chosenOperation.score > 0.0)
{
if(chosenOperation.type == "Add")
{
edge = newNetwork.addEdge( mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), true);
newNetwork.getRow(edge).set("name", newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeParent)).get("name", String.class)
+ " (HC) " + newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeChild)).get("name", String.class));
nodeParents.get(chosenOperation.nodeChild).add(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = true;
updateCache(data, selectedMetric,chosenOperation.nodeChild);
updateAscendantsAfterAdd(chosenOperation.nodeParent,chosenOperation.nodeChild);
added++;
}
if(chosenOperation.type == "Delete")
{
newNetwork.removeEdges(newNetwork.getConnectingEdgeList(mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), CyEdge.Type.DIRECTED));
nodeParents.get(chosenOperation.nodeChild).remove(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = false;
updateCache(data, selectedMetric,chosenOperation.nodeChild);
updateAscendantsAfterDelete(chosenOperation.nodeParent,chosenOperation.nodeChild);
removed++;
}
if(chosenOperation.type == "Reverse")
{
newNetwork.removeEdges(newNetwork.getConnectingEdgeList(mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), CyEdge.Type.DIRECTED));
edge = newNetwork.addEdge( mapIndexNode.get(chosenOperation.nodeChild), mapIndexNode.get(chosenOperation.nodeParent), true);
newNetwork.getRow(edge).set("name", newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeChild)).get("name", String.class)
+ " (HC) " + newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeParent)).get("name", String.class));
nodeParents.get(chosenOperation.nodeChild).remove(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = false;
updateAscendantsAfterDelete(chosenOperation.nodeParent,chosenOperation.nodeChild);
updateCache(data, selectedMetric,chosenOperation.nodeChild);
nodeParents.get(chosenOperation.nodeParent).add(Integer.valueOf(chosenOperation.nodeChild));
nodeParentsMatrix[chosenOperation.nodeParent][chosenOperation.nodeChild] = true;
updateCache(data, selectedMetric,chosenOperation.nodeParent);
updateAscendantsAfterAdd(chosenOperation.nodeChild,chosenOperation.nodeParent);
reversed++;
}
}
else
okToProceed = false;
progress = progress + step;
taskMonitor.setProgress(progress);
}
scoreTree.clear();
if (!cancelled)
{
if(removeNodes)
removeNodesWithoutEdges(newNetwork);
newNetworkView = displayNewNetwork(newNetwork,networkSelected, true);
taskMonitor.setProgress(1.0d);
layout = layoutManager.getDefaultLayout();
Object context = layout.getDefaultLayoutContext();
insertTasksAfterCurrentTask(layout.createTaskIterator(newNetworkView, context, CyLayoutAlgorithm.ALL_NODE_VIEWS,""));
}
}
/*
* Initialize the list of parents and the parents matrix for each node. The parents matrix is the fast way to know if
* a node is a parent of another node
*/
private void initParentsMap(CyNetwork network)
{
for ( CyEdge edge : network.getEdgeList()) {
nodeParents.get(mapNodeIndex.get(edge.getTarget())).add(Integer.valueOf(mapNodeIndex.get(edge.getSource())));
nodeParentsMatrix[mapNodeIndex.get(edge.getTarget())][mapNodeIndex.get(edge.getSource())] = true;
}
}
/*
* Update the matrix that allows to know for each node which other nodes are its ascendants
*/
private void updateAscendantsOfNode(int nodeToUpdate )
{
ArrayList<Integer> ascendantsList = new ArrayList<Integer>(nodeParents.size());
int pos = -1;
boolean [] nodeCheckList = new boolean [nodeParents.size()];
int nodeToCheck = nodeToUpdate;
nodeCheckList[nodeToUpdate] = true;
while(pos != ascendantsList.size())
{
for(int node : nodeParents.get(nodeToCheck))
{
nodeAscendantsReach[nodeToUpdate][node] = true;
if(!nodeCheckList[node])
{
ascendantsList.add(node);
nodeCheckList[node] = true;
}
}
pos++;
if(pos < ascendantsList.size())
nodeToCheck = ascendantsList.get(pos);
}
}
/*
* Update the ascendants matrix after adding a new edge
*/
private void updateAscendantsAfterAdd(int parent , int child)
{
ArrayList<Integer> parentsList = new ArrayList<Integer>();
ArrayList<Integer> childsList = new ArrayList<Integer>();
int i;
for(i=0;i<nodeParents.size();i++)
{
if(nodeAscendantsReach[i][child])
childsList.add(i);
if(nodeAscendantsReach[parent][i])
parentsList.add(i);
}
parentsList.add(parent);
childsList.add(child);
for(int c: childsList)
{
for(int p: parentsList)
{
nodeAscendantsReach[c][p] = true;
}
}
}
/*
* Update the ascendants matrix after deleting an existing edge
*/
private void updateAscendantsAfterDelete(int parent , int child)
{
ArrayList<Integer> childsList = new ArrayList<Integer>();
int i;
for(i=0;i<nodeParents.size();i++)
{
if(nodeAscendantsReach[i][child])
childsList.add(i);
}
childsList.add(child);
for(int c: childsList)
{
updateAscendantsOfNode(c);
}
}
private void initCache(CyniTable data, CyCyniMetric metric, TaskMonitor taskMonitor)
{
double[] baseScores = new double[data.nRows()];
int nRows = data.nRows();
int nodeIndex,i;
Double progress = 0.0d;
Double step = 0.0;
ArrayList<Integer> parents = new ArrayList<Integer>();
// Create the thread pools
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
step = 1.0 / (nRows*2.0);
for(i = 0;i<nRows;i++) {
nodeIndex =i;
parents.clear();
if(nodeParents.get(nodeIndex).size() > 0)
parents.addAll(nodeParents.get(nodeIndex));
else
parents.add(nodeIndex);
baseScores[nodeIndex] = metric.getMetric(data, data, nodeIndex,parents);
}
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
for (int nodeEnd = 0; nodeEnd < nRows; nodeEnd++)
{
if (nodeStart != nodeEnd)
{
executor.execute(new ThreadedGetMetric(data,nodeStart,nodeEnd,baseScores[nodeEnd]));
}
}
executor.shutdown();
// Wait until all threads are finish
try {
executor.awaitTermination(7, TimeUnit.DAYS);
} catch (Exception e) {}
executor = Executors.newFixedThreadPool(nThreads);
progress = progress + step;
taskMonitor.setProgress(progress);
}
}
private void updateCache(CyniTable data, CyCyniMetric metric, int nodeEnd)
{
int nRows = data.nRows();
ArrayList<Integer> parents = new ArrayList<Integer>();
double baseScore ;
// Create the thread pools
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
if(nodeParents.get(nodeEnd).size() > 0)
parents.addAll(nodeParents.get(nodeEnd));
else
parents.add(nodeEnd);
baseScore = metric.getMetric(data, data, nodeEnd, parents);
removeElements(nodeEnd,nRows);
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
if (nodeStart != nodeEnd) {
executor.execute(new ThreadedGetMetric(data,nodeStart,nodeEnd,baseScore));
}
}
executor.shutdown();
// Wait until all threads are finish
try {
executor.awaitTermination(7, TimeUnit.DAYS);
} catch (Exception e) {}
}
private Operation findBestOperation(CyniTable data, Operation operation)
{
boolean notFound = true;
ArrayList<Operation> opList = new ArrayList<Operation>();
Operation opTemp = new Operation();
while(notFound)
{
opTemp = scoreTree.pollFirst();
opList.add(opTemp);
if(opTemp.type == "Add")
{
if (nodeParents.get(opTemp.nodeChild).size() <= maxNumParents && !nodeAscendantsReach[opTemp.nodeParent][opTemp.nodeChild])
{
operation = opTemp;
notFound = false;
}
}
if(opTemp.type == "Delete")
{
if(!edgeBlocked[opTemp.nodeParent][opTemp.nodeChild])
{
operation = opTemp;
notFound = false;
}
}
}
scoreTree.addAll(opList);
return opTemp;
}
private void removeElements(int nodeEnd, int nRows)
{
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
if (nodeStart != nodeEnd)
scoreTree.remove(scoreOperations[nodeStart][nodeEnd]);
}
}
@SuppressWarnings("unchecked")
private void findBestReverseEdge(CyniTable data, Operation operation)
{
int nRows = data.nRows();
int nodeParent;
ArrayList<Integer> tempList;
for (int nodeChild = 0; nodeChild < nRows; nodeChild++) {
tempList = (ArrayList<Integer>)nodeParents.get(nodeChild).clone();
for (Iterator<Integer> it = tempList.iterator(); it.hasNext();) {
nodeParent = it.next();
if((scoreOperations[nodeParent][nodeChild].score + scoreOperations[nodeChild][nodeParent].score) > operation.score)
{
nodeParents.get(nodeChild).remove(Integer.valueOf(nodeParent));
nodeParents.get(nodeParent).add(Integer.valueOf(nodeChild));
if(!isGraphCyclic( nodeParent) )
{
operation.score = scoreOperations[nodeParent][nodeChild].score + scoreOperations[nodeChild][nodeParent].score;
operation.nodeParent = nodeParent;
operation.nodeChild = nodeChild;
}
nodeParents.get(nodeParent).remove(Integer.valueOf(nodeChild));
nodeParents.get(nodeChild).add(Integer.valueOf(nodeParent));
}
}
}
}
class Operation{
public Operation()
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
}
public Operation(String type)
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
this.type = type;
}
public int nodeParent;
public int nodeChild;
public double score;
public String type;
public void resetParameters()
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
}
}
private class ThreadedGetMetric implements Runnable {
private int nodeStart, nodeEnd;
private double baseScore;
private CyniTable tableData;
private ArrayList<Integer> parents = new ArrayList<Integer>();
ThreadedGetMetric(CyniTable data,int nodeStart, int nodeEnd, double baseScore)
{
this.nodeStart = nodeStart;
this.nodeEnd = nodeEnd;
this.tableData = data;
this.baseScore = baseScore;
}
public void run() {
if(!nodeParentsMatrix[nodeEnd][nodeStart])
{
if (nodeParents.get(nodeEnd).size() < maxNumParents)
{
Operation op = new Operation ("Add");
parents.addAll(nodeParents.get(nodeEnd));
parents.add(nodeStart);
op.score = selectedMetric.getMetric(tableData, tableData, nodeEnd, parents) - baseScore;
op.nodeChild = nodeEnd;
op.nodeParent = nodeStart;
scoreOperations[nodeStart][nodeEnd] = op;
synchronized (scoreTree){
scoreTree.add(op);
}
}
}
else
{
if(nodeParents.get(nodeEnd).size() > 0)
{
parents.addAll(nodeParents.get(nodeEnd));
parents.remove(Integer.valueOf(nodeStart));
}
if(parents.size() == 0)
parents.add(nodeEnd);
Operation op = new Operation ("Delete");
op.score = selectedMetric.getMetric(tableData, tableData, nodeEnd, parents) - baseScore;
op.nodeChild = nodeEnd;
op.nodeParent = nodeStart;
scoreOperations[nodeStart][nodeEnd] = op;
synchronized (scoreTree){
scoreTree.add(op);
}
}
parents.clear();
}
}
}
| final protected void doCyniTask(final TaskMonitor taskMonitor) {
String networkName;
Integer numNodes = 1;
CyTable nodeTable, edgeTable;
CyEdge edge;
CyNode newNode;
CyLayoutAlgorithm layout;
Double progress = 0.0d;
Double step = 0.0;
int i=0;
int nRows,added,removed,reversed;
CyNetwork newNetwork = netFactory.createNetwork();
CyNetworkView newNetworkView ;
CyNetwork networkSelected = null;
boolean okToProceed = true;
Operation operationAdd = new Operation("Add");
Operation operationDelete = new Operation("Delete");
Operation operationReverse = new Operation("Reverse");
Operation chosenOperation;
networkSelected = getNetworkAssociatedToTable(table);
taskMonitor.setTitle("Hill Climbing inference");
taskMonitor.setStatusMessage("Generating Hill Climbing inference...");
taskMonitor.setProgress(progress);
networkName = "HC Inference " + newNetwork.getSUID();
if (newNetwork != null && networkName != null) {
CyRow netRow = newNetwork.getRow(newNetwork);
netRow.set(CyNetwork.NAME, networkName);
}
addColumns(networkSelected,newNetwork,table,CyNode.class, CyNetwork.LOCAL_ATTRS);
for (CyRow origRow : table.getAllRows()) {
if(selectedOnly)
{
if(networkSelected != null && !origRow.get(CyNetwork.SELECTED, Boolean.class))
continue;
}
newNode = newNetwork.addNode();
if(networkSelected != null)
{
orig2NewNodeMap.put(networkSelected.getNode(origRow.get(CyNetwork.SUID,Long.class)), newNode);
new2OrigNodeMap.put(newNode, networkSelected.getNode(origRow.get(CyNetwork.SUID,Long.class)));
}
cloneRow(newNetwork, CyNode.class,origRow, newNetwork.getRow(newNode, CyNetwork.LOCAL_ATTRS));
if(!origRow.isSet(CyNetwork.NAME))
newNetwork.getRow(newNode).set(CyNetwork.NAME, "Node " + numNodes);
numNodes++;
}
nodeTable = newNetwork.getDefaultNodeTable();
edgeTable = newNetwork.getDefaultEdgeTable();
// Create the CyniTable
CyniTable data = new CyniTable(nodeTable,attributeArray.toArray(new String[0]), false, false, selectedOnly);
if(data.hasAnyMissingValue())
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected contains missing values.\n " +
"Therefore, this algorithm can not proceed with these conditions.", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
nRows = data.nRows();
step = 1.0 / nRows;
progress = progress + step;
taskMonitor.setProgress(progress);
for (i = 0; i< nRows;i++){
nodeParents.put(i, new ArrayList<Integer>());
/*if(!data.rowHasMissingValue(i))
{*/
mapNodeIndex.put( newNetwork.getNode(nodeTable.getRow(data.getRowLabel(i)).get(CyNetwork.SUID, Long.class)) ,i);
mapIndexNode.put( i, newNetwork.getNode(nodeTable.getRow(data.getRowLabel(i)).get(CyNetwork.SUID, Long.class)));
//}
}
scoreTree = new TreeSet<Operation>( new Comparator<Operation>() {
public int compare(Operation op1, Operation op2) {
if(op1.score > op2.score)
return -1;
if(op1.score < op2.score)
return 1;
if(op1.nodeChild > op2.nodeChild)
return -1;
if(op1.nodeChild < op2.nodeChild)
return 1;
if(op1.nodeParent > op2.nodeParent)
return -1;
if(op1.nodeParent < op2.nodeParent)
return 1;
return 0;
}
});
edgeBlocked = new boolean [nRows][nRows];
nodeParentsMatrix = new boolean [nRows][nRows];
nodeAscendantsReach = new boolean [nRows][nRows];
if(networkSelected != null && useNetworkAsInitialSearch)
{
addColumns(networkSelected,newNetwork,table,CyEdge.class, CyNetwork.LOCAL_ATTRS);
for (final CyEdge origEdge : networkSelected.getEdgeList()) {
final CyNode newSource = orig2NewNodeMap.get(origEdge.getSource());
final CyNode newTarget = orig2NewNodeMap.get(origEdge.getTarget());
if(newSource != null && newTarget != null)
{
final boolean newDirected = origEdge.isDirected();
final CyEdge newEdge = newNetwork.addEdge(newSource, newTarget, newDirected);
cloneRow(newNetwork, CyEdge.class, networkSelected.getRow(origEdge, CyNetwork.LOCAL_ATTRS), newNetwork.getRow(newEdge, CyNetwork.LOCAL_ATTRS));
if(edgesBlocked)
{
if(networkSelected.getRow(origEdge, CyNetwork.LOCAL_ATTRS).get(CyNetwork.SELECTED, Boolean.class))
edgeBlocked[mapNodeIndex.get(newSource)][mapNodeIndex.get(newTarget)] = true;
}
if(!newDirected )
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected belongs to a network that is not directed.\n " +
"Therefore, this algorithm is not able to proceed with parameters requested", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
}
}
initParentsMap(newNetwork);
for ( i=0;i<nRows;i++)
{
updateAscendantsOfNode(i);
}
for ( i = 0; i< nRows; i++) {
if(isGraphCyclic( i))
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, "The data selected belongs to a network that is not acyclic.\n " +
"This algorithm is a bayesian network algorithm and requires a Directed Acyclic Graph(DAG) to perform", "Warning", JOptionPane.WARNING_MESSAGE);
}
});
newNetwork.dispose();
return;
}
}
}
scoreOperations = new Operation [nRows][nRows];
selectedMetric.resetParameters();
taskMonitor.setStatusMessage("Initializing Cache..." );
initCache(data, selectedMetric, taskMonitor);
taskMonitor.setStatusMessage("Cache Initialized\n Looking for optimal solution..." );
edgeTable.createColumn("Score", Double.class, false);
progress += 0.5;
added = 0;
removed = 0;
reversed = 0;
while(okToProceed)
{
operationAdd.resetParameters();
operationDelete.resetParameters();
operationReverse.resetParameters();
taskMonitor.setStatusMessage("Cache Initialized\nLooking for optimal solution by performing the following operations:\n" +
"Added edges: " + added + "\nRemoved edges: " + removed + "\nReversed edges: " + reversed );
chosenOperation=findBestOperation(data, operationAdd);
if(reversalOption)
findBestReverseEdge(data, operationReverse);
if (cancelled)
break;
if(reversalOption)
{
if(operationReverse.score > chosenOperation.score)
{
chosenOperation = operationReverse;
}
}
if(chosenOperation.score > 0.0)
{
if(chosenOperation.type == "Add")
{
edge = newNetwork.addEdge( mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), true);
newNetwork.getRow(edge).set("name", newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeParent)).get("name", String.class)
+ " (HC) " + newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeChild)).get("name", String.class));
nodeParents.get(chosenOperation.nodeChild).add(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = true;
updateCache(data, selectedMetric,chosenOperation.nodeChild);
updateAscendantsAfterAdd(chosenOperation.nodeParent,chosenOperation.nodeChild);
added++;
newNetwork.getRow(edge).set("Score", chosenOperation.score);
}
if(chosenOperation.type == "Delete")
{
newNetwork.removeEdges(newNetwork.getConnectingEdgeList(mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), CyEdge.Type.DIRECTED));
nodeParents.get(chosenOperation.nodeChild).remove(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = false;
updateCache(data, selectedMetric,chosenOperation.nodeChild);
updateAscendantsAfterDelete(chosenOperation.nodeParent,chosenOperation.nodeChild);
removed++;
}
if(chosenOperation.type == "Reverse")
{
newNetwork.removeEdges(newNetwork.getConnectingEdgeList(mapIndexNode.get(chosenOperation.nodeParent), mapIndexNode.get(chosenOperation.nodeChild), CyEdge.Type.DIRECTED));
edge = newNetwork.addEdge( mapIndexNode.get(chosenOperation.nodeChild), mapIndexNode.get(chosenOperation.nodeParent), true);
newNetwork.getRow(edge).set("name", newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeChild)).get("name", String.class)
+ " (HC) " + newNetwork.getRow( mapIndexNode.get(chosenOperation.nodeParent)).get("name", String.class));
nodeParents.get(chosenOperation.nodeChild).remove(Integer.valueOf(chosenOperation.nodeParent));
nodeParentsMatrix[chosenOperation.nodeChild][chosenOperation.nodeParent] = false;
updateAscendantsAfterDelete(chosenOperation.nodeParent,chosenOperation.nodeChild);
updateCache(data, selectedMetric,chosenOperation.nodeChild);
nodeParents.get(chosenOperation.nodeParent).add(Integer.valueOf(chosenOperation.nodeChild));
nodeParentsMatrix[chosenOperation.nodeParent][chosenOperation.nodeChild] = true;
updateCache(data, selectedMetric,chosenOperation.nodeParent);
updateAscendantsAfterAdd(chosenOperation.nodeChild,chosenOperation.nodeParent);
reversed++;
newNetwork.getRow(edge).set("Score", chosenOperation.score);
}
}
else
okToProceed = false;
progress = progress + step;
taskMonitor.setProgress(progress);
}
scoreTree.clear();
if (!cancelled)
{
if(removeNodes)
removeNodesWithoutEdges(newNetwork);
newNetworkView = displayNewNetwork(newNetwork,networkSelected, true);
taskMonitor.setProgress(1.0d);
layout = layoutManager.getDefaultLayout();
Object context = layout.getDefaultLayoutContext();
insertTasksAfterCurrentTask(layout.createTaskIterator(newNetworkView, context, CyLayoutAlgorithm.ALL_NODE_VIEWS,""));
}
}
/*
* Initialize the list of parents and the parents matrix for each node. The parents matrix is the fast way to know if
* a node is a parent of another node
*/
private void initParentsMap(CyNetwork network)
{
for ( CyEdge edge : network.getEdgeList()) {
nodeParents.get(mapNodeIndex.get(edge.getTarget())).add(Integer.valueOf(mapNodeIndex.get(edge.getSource())));
nodeParentsMatrix[mapNodeIndex.get(edge.getTarget())][mapNodeIndex.get(edge.getSource())] = true;
}
}
/*
* Update the matrix that allows to know for each node which other nodes are its ascendants
*/
private void updateAscendantsOfNode(int nodeToUpdate )
{
ArrayList<Integer> ascendantsList = new ArrayList<Integer>(nodeParents.size());
int pos = -1;
boolean [] nodeCheckList = new boolean [nodeParents.size()];
int nodeToCheck = nodeToUpdate;
nodeCheckList[nodeToUpdate] = true;
while(pos != ascendantsList.size())
{
for(int node : nodeParents.get(nodeToCheck))
{
nodeAscendantsReach[nodeToUpdate][node] = true;
if(!nodeCheckList[node])
{
ascendantsList.add(node);
nodeCheckList[node] = true;
}
}
pos++;
if(pos < ascendantsList.size())
nodeToCheck = ascendantsList.get(pos);
}
}
/*
* Update the ascendants matrix after adding a new edge
*/
private void updateAscendantsAfterAdd(int parent , int child)
{
ArrayList<Integer> parentsList = new ArrayList<Integer>();
ArrayList<Integer> childsList = new ArrayList<Integer>();
int i;
for(i=0;i<nodeParents.size();i++)
{
if(nodeAscendantsReach[i][child])
childsList.add(i);
if(nodeAscendantsReach[parent][i])
parentsList.add(i);
}
parentsList.add(parent);
childsList.add(child);
for(int c: childsList)
{
for(int p: parentsList)
{
nodeAscendantsReach[c][p] = true;
}
}
}
/*
* Update the ascendants matrix after deleting an existing edge
*/
private void updateAscendantsAfterDelete(int parent , int child)
{
ArrayList<Integer> childsList = new ArrayList<Integer>();
int i;
for(i=0;i<nodeParents.size();i++)
{
if(nodeAscendantsReach[i][child])
childsList.add(i);
}
childsList.add(child);
for(int c: childsList)
{
updateAscendantsOfNode(c);
}
}
private void initCache(CyniTable data, CyCyniMetric metric, TaskMonitor taskMonitor)
{
double[] baseScores = new double[data.nRows()];
int nRows = data.nRows();
int nodeIndex,i;
Double progress = 0.0d;
Double step = 0.0;
ArrayList<Integer> parents = new ArrayList<Integer>();
// Create the thread pools
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
step = 1.0 / (nRows*2.0);
for(i = 0;i<nRows;i++) {
nodeIndex =i;
parents.clear();
if(nodeParents.get(nodeIndex).size() > 0)
parents.addAll(nodeParents.get(nodeIndex));
else
parents.add(nodeIndex);
baseScores[nodeIndex] = metric.getMetric(data, data, nodeIndex,parents);
}
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
for (int nodeEnd = 0; nodeEnd < nRows; nodeEnd++)
{
if (nodeStart != nodeEnd)
{
executor.execute(new ThreadedGetMetric(data,nodeStart,nodeEnd,baseScores[nodeEnd]));
}
}
executor.shutdown();
// Wait until all threads are finish
try {
executor.awaitTermination(7, TimeUnit.DAYS);
} catch (Exception e) {}
executor = Executors.newFixedThreadPool(nThreads);
progress = progress + step;
taskMonitor.setProgress(progress);
}
}
private void updateCache(CyniTable data, CyCyniMetric metric, int nodeEnd)
{
int nRows = data.nRows();
ArrayList<Integer> parents = new ArrayList<Integer>();
double baseScore ;
// Create the thread pools
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
if(nodeParents.get(nodeEnd).size() > 0)
parents.addAll(nodeParents.get(nodeEnd));
else
parents.add(nodeEnd);
baseScore = metric.getMetric(data, data, nodeEnd, parents);
removeElements(nodeEnd,nRows);
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
if (nodeStart != nodeEnd) {
executor.execute(new ThreadedGetMetric(data,nodeStart,nodeEnd,baseScore));
}
}
executor.shutdown();
// Wait until all threads are finish
try {
executor.awaitTermination(7, TimeUnit.DAYS);
} catch (Exception e) {}
}
private Operation findBestOperation(CyniTable data, Operation operation)
{
boolean notFound = true;
ArrayList<Operation> opList = new ArrayList<Operation>();
Operation opTemp = new Operation();
while(notFound)
{
opTemp = scoreTree.pollFirst();
opList.add(opTemp);
if(opTemp.type == "Add")
{
if (nodeParents.get(opTemp.nodeChild).size() <= maxNumParents && !nodeAscendantsReach[opTemp.nodeParent][opTemp.nodeChild])
{
operation = opTemp;
notFound = false;
}
}
if(opTemp.type == "Delete")
{
if(!edgeBlocked[opTemp.nodeParent][opTemp.nodeChild])
{
operation = opTemp;
notFound = false;
}
}
}
scoreTree.addAll(opList);
return opTemp;
}
private void removeElements(int nodeEnd, int nRows)
{
for (int nodeStart = 0; nodeStart < nRows; nodeStart++) {
if (nodeStart != nodeEnd)
scoreTree.remove(scoreOperations[nodeStart][nodeEnd]);
}
}
@SuppressWarnings("unchecked")
private void findBestReverseEdge(CyniTable data, Operation operation)
{
int nRows = data.nRows();
int nodeParent;
ArrayList<Integer> tempList;
for (int nodeChild = 0; nodeChild < nRows; nodeChild++) {
tempList = (ArrayList<Integer>)nodeParents.get(nodeChild).clone();
for (Iterator<Integer> it = tempList.iterator(); it.hasNext();) {
nodeParent = it.next();
if((scoreOperations[nodeParent][nodeChild].score + scoreOperations[nodeChild][nodeParent].score) > operation.score)
{
nodeParents.get(nodeChild).remove(Integer.valueOf(nodeParent));
nodeParents.get(nodeParent).add(Integer.valueOf(nodeChild));
if(!isGraphCyclic( nodeParent) )
{
operation.score = scoreOperations[nodeParent][nodeChild].score + scoreOperations[nodeChild][nodeParent].score;
operation.nodeParent = nodeParent;
operation.nodeChild = nodeChild;
}
nodeParents.get(nodeParent).remove(Integer.valueOf(nodeChild));
nodeParents.get(nodeChild).add(Integer.valueOf(nodeParent));
}
}
}
}
class Operation{
public Operation()
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
}
public Operation(String type)
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
this.type = type;
}
public int nodeParent;
public int nodeChild;
public double score;
public String type;
public void resetParameters()
{
nodeParent = -1;
nodeChild = -1;
score = -1E100;
}
}
private class ThreadedGetMetric implements Runnable {
private int nodeStart, nodeEnd;
private double baseScore;
private CyniTable tableData;
private ArrayList<Integer> parents = new ArrayList<Integer>();
ThreadedGetMetric(CyniTable data,int nodeStart, int nodeEnd, double baseScore)
{
this.nodeStart = nodeStart;
this.nodeEnd = nodeEnd;
this.tableData = data;
this.baseScore = baseScore;
}
public void run() {
if(!nodeParentsMatrix[nodeEnd][nodeStart])
{
if (nodeParents.get(nodeEnd).size() < maxNumParents)
{
Operation op = new Operation ("Add");
parents.addAll(nodeParents.get(nodeEnd));
parents.add(nodeStart);
op.score = selectedMetric.getMetric(tableData, tableData, nodeEnd, parents) - baseScore;
op.nodeChild = nodeEnd;
op.nodeParent = nodeStart;
scoreOperations[nodeStart][nodeEnd] = op;
synchronized (scoreTree){
scoreTree.add(op);
}
}
}
else
{
if(nodeParents.get(nodeEnd).size() > 0)
{
parents.addAll(nodeParents.get(nodeEnd));
parents.remove(Integer.valueOf(nodeStart));
}
if(parents.size() == 0)
parents.add(nodeEnd);
Operation op = new Operation ("Delete");
op.score = selectedMetric.getMetric(tableData, tableData, nodeEnd, parents) - baseScore;
op.nodeChild = nodeEnd;
op.nodeParent = nodeStart;
scoreOperations[nodeStart][nodeEnd] = op;
synchronized (scoreTree){
scoreTree.add(op);
}
}
parents.clear();
}
}
}
|
diff --git a/Client/src/edu/purdue/cs252/lab06/DirectoryActivity.java b/Client/src/edu/purdue/cs252/lab06/DirectoryActivity.java
index 59622f6..35aa560 100644
--- a/Client/src/edu/purdue/cs252/lab06/DirectoryActivity.java
+++ b/Client/src/edu/purdue/cs252/lab06/DirectoryActivity.java
@@ -1,321 +1,313 @@
package edu.purdue.cs252.lab06;
import java.io.IOException;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class DirectoryActivity extends ListActivity
{
String serverAddress;
String username;
Handler UIhandler;
private DirectoryClient dc;
private ArrayAdapter<String> database;
private ArrayList<String> usernames;
private ArrayList<User> users;
private AlertDialog incomingDialog = null;
private ProgressDialog ringingDialog = null;
private int CALL_STATUS = 0; // 0 = idle, 1 = place call, 2 = receive call, 3 = in call
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.directory);
users = new ArrayList<User>();
usernames = new ArrayList<String>();
database = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usernames);
setListAdapter(database);
final ListView lv1 = getListView();
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
User target = null;
for (User u : users)
{
if (u.getUsername().equals(lv1.getItemAtPosition(position)))
{
target = u;
}
}
if (target == null) return;
final String username = target.getUsername();
final String destinationIP = target.getIPAddress();
AlertDialog.Builder adb = new AlertDialog.Builder(DirectoryActivity.this);
adb.setTitle("Send Call");
adb.setMessage("Are you sure you want to call " + target.getUsername() + " at " + target.getIPAddress() + "?");
adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 1;
try
{
dc.sendCall(destinationIP);
ringingDialog = new ProgressDialog(DirectoryActivity.this);
ringingDialog.setTitle("Ringing");
ringingDialog.setMessage("Waiting for " + username + " to respond...");
ringingDialog.setOnCancelListener(new ProgressDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
try
{
dc.hangUp(destinationIP);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ringingDialog.show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 0;
- try
- {
- dc.hangUp(destinationIP);
- }
- catch (IOException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ // FUCK OFF
}
});
adb.show();
}
});
connectToServer();
}
public void connectToServer()
{
Log.i("Checkpoint", "Entered connectToServer()...");
Bundle extras = getIntent().getExtras();
serverAddress = extras.getString("serverAddress");
username = extras.getString("username");
try
{
setupHandler();
dc = new DirectoryClient(serverAddress, UIhandler);
dc.connect();
dc.addUser(username);
}
catch (Exception ex)
{
AlertDialog.Builder adb = new AlertDialog.Builder(DirectoryActivity.this);
adb.setTitle("Error");
adb.setMessage(ex.getMessage());
adb.setPositiveButton("OK", null);
adb.show();
}
finishActivity(0);
}
public void setupHandler()
{
UIhandler = new Handler() {
public void handleMessage(Message msg)
{
if (msg.what == 0)
{
updateDirectory(((ArrayList<User>)msg.obj));
}
else if (msg.what == 1)
{
displayIncomingCall(((String[])msg.obj)[0], ((String[])msg.obj)[1]);
}
else if (msg.what == 2)
{
displayHangup();
}
else if (msg.what == 3)
{
displayBusy();
}
else if (msg.what == 4)
{
connect((String)msg.obj);
}
}
};
}
public void updateDirectory(ArrayList<User> directory)
{
users.clear();
usernames.clear();
for (User u : directory)
{
users.add(u);
usernames.add(u.getUsername());
}
database.notifyDataSetChanged();
}
//private String senderIP = null;
public void displayIncomingCall(String username, String ipAddress)
{
CALL_STATUS = 2;
final String senderIP = ipAddress;
Log.i("Checkpoint", "Entered displayIncomingCall()...");
AlertDialog.Builder adb = new AlertDialog.Builder(DirectoryActivity.this);
adb.setTitle("Incoming Call");
adb.setMessage("You have an incoming call from " + username + " at " + ipAddress + ".");
adb.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 3;
try
{
dc.acceptCall(senderIP);
}
catch (IOException e)
{
// TODO Auto-generated catch block
}
}
});
adb.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 0;
try
{
dc.hangUp(senderIP);
}
catch (IOException e)
{
// TODO Auto-generated catch block
}
}
});
incomingDialog = adb.create();
incomingDialog.show();
}
public void displayHangup()
{
if (incomingDialog != null)
{
incomingDialog.dismiss();
}
if (ringingDialog != null)
{
ringingDialog.dismiss();
}
if (CALL_STATUS == 1)
{
AlertDialog.Builder adb = new AlertDialog.Builder(DirectoryActivity.this);
adb.setTitle("Busy");
adb.setMessage("The user that you tried to call is busy and declined to answer.");
adb.setPositiveButton("OK", null);
adb.show();
}
}
public void connect(String ipAddress)
{
if (incomingDialog != null)
{
incomingDialog.dismiss();
}
if (ringingDialog != null)
{
ringingDialog.dismiss();
}
// Intent i = new Intent(DirectoryActivity.this, CallActivity.class);
// i.putExtra("serverAddress", ipAddress.toString());
// i.putExtra("username", "STEVE JOBS");
// startActivity(i);
CALL_STATUS = 3;
}
public void displayBusy()
{
if (incomingDialog != null)
{
incomingDialog.dismiss();
}
if (ringingDialog != null)
{
ringingDialog.dismiss();
}
if (CALL_STATUS == 1)
{
AlertDialog.Builder adb = new AlertDialog.Builder(DirectoryActivity.this);
adb.setTitle("Busy");
adb.setMessage("The user that you tried to call is busy and declined to answer.");
adb.setPositiveButton("OK", null);
adb.show();
}
CALL_STATUS = 0;
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.directory);
users = new ArrayList<User>();
usernames = new ArrayList<String>();
database = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usernames);
setListAdapter(database);
final ListView lv1 = getListView();
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
User target = null;
for (User u : users)
{
if (u.getUsername().equals(lv1.getItemAtPosition(position)))
{
target = u;
}
}
if (target == null) return;
final String username = target.getUsername();
final String destinationIP = target.getIPAddress();
AlertDialog.Builder adb = new AlertDialog.Builder(DirectoryActivity.this);
adb.setTitle("Send Call");
adb.setMessage("Are you sure you want to call " + target.getUsername() + " at " + target.getIPAddress() + "?");
adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 1;
try
{
dc.sendCall(destinationIP);
ringingDialog = new ProgressDialog(DirectoryActivity.this);
ringingDialog.setTitle("Ringing");
ringingDialog.setMessage("Waiting for " + username + " to respond...");
ringingDialog.setOnCancelListener(new ProgressDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
try
{
dc.hangUp(destinationIP);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ringingDialog.show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 0;
try
{
dc.hangUp(destinationIP);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
adb.show();
}
});
connectToServer();
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.directory);
users = new ArrayList<User>();
usernames = new ArrayList<String>();
database = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usernames);
setListAdapter(database);
final ListView lv1 = getListView();
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
User target = null;
for (User u : users)
{
if (u.getUsername().equals(lv1.getItemAtPosition(position)))
{
target = u;
}
}
if (target == null) return;
final String username = target.getUsername();
final String destinationIP = target.getIPAddress();
AlertDialog.Builder adb = new AlertDialog.Builder(DirectoryActivity.this);
adb.setTitle("Send Call");
adb.setMessage("Are you sure you want to call " + target.getUsername() + " at " + target.getIPAddress() + "?");
adb.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 1;
try
{
dc.sendCall(destinationIP);
ringingDialog = new ProgressDialog(DirectoryActivity.this);
ringingDialog.setTitle("Ringing");
ringingDialog.setMessage("Waiting for " + username + " to respond...");
ringingDialog.setOnCancelListener(new ProgressDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
try
{
dc.hangUp(destinationIP);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ringingDialog.show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
CALL_STATUS = 0;
// FUCK OFF
}
});
adb.show();
}
});
connectToServer();
}
|
diff --git a/src/net/java/sip/communicator/impl/neomedia/device/MediaDeviceImpl.java b/src/net/java/sip/communicator/impl/neomedia/device/MediaDeviceImpl.java
index 2d695bc21..2bd47e2ad 100644
--- a/src/net/java/sip/communicator/impl/neomedia/device/MediaDeviceImpl.java
+++ b/src/net/java/sip/communicator/impl/neomedia/device/MediaDeviceImpl.java
@@ -1,459 +1,461 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.neomedia.device;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import javax.media.*;
import javax.media.control.*;
import javax.media.protocol.*;
import net.java.sip.communicator.impl.neomedia.*;
import net.java.sip.communicator.impl.neomedia.codec.*;
import net.java.sip.communicator.impl.neomedia.format.*;
import net.java.sip.communicator.impl.neomedia.jmfext.media.protocol.*;
import net.java.sip.communicator.impl.neomedia.protocol.*;
import net.java.sip.communicator.service.neomedia.*;
import net.java.sip.communicator.service.neomedia.device.*;
import net.java.sip.communicator.service.neomedia.format.*;
import net.java.sip.communicator.util.*;
/**
* Implements <tt>MediaDevice</tt> for the JMF <tt>CaptureDevice</tt>.
*
* @author Lubomir Marinov
* @author Emil Ivov
*/
public class MediaDeviceImpl
extends AbstractMediaDevice
{
/**
* The <tt>Logger</tt> used by <tt>MediaDeviceImpl</tt> and its instances
* for logging output.
*/
private static final Logger logger
= Logger.getLogger(MediaDeviceImpl.class);
/**
* The <tt>CaptureDeviceInfo</tt> of the device that this instance is
* representing.
*/
private final CaptureDeviceInfo captureDeviceInfo;
/**
* The <tt>MediaType</tt> of this instance and the <tt>CaptureDevice</tt>
* that it wraps.
*/
private final MediaType mediaType;
/**
* Initializes a new <tt>MediaDeviceImpl</tt> instance with a specific
* <tt>MediaType</tt> and with <tt>MediaDirection</tt> which does not allow
* sending.
*
* @param mediaType the <tt>MediaType</tt> of the new instance
*/
public MediaDeviceImpl(MediaType mediaType)
{
this.captureDeviceInfo = null;
this.mediaType = mediaType;
}
/**
* Initializes a new <tt>MediaDeviceImpl</tt> instance which is to provide
* an implementation of <tt>MediaDevice</tt> for a <tt>CaptureDevice</tt>
* with a specific <tt>CaptureDeviceInfo</tt> and which is of a specific
* <tt>MediaType</tt>.
*
* @param captureDeviceInfo the <tt>CaptureDeviceInfo</tt> of the JMF
* <tt>CaptureDevice</tt> the new instance is to provide an implementation
* of <tt>MediaDevice</tt> for
* @param mediaType the <tt>MediaType</tt> of the new instance
*/
public MediaDeviceImpl(
CaptureDeviceInfo captureDeviceInfo,
MediaType mediaType)
{
if (captureDeviceInfo == null)
throw new NullPointerException("captureDeviceInfo");
if (mediaType == null)
throw new NullPointerException("mediaType");
this.captureDeviceInfo = captureDeviceInfo;
this.mediaType = mediaType;
}
/**
* Creates the JMF <tt>CaptureDevice</tt> this instance represents and
* provides an implementation of <tt>MediaDevice</tt> for.
*
* @return the JMF <tt>CaptureDevice</tt> this instance represents and
* provides an implementation of <tt>MediaDevice</tt> for; <tt>null</tt>
* if the creation fails
*/
CaptureDevice createCaptureDevice()
{
CaptureDevice captureDevice = null;
if (getDirection().allowsSending())
{
Throwable exception = null;
try
{
captureDevice
= (CaptureDevice)
Manager.createDataSource(
captureDeviceInfo.getLocator());
}
catch (IOException ioe)
{
// TODO
exception = ioe;
}
catch (NoDataSourceException ndse)
{
// TODO
exception = ndse;
}
if (exception != null)
logger
.error(
"Failed to create CaptureDevice"
+ " from CaptureDeviceInfo "
+ captureDeviceInfo,
exception);
else
{
if(captureDevice instanceof AbstractPullBufferCaptureDevice)
{
((AbstractPullBufferCaptureDevice)captureDevice)
.setCaptureDeviceInfo(captureDeviceInfo);
}
// Try to enable tracing on captureDevice.
if (logger.isTraceEnabled())
captureDevice
= createTracingCaptureDevice(captureDevice, logger);
}
}
return captureDevice;
}
/**
* Creates a <tt>DataSource</tt> instance for this <tt>MediaDevice</tt>
* which gives access to the captured media.
*
* @return a <tt>DataSource</tt> instance which gives access to the media
* captured by this <tt>MediaDevice</tt>
* @see AbstractMediaDevice#createOutputDataSource()
*/
DataSource createOutputDataSource()
{
return
getDirection().allowsSending()
? (DataSource) createCaptureDevice()
: null;
}
/**
* Creates a new <tt>CaptureDevice</tt> which traces calls to a specific
* <tt>CaptureDevice</tt> for debugging purposes.
*
* @param captureDevice the <tt>CaptureDevice</tt> which is to have its
* calls traced for debugging output
* @param logger the <tt>Logger</tt> to be used for logging the trace
* messages
* @return a new <tt>CaptureDevice</tt> which traces the calls to the
* specified <tt>captureDevice</tt>
*/
public static CaptureDevice createTracingCaptureDevice(
CaptureDevice captureDevice,
final Logger logger)
{
if (captureDevice instanceof PushBufferDataSource)
captureDevice
= new CaptureDeviceDelegatePushBufferDataSource(
captureDevice)
{
@Override
public void connect()
throws IOException
{
super.connect();
if (logger.isTraceEnabled())
logger
.trace(
"Connected "
+ MediaDeviceImpl
.toString(this.captureDevice));
}
@Override
public void disconnect()
{
super.disconnect();
if (logger.isTraceEnabled())
logger
.trace(
"Disconnected "
+ MediaDeviceImpl
.toString(this.captureDevice));
}
@Override
public void start()
throws IOException
{
super.start();
if (logger.isTraceEnabled())
logger
.trace(
"Started "
+ MediaDeviceImpl
.toString(this.captureDevice));
}
@Override
public void stop()
throws IOException
{
super.stop();
if (logger.isTraceEnabled())
logger
.trace(
"Stopped "
+ MediaDeviceImpl
.toString(this.captureDevice));
}
};
return captureDevice;
}
/**
* Gets the <tt>CaptureDeviceInfo</tt> of the JMF <tt>CaptureDevice</tt>
* represented by this instance.
*
* @return the <tt>CaptureDeviceInfo</tt> of the <tt>CaptureDevice</tt>
* represented by this instance
*/
public CaptureDeviceInfo getCaptureDeviceInfo()
{
return captureDeviceInfo;
}
/**
* Returns the <tt>MediaDirection</tt> supported by this device.
*
* @return {@link MediaDirection#SENDONLY} if this is a read-only device,
* {@link MediaDirection#RECVONLY} if this is a write-only device or
* {@link MediaDirection#SENDRECV} if this <tt>MediaDevice</tt> can both
* capture and render media
* @see MediaDevice#getDirection()
*/
public MediaDirection getDirection()
{
if (captureDeviceInfo != null)
return MediaDirection.SENDRECV;
else
return
MediaType.AUDIO.equals(getMediaType())
? MediaDirection.INACTIVE
: MediaDirection.RECVONLY;
}
/**
* Gets the <tt>MediaFormat</tt> in which this <tt>MediaDevice</tt> captures
* media.
*
* @return the <tt>MediaFormat</tt> in which this <tt>MediaDevice</tt>
* captures media
* @see MediaDevice#getFormat()
*/
public MediaFormat getFormat()
{
CaptureDevice captureDevice = createCaptureDevice();
if (captureDevice != null)
{
MediaType mediaType = getMediaType();
for (FormatControl formatControl
: captureDevice.getFormatControls())
{
MediaFormat format
= MediaFormatImpl.createInstance(formatControl.getFormat());
if ((format != null) && format.getMediaType().equals(mediaType))
return format;
}
}
return null;
}
/**
* Gets the <tt>MediaType</tt> that this device supports.
*
* @return {@link MediaType#AUDIO} if this is an audio device or
* {@link MediaType#VIDEO} if this is a video device
* @see MediaDevice#getMediaType()
*/
public MediaType getMediaType()
{
return mediaType;
}
/**
* Gets a list of <tt>MediaFormat</tt>s supported by this
* <tt>MediaDevice</tt>.
*
* @return the list of <tt>MediaFormat</tt>s supported by this device
* @see MediaDevice#getSupportedFormats()
*/
public List<MediaFormat> getSupportedFormats()
{
return this.getSupportedFormats(null, null);
}
/**
* Gets a list of <tt>MediaFormat</tt>s supported by this
* <tt>MediaDevice</tt>.
* @param sendPreset the preset used to set some of the format parameters,
* used for video and settings.
* @return the list of <tt>MediaFormat</tt>s supported by this device
* @see MediaDevice#getSupportedFormats()
*/
public List<MediaFormat> getSupportedFormats(QualityPresets sendPreset,
QualityPresets receivePreset)
{
EncodingConfiguration encodingConfiguration
= NeomediaActivator
.getMediaServiceImpl().getEncodingConfiguration();
MediaFormat[] supportedEncodings
= encodingConfiguration.getSupportedEncodings(getMediaType());
List<MediaFormat> supportedFormats = new ArrayList<MediaFormat>();
if (supportedEncodings != null)
for (MediaFormat supportedEncoding : supportedEncodings)
supportedFormats.add(supportedEncoding);
// if there is preset check and set the format attributes
// where needed
{
MediaFormat customFormat = null;
MediaFormat toRemove = null;
for(MediaFormat f : supportedFormats)
{
if("h264".equalsIgnoreCase(f.getEncoding()))
{
Map<String,String> h264AdvancedAttributes =
f.getAdvancedAttributes();
if(h264AdvancedAttributes == null)
h264AdvancedAttributes = new HashMap<String, String>();
Dimension sendSize = null;
Dimension receiveSize;
// change send size only for video calls
- if(!captureDeviceInfo.getLocator().getProtocol().equals(
- ImageStreamingAuto.LOCATOR_PROTOCOL))
+ if(captureDeviceInfo != null
+ && captureDeviceInfo.getLocator() != null
+ && !(ImageStreamingAuto.LOCATOR_PROTOCOL.equals(
+ captureDeviceInfo.getLocator().getProtocol())))
{
if(sendPreset != null)
sendSize = sendPreset.getResolution();
else
sendSize = NeomediaActivator.getMediaServiceImpl()
.getDeviceConfiguration().getVideoSize();
}
// if there is specified preset, send its settings
if(receivePreset != null)
receiveSize = receivePreset.getResolution();
else
{
// or just send the max video resolution of the PC
// as we do by default
ScreenDevice screen
= NeomediaActivator.getMediaServiceImpl()
.getDefaultScreenDevice();
receiveSize = (screen == null) ?
null : screen.getSize();
}
h264AdvancedAttributes.put("imageattr",
MediaUtils.createImageAttr(sendSize,
receiveSize));
customFormat = NeomediaActivator.getMediaServiceImpl()
.getFormatFactory().createMediaFormat(
f.getEncoding(),
f.getClockRate(),
f.getFormatParameters(),
h264AdvancedAttributes);
toRemove = f;
}
}
if(toRemove != null && customFormat != null)
{
supportedFormats.remove(toRemove);
supportedFormats.add(customFormat);
}
}
return supportedFormats;
}
/**
* Gets a human-readable <tt>String</tt> representation of this instance.
*
* @return a <tt>String</tt> providing a human-readable representation of
* this instance
*/
@Override
public String toString()
{
CaptureDeviceInfo captureDeviceInfo = getCaptureDeviceInfo();
return
(captureDeviceInfo == null)
? super.toString()
: captureDeviceInfo.toString();
}
/**
* Returns a human-readable representation of a specific
* <tt>CaptureDevice</tt> in the form of a <tt>String</tt> value.
*
* @param captureDevice the <tt>CaptureDevice</tt> to get a human-readable
* representation of
* @return a <tt>String</tt> value which gives a human-readable
* representation of the specified <tt>captureDevice</tt>
*/
private static String toString(CaptureDevice captureDevice)
{
StringBuffer str = new StringBuffer();
str.append("CaptureDevice with hashCode ");
str.append(captureDevice.hashCode());
str.append(" and captureDeviceInfo ");
CaptureDeviceInfo captureDeviceInfo
= captureDevice.getCaptureDeviceInfo();
MediaLocator mediaLocator = captureDeviceInfo.getLocator();
str.append((mediaLocator == null) ? captureDeviceInfo : mediaLocator);
return str.toString();
}
}
| true | true | public List<MediaFormat> getSupportedFormats(QualityPresets sendPreset,
QualityPresets receivePreset)
{
EncodingConfiguration encodingConfiguration
= NeomediaActivator
.getMediaServiceImpl().getEncodingConfiguration();
MediaFormat[] supportedEncodings
= encodingConfiguration.getSupportedEncodings(getMediaType());
List<MediaFormat> supportedFormats = new ArrayList<MediaFormat>();
if (supportedEncodings != null)
for (MediaFormat supportedEncoding : supportedEncodings)
supportedFormats.add(supportedEncoding);
// if there is preset check and set the format attributes
// where needed
{
MediaFormat customFormat = null;
MediaFormat toRemove = null;
for(MediaFormat f : supportedFormats)
{
if("h264".equalsIgnoreCase(f.getEncoding()))
{
Map<String,String> h264AdvancedAttributes =
f.getAdvancedAttributes();
if(h264AdvancedAttributes == null)
h264AdvancedAttributes = new HashMap<String, String>();
Dimension sendSize = null;
Dimension receiveSize;
// change send size only for video calls
if(!captureDeviceInfo.getLocator().getProtocol().equals(
ImageStreamingAuto.LOCATOR_PROTOCOL))
{
if(sendPreset != null)
sendSize = sendPreset.getResolution();
else
sendSize = NeomediaActivator.getMediaServiceImpl()
.getDeviceConfiguration().getVideoSize();
}
// if there is specified preset, send its settings
if(receivePreset != null)
receiveSize = receivePreset.getResolution();
else
{
// or just send the max video resolution of the PC
// as we do by default
ScreenDevice screen
= NeomediaActivator.getMediaServiceImpl()
.getDefaultScreenDevice();
receiveSize = (screen == null) ?
null : screen.getSize();
}
h264AdvancedAttributes.put("imageattr",
MediaUtils.createImageAttr(sendSize,
receiveSize));
customFormat = NeomediaActivator.getMediaServiceImpl()
.getFormatFactory().createMediaFormat(
f.getEncoding(),
f.getClockRate(),
f.getFormatParameters(),
h264AdvancedAttributes);
toRemove = f;
}
}
if(toRemove != null && customFormat != null)
{
supportedFormats.remove(toRemove);
supportedFormats.add(customFormat);
}
}
return supportedFormats;
}
| public List<MediaFormat> getSupportedFormats(QualityPresets sendPreset,
QualityPresets receivePreset)
{
EncodingConfiguration encodingConfiguration
= NeomediaActivator
.getMediaServiceImpl().getEncodingConfiguration();
MediaFormat[] supportedEncodings
= encodingConfiguration.getSupportedEncodings(getMediaType());
List<MediaFormat> supportedFormats = new ArrayList<MediaFormat>();
if (supportedEncodings != null)
for (MediaFormat supportedEncoding : supportedEncodings)
supportedFormats.add(supportedEncoding);
// if there is preset check and set the format attributes
// where needed
{
MediaFormat customFormat = null;
MediaFormat toRemove = null;
for(MediaFormat f : supportedFormats)
{
if("h264".equalsIgnoreCase(f.getEncoding()))
{
Map<String,String> h264AdvancedAttributes =
f.getAdvancedAttributes();
if(h264AdvancedAttributes == null)
h264AdvancedAttributes = new HashMap<String, String>();
Dimension sendSize = null;
Dimension receiveSize;
// change send size only for video calls
if(captureDeviceInfo != null
&& captureDeviceInfo.getLocator() != null
&& !(ImageStreamingAuto.LOCATOR_PROTOCOL.equals(
captureDeviceInfo.getLocator().getProtocol())))
{
if(sendPreset != null)
sendSize = sendPreset.getResolution();
else
sendSize = NeomediaActivator.getMediaServiceImpl()
.getDeviceConfiguration().getVideoSize();
}
// if there is specified preset, send its settings
if(receivePreset != null)
receiveSize = receivePreset.getResolution();
else
{
// or just send the max video resolution of the PC
// as we do by default
ScreenDevice screen
= NeomediaActivator.getMediaServiceImpl()
.getDefaultScreenDevice();
receiveSize = (screen == null) ?
null : screen.getSize();
}
h264AdvancedAttributes.put("imageattr",
MediaUtils.createImageAttr(sendSize,
receiveSize));
customFormat = NeomediaActivator.getMediaServiceImpl()
.getFormatFactory().createMediaFormat(
f.getEncoding(),
f.getClockRate(),
f.getFormatParameters(),
h264AdvancedAttributes);
toRemove = f;
}
}
if(toRemove != null && customFormat != null)
{
supportedFormats.remove(toRemove);
supportedFormats.add(customFormat);
}
}
return supportedFormats;
}
|
diff --git a/src/CardDriver.java b/src/CardDriver.java
index 617cc14..cbaf2ce 100644
--- a/src/CardDriver.java
+++ b/src/CardDriver.java
@@ -1,23 +1,23 @@
/**
* Programmer: kyle
* Date: 1/24/13
* Time: 8:00 AM
* Exercise:
*/
public class CardDriver {
public static void main(String[] args) {
Card card = new Card(1,4);
System.out.println(card);
- System.out.println("Card is suit " + card.getSuit());
- System.out.println("Card is rank " + card.getRank());
+ System.out.println("Card one is suit " + card.getSuit());
+ System.out.println("Card one is rank " + card.getRank());
System.out.println();
Card card2 = new Card(5, 3);
System.out.println(card2);
- System.out.println("Card is suit " +card2.getSuit());
- System.out.println("Card is rank " + card2.getRank());
+ System.out.println("Card two is suit " +card2.getSuit());
+ System.out.println("Card two is rank " + card2.getRank());
}
}
| false | true | public static void main(String[] args) {
Card card = new Card(1,4);
System.out.println(card);
System.out.println("Card is suit " + card.getSuit());
System.out.println("Card is rank " + card.getRank());
System.out.println();
Card card2 = new Card(5, 3);
System.out.println(card2);
System.out.println("Card is suit " +card2.getSuit());
System.out.println("Card is rank " + card2.getRank());
}
| public static void main(String[] args) {
Card card = new Card(1,4);
System.out.println(card);
System.out.println("Card one is suit " + card.getSuit());
System.out.println("Card one is rank " + card.getRank());
System.out.println();
Card card2 = new Card(5, 3);
System.out.println(card2);
System.out.println("Card two is suit " +card2.getSuit());
System.out.println("Card two is rank " + card2.getRank());
}
|
diff --git a/tool/src/java/org/sakaiproject/profile2/tool/pages/panels/MyStatusPanel.java b/tool/src/java/org/sakaiproject/profile2/tool/pages/panels/MyStatusPanel.java
index 342f8b38..9f3b2bf2 100644
--- a/tool/src/java/org/sakaiproject/profile2/tool/pages/panels/MyStatusPanel.java
+++ b/tool/src/java/org/sakaiproject/profile2/tool/pages/panels/MyStatusPanel.java
@@ -1,225 +1,225 @@
/**
* Copyright (c) 2008-2010 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.profile2.tool.pages.panels;
import org.apache.log4j.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.behavior.StringHeaderContributor;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogic;
import org.sakaiproject.profile2.logic.ProfileMessagingLogic;
import org.sakaiproject.profile2.logic.ProfilePreferencesLogic;
import org.sakaiproject.profile2.logic.ProfileStatusLogic;
import org.sakaiproject.profile2.logic.SakaiProxy;
import org.sakaiproject.profile2.model.UserProfile;
import org.sakaiproject.profile2.tool.components.ProfileStatusRenderer;
import org.sakaiproject.profile2.tool.models.StringModel;
import org.sakaiproject.profile2.util.ProfileConstants;
public class MyStatusPanel extends Panel {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(MyStatusPanel.class);
private ProfileStatusRenderer status;
@SpringBean(name="org.sakaiproject.profile2.logic.SakaiProxy")
private SakaiProxy sakaiProxy;
@SpringBean(name="org.sakaiproject.profile2.logic.ProfileStatusLogic")
private ProfileStatusLogic statusLogic;
@SpringBean(name="org.sakaiproject.profile2.logic.ProfilePreferencesLogic")
private ProfilePreferencesLogic preferencesLogic;
@SpringBean(name="org.sakaiproject.profile2.logic.ProfileMessagingLogic")
private ProfileMessagingLogic messagingLogic;
@SpringBean(name="org.sakaiproject.profile2.logic.ProfileExternalIntegrationLogic")
protected ProfileExternalIntegrationLogic externalIntegrationLogic;
//get default text that fills the textField
String defaultStatus = new ResourceModel("text.no.status", "Say something").getObject().toString();
public MyStatusPanel(String id, UserProfile userProfile) {
super(id);
log.debug("MyStatusPanel()");
//get info
final String displayName = userProfile.getDisplayName();
final String userId = userProfile.getUserUuid();
//if superUser and proxied, can't update
boolean editable = true;
if(sakaiProxy.isSuperUserAndProxiedToUser(userId)) {
editable = false;
}
//name
Label profileName = new Label("profileName", displayName);
add(profileName);
//status component
status = new ProfileStatusRenderer("status", userId, null, "tiny");
status.setOutputMarkupId(true);
add(status);
WebMarkupContainer statusFormContainer = new WebMarkupContainer("statusFormContainer");
//setup SimpleText object to back the single form field
StringModel stringModel = new StringModel();
//status form
Form form = new Form("form", new Model(stringModel));
form.setOutputMarkupId(true);
//status field
final TextField statusField = new TextField("message", new PropertyModel(stringModel, "string"));
statusField.setOutputMarkupPlaceholderTag(true);
form.add(statusField);
//link the status textfield field with the focus/blur function via this dynamic js
//also link with counter
StringHeaderContributor statusJavascript = new StringHeaderContributor(
"<script type=\"text/javascript\">" +
"$(document).ready( function(){" +
- "autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');" +
+ "autoFill('#" + statusField.getMarkupId() + "', '" + defaultStatus + "');" +
"countChars('#" + statusField.getMarkupId() + "');" +
"});" +
"</script>");
add(statusJavascript);
//clear link
final AjaxFallbackLink clearLink = new AjaxFallbackLink("clearLink") {
private static final long serialVersionUID = 1L;
public void onClick(AjaxRequestTarget target) {
//clear status, hide and repaint
if(statusLogic.clearUserStatus(userId)) {
status.setVisible(false); //hide status
this.setVisible(false); //hide clear link
target.addComponent(status);
target.addComponent(this);
target.appendJavascript("autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');");
//target.addComponent(statusField);
}
}
};
clearLink.setOutputMarkupPlaceholderTag(true);
clearLink.add(new Label("clearLabel",new ResourceModel("link.status.clear")));
//set visibility of clear link based on status and if it's editable
if(!status.isVisible() || !editable) {
clearLink.setVisible(false);
}
add(clearLink);
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
private static final long serialVersionUID = 1L;
protected void onSubmit(AjaxRequestTarget target, Form form) {
//get the backing model
StringModel stringModel = (StringModel) form.getModelObject();
//get userId from sakaiProxy
String userId = sakaiProxy.getCurrentUserId();
//get the status. if its the default text, do not update, although we should clear the model
String statusMessage = stringModel.getString().trim();
if(statusMessage.equals(defaultStatus)) {
log.warn("Status for userId: " + userId + " was not updated because they didn't enter anything.");
return;
}
//save status from userProfile
if(statusLogic.setUserStatus(userId, statusMessage)) {
log.info("Saved status for: " + userId);
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_STATUS_UPDATE, "/profile/"+userId, true);
//update twitter
externalIntegrationLogic.sendMessageToTwitter(userId, statusMessage);
//repaint status component
ProfileStatusRenderer newStatus = new ProfileStatusRenderer("status", userId, null, "tiny");
newStatus.setOutputMarkupId(true);
status.replaceWith(newStatus);
newStatus.setVisible(true);
//also show the clear link
clearLink.setVisible(true);
if(target != null) {
target.addComponent(newStatus);
target.addComponent(clearLink);
status=newStatus; //update reference
//reset the field
target.appendJavascript("autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');");
}
} else {
log.error("Couldn't save status for: " + userId);
String js = "alert('Failed to save status. If the problem persists, contact your system administrator.');";
target.prependJavascript(js);
}
}
};
submitButton.setModel(new ResourceModel("button.sayit"));
form.add(submitButton);
//add form to container
statusFormContainer.add(form);
//if not editable, hide the entire form
if(!editable) {
statusFormContainer.setVisible(false);
}
add(statusFormContainer);
}
}
| true | true | public MyStatusPanel(String id, UserProfile userProfile) {
super(id);
log.debug("MyStatusPanel()");
//get info
final String displayName = userProfile.getDisplayName();
final String userId = userProfile.getUserUuid();
//if superUser and proxied, can't update
boolean editable = true;
if(sakaiProxy.isSuperUserAndProxiedToUser(userId)) {
editable = false;
}
//name
Label profileName = new Label("profileName", displayName);
add(profileName);
//status component
status = new ProfileStatusRenderer("status", userId, null, "tiny");
status.setOutputMarkupId(true);
add(status);
WebMarkupContainer statusFormContainer = new WebMarkupContainer("statusFormContainer");
//setup SimpleText object to back the single form field
StringModel stringModel = new StringModel();
//status form
Form form = new Form("form", new Model(stringModel));
form.setOutputMarkupId(true);
//status field
final TextField statusField = new TextField("message", new PropertyModel(stringModel, "string"));
statusField.setOutputMarkupPlaceholderTag(true);
form.add(statusField);
//link the status textfield field with the focus/blur function via this dynamic js
//also link with counter
StringHeaderContributor statusJavascript = new StringHeaderContributor(
"<script type=\"text/javascript\">" +
"$(document).ready( function(){" +
"autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');" +
"countChars('#" + statusField.getMarkupId() + "');" +
"});" +
"</script>");
add(statusJavascript);
//clear link
final AjaxFallbackLink clearLink = new AjaxFallbackLink("clearLink") {
private static final long serialVersionUID = 1L;
public void onClick(AjaxRequestTarget target) {
//clear status, hide and repaint
if(statusLogic.clearUserStatus(userId)) {
status.setVisible(false); //hide status
this.setVisible(false); //hide clear link
target.addComponent(status);
target.addComponent(this);
target.appendJavascript("autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');");
//target.addComponent(statusField);
}
}
};
clearLink.setOutputMarkupPlaceholderTag(true);
clearLink.add(new Label("clearLabel",new ResourceModel("link.status.clear")));
//set visibility of clear link based on status and if it's editable
if(!status.isVisible() || !editable) {
clearLink.setVisible(false);
}
add(clearLink);
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
private static final long serialVersionUID = 1L;
protected void onSubmit(AjaxRequestTarget target, Form form) {
//get the backing model
StringModel stringModel = (StringModel) form.getModelObject();
//get userId from sakaiProxy
String userId = sakaiProxy.getCurrentUserId();
//get the status. if its the default text, do not update, although we should clear the model
String statusMessage = stringModel.getString().trim();
if(statusMessage.equals(defaultStatus)) {
log.warn("Status for userId: " + userId + " was not updated because they didn't enter anything.");
return;
}
//save status from userProfile
if(statusLogic.setUserStatus(userId, statusMessage)) {
log.info("Saved status for: " + userId);
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_STATUS_UPDATE, "/profile/"+userId, true);
//update twitter
externalIntegrationLogic.sendMessageToTwitter(userId, statusMessage);
//repaint status component
ProfileStatusRenderer newStatus = new ProfileStatusRenderer("status", userId, null, "tiny");
newStatus.setOutputMarkupId(true);
status.replaceWith(newStatus);
newStatus.setVisible(true);
//also show the clear link
clearLink.setVisible(true);
if(target != null) {
target.addComponent(newStatus);
target.addComponent(clearLink);
status=newStatus; //update reference
//reset the field
target.appendJavascript("autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');");
}
} else {
log.error("Couldn't save status for: " + userId);
String js = "alert('Failed to save status. If the problem persists, contact your system administrator.');";
target.prependJavascript(js);
}
}
};
submitButton.setModel(new ResourceModel("button.sayit"));
form.add(submitButton);
//add form to container
statusFormContainer.add(form);
//if not editable, hide the entire form
if(!editable) {
statusFormContainer.setVisible(false);
}
add(statusFormContainer);
}
| public MyStatusPanel(String id, UserProfile userProfile) {
super(id);
log.debug("MyStatusPanel()");
//get info
final String displayName = userProfile.getDisplayName();
final String userId = userProfile.getUserUuid();
//if superUser and proxied, can't update
boolean editable = true;
if(sakaiProxy.isSuperUserAndProxiedToUser(userId)) {
editable = false;
}
//name
Label profileName = new Label("profileName", displayName);
add(profileName);
//status component
status = new ProfileStatusRenderer("status", userId, null, "tiny");
status.setOutputMarkupId(true);
add(status);
WebMarkupContainer statusFormContainer = new WebMarkupContainer("statusFormContainer");
//setup SimpleText object to back the single form field
StringModel stringModel = new StringModel();
//status form
Form form = new Form("form", new Model(stringModel));
form.setOutputMarkupId(true);
//status field
final TextField statusField = new TextField("message", new PropertyModel(stringModel, "string"));
statusField.setOutputMarkupPlaceholderTag(true);
form.add(statusField);
//link the status textfield field with the focus/blur function via this dynamic js
//also link with counter
StringHeaderContributor statusJavascript = new StringHeaderContributor(
"<script type=\"text/javascript\">" +
"$(document).ready( function(){" +
"autoFill('#" + statusField.getMarkupId() + "', '" + defaultStatus + "');" +
"countChars('#" + statusField.getMarkupId() + "');" +
"});" +
"</script>");
add(statusJavascript);
//clear link
final AjaxFallbackLink clearLink = new AjaxFallbackLink("clearLink") {
private static final long serialVersionUID = 1L;
public void onClick(AjaxRequestTarget target) {
//clear status, hide and repaint
if(statusLogic.clearUserStatus(userId)) {
status.setVisible(false); //hide status
this.setVisible(false); //hide clear link
target.addComponent(status);
target.addComponent(this);
target.appendJavascript("autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');");
//target.addComponent(statusField);
}
}
};
clearLink.setOutputMarkupPlaceholderTag(true);
clearLink.add(new Label("clearLabel",new ResourceModel("link.status.clear")));
//set visibility of clear link based on status and if it's editable
if(!status.isVisible() || !editable) {
clearLink.setVisible(false);
}
add(clearLink);
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
private static final long serialVersionUID = 1L;
protected void onSubmit(AjaxRequestTarget target, Form form) {
//get the backing model
StringModel stringModel = (StringModel) form.getModelObject();
//get userId from sakaiProxy
String userId = sakaiProxy.getCurrentUserId();
//get the status. if its the default text, do not update, although we should clear the model
String statusMessage = stringModel.getString().trim();
if(statusMessage.equals(defaultStatus)) {
log.warn("Status for userId: " + userId + " was not updated because they didn't enter anything.");
return;
}
//save status from userProfile
if(statusLogic.setUserStatus(userId, statusMessage)) {
log.info("Saved status for: " + userId);
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_STATUS_UPDATE, "/profile/"+userId, true);
//update twitter
externalIntegrationLogic.sendMessageToTwitter(userId, statusMessage);
//repaint status component
ProfileStatusRenderer newStatus = new ProfileStatusRenderer("status", userId, null, "tiny");
newStatus.setOutputMarkupId(true);
status.replaceWith(newStatus);
newStatus.setVisible(true);
//also show the clear link
clearLink.setVisible(true);
if(target != null) {
target.addComponent(newStatus);
target.addComponent(clearLink);
status=newStatus; //update reference
//reset the field
target.appendJavascript("autoFill($('#" + statusField.getMarkupId() + "'), '" + defaultStatus + "');");
}
} else {
log.error("Couldn't save status for: " + userId);
String js = "alert('Failed to save status. If the problem persists, contact your system administrator.');";
target.prependJavascript(js);
}
}
};
submitButton.setModel(new ResourceModel("button.sayit"));
form.add(submitButton);
//add form to container
statusFormContainer.add(form);
//if not editable, hide the entire form
if(!editable) {
statusFormContainer.setVisible(false);
}
add(statusFormContainer);
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java
index 4f4698eed..a72cb4e68 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/commands/CommandRegistry.java
@@ -1,1901 +1,1901 @@
package net.aufdemrand.denizen.scripts.commands;
import java.util.HashMap;
import java.util.Map;
import net.aufdemrand.denizen.Denizen;
import net.aufdemrand.denizen.interfaces.dRegistry;
import net.aufdemrand.denizen.interfaces.RegistrationableInstance;
import net.aufdemrand.denizen.scripts.commands.core.*;
import net.aufdemrand.denizen.scripts.commands.item.*;
import net.aufdemrand.denizen.scripts.commands.player.*;
import net.aufdemrand.denizen.scripts.commands.server.*;
import net.aufdemrand.denizen.scripts.commands.entity.*;
import net.aufdemrand.denizen.scripts.commands.npc.*;
import net.aufdemrand.denizen.scripts.commands.world.*;
import net.aufdemrand.denizen.utilities.debugging.dB;
public class CommandRegistry implements dRegistry {
public Denizen denizen;
public CommandRegistry(Denizen denizen) {
this.denizen = denizen;
}
private Map<String, AbstractCommand> instances = new HashMap<String, AbstractCommand>();
private Map<Class<? extends AbstractCommand>, String> classes = new HashMap<Class<? extends AbstractCommand>, String>();
@Override
public boolean register(String commandName, RegistrationableInstance commandInstance) {
this.instances.put(commandName.toUpperCase(), (AbstractCommand) commandInstance);
this.classes.put(((AbstractCommand) commandInstance).getClass(), commandName.toUpperCase());
return true;
}
@Override
public Map<String, AbstractCommand> list() {
return instances;
}
@Override
public AbstractCommand get(String commandName) {
if (instances.containsKey(commandName.toUpperCase())) return instances.get(commandName.toUpperCase());
else return null;
}
@Override
public <T extends RegistrationableInstance> T get(Class<T> clazz) {
if (classes.containsKey(clazz)) return clazz.cast(instances.get(classes.get(clazz)));
else return null;
}
@Override
public void registerCoreMembers() {
// <--[command]
// @Name Age
// @Usage age [<entity>|...] (adult/baby/<age>) (lock)
// @Required 1
- // @Stable 1.0
+ // @Stable stable
// @Short Sets the ages of a list of entities, optionally locking them in those ages.
// @Author David Cernat
// @Description
// Some living entity types are 'ageable' which can affect an entities ability to breed, or whether they appear
// as a baby or an adult. Using the 'age' command allows modification of an entity's age.
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AgeCommand.class,
"AGE", "age [<entity>|...] (adult/baby/<age>) (lock)", 1);
// <--[command]
// @Name Anchor
// @Usage anchor [id:<name>] [assume/remove/add <location>/walkto/walknear (r:#)]
// @Required 2
// @Stable stable
// @Short Controls a NPC's Anchor Trait.
// @Author aufdemrand
// @Description
// The anchor system inside Citizens2 allows locations to be 'bound' to a NPC, saved by an 'id'. The anchor
// command can add and remove new anchors, as well as the ability to teleport NPCs to anchors with the 'assume'
// argument.
// The Anchors Trait can also be used as a sort of 'waypoints' system. For ease of use, the anchor command
// provides function for NPCs to walk to or walk near an anchor.
// As the Anchor command is a NPC specific command, a valid npc object must be referenced in the script entry.
// If none is provided by default, the use of the 'npc:n@id' argument, replacing the id with the npcid of the
// NPC desired, can create a link, or alternatively override the default linked npc.
// @Tags
// <[email protected][anchor_name]>
// @Usage
// Use to add and remove anchors to a npc.
// - define location_name <context.message>
// - chat "I have saved this location as %location_name%.'
// - anchor add <npc.location> "id:%location_name%"
// @Usage
// Use to make a NPC walk to or walk near a saved anchor.
// - anchor walkto i:waypoint_1
// - anchor walknear i:waypoint_2 r:5
// -->
registerCoreMember(AnchorCommand.class,
"ANCHOR", "anchor [id:<name>] [assume/remove/add <location>/walkto/walknear (r:#)]", 2);
// <--[command]
// @Name Animate
// @Usage animate [<entity>|...] [animation:<name>]
// @Required 1
// @Stable stable
// @Short Makes a list of entities perform a certain animation.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnimateCommand.class,
"ANIMATE", "animate [<entity>|...] [animation:<name>]", 1);
// <--[command]
// @Name AnimateChest
// @Usage animatechest [<location>] ({open}/close) (sound:{true}/false)
// @Required 1
// @Stable unstable
// @Short Makes a chest open or close.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnimateChestCommand.class,
"ANIMATECHEST", "animatechest [<location>] ({open}/close) (sound:{true}/false)", 1);
// <--[command]
// @Name Announce
// @Usage announce ["<text>"] (to_ops) (to_flagged:<flag>) (format:<name>)
// @Required 1
// @Stable stable
// @Short Announces a message for everyone online to read.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnnounceCommand.class,
"ANNOUNCE", "announce [\"<text>\"] (to_ops) (to_flagged:<flag>) (format:<name>)", 1);
// <--[command]
// @Name Assignment
// @Usage assignment [{set}/remove] (script:<name>)
// @Required 1
// @Stable unstable
// @Short Changes an NPC's assignment.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(AssignmentCommand.class,
"ASSIGNMENT", "assignment [{set}/remove] (script:<name>)", 1);
// <--[command]
// @Name Attack
// @Usage attack (cancel) (<entity>|...) (target:<entity>)
// @Required 0
// @Stable stable
// @Short Makes a list of entities attack a target.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AttackCommand.class,
"ATTACK", "attack (cancel) (<entity>|...) (target:<entity>)", 0);
// <--[command]
// @Name Break
// @Usage break [<location>] (entity:<entity>) (radius:<#.#>)
// @Required 1
// @Stable unstable
// @Short Makes the NPC walk over and break a block. (Doesn't work!)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(BreakCommand.class,
"BREAK", "break [<location>] (entity:<entity>) (radius:<#.#>)", 1);
// <--[command]
// @Name Burn
// @Usage burn [<entity>|...] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Sets a list of entities on fire.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_time>
// @Usage
// Todo
// -->
registerCoreMember(BurnCommand.class,
"BURN", "burn [<entity>|...] (duration:<value>)", 1);
// <--[command]
// @Name Cast, Potion
// @Usage cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)
// @Required 1
// @Stable Stable
// @Short Casts a potion effect to a list of entities.
// @Author aufdemrand, Jeebiss, Morphan1
// @Description
// Casts or removes a potion effect to or from a list of entities. If you don't specify a duration,
// it defaults to 60 seconds. If you don't specify a power level, it defaults to 1.
// @Tags
// <[email protected]_effect[<effect>]> will return true if the entity has an effect.
// @Usage
// Use to apply an effect to an entity
// - potion jump <player> d:120 p:3
// - narrate "You have been given the temporary ability to jump like a kangaroo."
// @Usage
// Use to remove an effect from an entity
// - if <[email protected]_effect[jump]> {
// - potion jump remove <player>
// }
//
// -->
registerCoreMember(CastCommand.class,
"CAST, POTION", "cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)", 1);
// <--[command]
// @Name Chat
// @Usage chat ["<text>"] (targets:<entity>|...)
// @Required 1
// @Stable stable
// @Short Causes the NPC to send a chat message to nearby players.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ChatCommand.class,
"CHAT", "chat [\"<text>\"] (targets:<entity>|...)", 1);
// <--[command]
// @Name ChunkLoad
// @Usage chunkload ({add}/remove/removeall) [<location>] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Keeps a chunk actively loaded and allowing NPC activity.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ChunkLoadCommand.class,
"CHUNKLOAD", "chunkload ({add}/remove/removeall) [<location>] (duration:<value>)", 1);
// <--[command]
// @Name Compass
// @Usage compass [<location>]
// @Required 1
// @Stable stable
// @Short Redirects the player's compass to target the given location.
// @Author mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(CompassCommand.class,
"COMPASS", "compass [<location>]", 1);
// <--[command]
// @Name Cooldown
// @Usage cooldown [<duration>] (global) (s:<script>)
// @Required 1
// @Stable stable
// @Short Temporarily disables a script-container from meeting requirements.
// @Author aufdemrand
// @Description
// Cools down a script-container. If an interact-container, when on cooldown, scripts will not pass a
// requirements check allowing the next highest priority script to trigger. If any other type of script, a
// manual requirements check (<s@script_name.requirements.check>) will also return false until the cooldown
// period is completed. Cooldown requires a type (player or global), a script, and a duration. It also requires
// a valid link to a dPlayer if using player-type cooldown.
//
// Cooldown periods are persistent through a server restart as they are saved in the saves.yml.
// @Tags
// <s@script_name.cooled_down[player]> will return whether the script is cooled down
// <s@script_name.cooldown> will return the duration of the cooldown in progress.
// <[email protected]> will also check script cooldown, as well as any requirements.
// @Usage
// Use to keep the current interact script from meeting requirements.
// - cooldown 20m
// @Usage
// Use to keep a player from activating a script for a specified duration.
// - cooldown 11h s:s@bonus_script
// - cooldown 5s s:s@hit_indicator
// @Usage
// Use the 'global' argument to indicate the script to be on cooldown for all players.
// - cooldown global 24h s:s@daily_treasure_offering
// -->
registerCoreMember(CooldownCommand.class,
"COOLDOWN", "cooldown [<duration>] (global) (s:<script>)", 1);
// <--[command]
// @Name CopyBlock
// @Usage copyblock [location:<location>] [to:<location>]
// @Required 1
// @Stable unstable
// @Short Copies a block to another location, keeping all metadata.
// @Author aufdemrand, David Cernat
// @Description
// Todo
// @Tags
// <[email protected]. * >
// @Usage
// Todo
// -->
registerCoreMember(CopyBlockCommand.class,
"COPYBLOCK", "copyblock [location:<location>] [to:<location>]", 1);
// <--[command]
// @Name CreateWorld
// @Usage createworld [<name>] (g:<generator>)
// @Required 1
// @Stable unstable
// @Short Creates a new world
// @Author Todo
// @Description
// Todo
// @Tags
// <server.list_worlds>
// @Usage
// Todo
// -->
registerCoreMember(CreateWorldCommand.class,
"CREATEWORLD", "createworld [<name>] (g:<generator>)", 1);
// <--[command]
// @Name Define
// @Usage define [<id>] [<value>]
// @Required 2
// @Stable stable
// @Short Creates a temporary variable inside a script queue.
// @Author aufdemrand
//
// @Description
// Definitions are queue-level (or script-level) 'variables' that can be used throughout a script, once
// defined, by using %'s around the definition id/name. Definitions are only valid on the current queue and are
// not transferred to any new queues constructed within the script, such as a 'run' command, without explicitly
// specifying to do so.
//
// Definitions are lighter and faster than creating a temporary flag, but unlike flags, are only a single entry,
// that is, you can't add or remove from the definition, but you can re-create it if you wish to specify a new
// value. Definitions are also automatically destroyed when the queue is completed, so there is no worry for
// leaving unused data hanging around.
//
// Definitions are also resolved before replaceable tags, meaning you can use them within tags, even as an
// attribute. ie. <%player%.name>
//
// @Tags
// %DefinedItem%
// @Usage
// Use to make complex tags look less complex, and scripts more readable.
// - narrate 'You invoke your power of notice...'
// - define range '<player.flag[range_level].mul[3]>'
// - define blocks '<player.flag[noticeable_blocks>'
// - narrate '[NOTICE] You have noticed <player.location.find.blocks[%blocks%].within[%range].size>
// blocks in the area that may be of interest.'
//
// @Usage
// Use to keep the value of a replaceable tag that you might use many times within a single script. Definitions
// can be faster and cleaner than reusing a replaceable tag over and over.
// - define arg1 <c.args.get[1]>
// - if %arg1% == hello narrate 'Hello!'
// - if %arg1% == goodbye narrate 'Goodbye!'
//
// @Usage
// Use to pass some important information (arguments) on to another queue.
// - run 'new_task' d:hello|world
// 'new_task' now has some definitions, %1% and %2%, that contains the contents specified, 'hello' and 'world'.
//
// -->
registerCoreMember(DefineCommand.class,
"DEFINE", "define [<id>] [<value>]", 2);
// <--[command]
// @Name Determine
// @Usage determine [<value>]
// @Required 1
// @Stable stable
// @Short Sets the outcome of an event.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DetermineCommand.class,
"DETERMINE", "determine [<value>]", 1);
// <--[command]
// @Name Disengage
// @Usage disengage (npc:<npc>)
// @Required 0
// @Stable stable
// @Short Enables a NPCs triggers that have been temporarily disabled by the engage command.
// @Author aufdemrand
//
// @Description
// Re-enables any toggled triggers that have been disabled by disengage. Using
// disengage inside scripts must have a NPC to reference, or one may be specified
// by supplying a valid dNPC object with the npc argument.
//
// This is mostly regarded as an 'interact script command', though it may be used inside
// other script types. This is because disengage works with the trigger system, which is an
// interact script-container feature.
//
// NPCs that are interacted with while engaged will fire an 'on unavailable' assignment
// script-container action.
//
// @Tags
// none
// @Usage
// Use to reenable a NPC's triggers, disabled via 'engage'.
// - engage
// - chat 'Be right there!'
// - walkto <player.location>
// - wait 5s
// - disengage
//
// -->
registerCoreMember(DisengageCommand.class,
"DISENGAGE", "disengage (npc:<npc>)", 0);
// <--[command]
// @Name DisplayItem
// @Usage displayitem [<item>] [<location>] (duration:<value>)
// @Required 2
// @Stable Todo
// @Short Makes a non-touchable item spawn for players to view.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DisplayItemCommand.class,
"DISPLAYITEM", "displayitem [<item>] [<location>] (duration:<value>)", 2);
// <--[command]
// @Name Drop
// @Usage drop [<item>/<entity>/xp] [<location>] (qty:<#>)
// @Required 1
// @Stable stable
// @Short Drops an item for players to pick up.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DropCommand.class,
"DROP", "drop [<item>/<entity>/xp] [<location>] (qty:<#>)", 1);
// <--[command]
// @Name Engage
// @Usage engage (<duration>) (npc:<npc>)
// @Required 0
// @Stable stable
// @Short Temporarily disables a NPCs toggled interact script-container triggers.
// @Author aufdemrand
//
// @Description
// Engaging a NPC will temporarily disable any interact script-container triggers. To reverse
// this behavior, use either the disengage command, or specify a duration in which the engage
// should timeout. Specifying an engage without a duration will render the NPC engaged until
// a disengage is used on the NPC. Engaging a NPC affects all players attempting to interact
// with the NPC.
//
// While engaged, all triggers and actions associated with triggers will not 'fire', except
// the 'on unavailable' assignment script-container action, which will fire for triggers that
// were enabled previous to the engage command.
//
// Engage can be useful when NPCs are carrying out a task that shouldn't be interrupted, or
// to provide a good way to avoid accidental 'retrigger'.
//
// @See Disengage Command
//
// @Tags
// <[email protected]> will return true if the NPC is currently engaged, false otherwise.
//
// @Usage
// Use to make a NPC appear 'busy'.
// - engage
// - chat 'Give me a few minutes while I mix you a potion!'
// - walkto <npc.anchor[mixing_station]>
// - wait 10s
// - walkto <npc.anchor[service_station]>
// - chat 'Here you go!'
// - give potion <player>
// - disengage
//
// @Usage
// Use to avoid 'retrigger'.
// - engage 5s
// - take quest_item
// - flag player finished_quests:->:super_quest
//
// -->
registerCoreMember(EngageCommand.class,
"ENGAGE", "engage (<duration>) (npc:<npc>)", 0);
// <--[command]
// @Name Engrave
// @Usage engrave (set/remove)
// @Required 0
// @Stable unstable
// @Short Locks an item to a player *does not work currently*
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(EngraveCommand.class,
"ENGRAVE", "engrave (set/remove)", 0);
// <--[command]
// @Name Equip
// @Usage equip (player/{npc}) (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)
// @Required 1
// @Stable unstable
// @Short Equips an item into the chosen inventory slot of the player or NPC.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(EquipCommand.class,
"EQUIP", "equip (player/{npc}) (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)", 1);
// <--[command]
// @Name Execute
// @Usage execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]
// @Required 2
// @Stable stable
// @Short Executes an arbitrary server command as if the player, NPC, or server typed it in.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ExecuteCommand.class,
"EXECUTE", "execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]", 2);
// <--[command]
// @Name Experience
// @Usage experience [{set}/give/take] (level) [<#>]
// @Required 2
// @Stable Todo
// @Short Gives or takes experience points to the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]_next_level>
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(ExperienceCommand.class,
"EXPERIENCE", "experience [{set}/give/take] (level) [<#>]", 2);
// <--[command]
// @Name Explode
// @Usage explode (power:<#.#>) (<location>) (fire) (breakblocks)
// @Required 0
// @Stable stable
// @Short Causes an explosion at the location.
// @Author Alain Blanquet
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ExplodeCommand.class,
"EXPLODE", "explode (power:<#.#>) (<location>) (fire) (breakblocks)", 0);
// <--[command]
// @Name Fail
// @Usage fail (script:<name>)
// @Required 0
// @Stable stable
// @Short Marks a script as having failed.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FailCommand.class,
"FAIL", "fail (script:<name>)", 0);
// <--[command]
// @Name Feed
// @Usage feed (amt:<#>) (target:<entity>|...)
// @Required 0
// @Stable unstable
// @Short Refills the player's food bar.
// @Author aufdemrand, Jeebiss
// @Description
// Todo
// @Tags
// <[email protected]_level>
// <[email protected]_level.formatted>
// @Usage
// Todo
// -->
registerCoreMember(FeedCommand.class,
"FEED", "feed (amt:<#>) (target:<entity>|...)", 0);
// <--[command]
// @Name Finish
// @Usage finish (script:<name>)
// @Required 0
// @Stable stable
// @Short Marks a script as having been completed successfully.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FinishCommand.class,
"FINISH", "finish (script:<name>)", 0);
// <--[command]
// @Name Firework
// @Usage firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)
// @Required 0
// @Stable Todo
// @Short Launches a firework.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FireworkCommand.class,
"FIREWORK", "firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)", 0);
// <--[command]
// @Name Fish
// @Usage fish (catchfish) (stop) (<location>) (catchpercent:<#>)
// @Required 1
// @Stable Todo
// @Short Causes an NPC to begin fishing
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FishCommand.class,
"FISH", "fish (catchfish) (stop) (<location>) (catchpercent:<#>)", 1);
// <--[command]
// @Name Flag
// @Usage flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Sets or modifies a flag on the player, NPC, or server.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <[email protected][<flag>]>
// <[email protected][<flag>]>
// <global.flag[<flag>]>
// @Usage
// Todo
// -->
registerCoreMember(FlagCommand.class,
"FLAG", "flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)", 1);
// <--[command]
// @Name Fly
// @Usage fly (cancel) [<entity>|...] (controller:<player>) (origin:<location>) (destinations:<location>|...) (speed:<#.#>) (rotationthreshold:<#.#>)
// @Required 1
// @Stable stable
// @Short Make an entity fly where its controller is looking or fly to waypoints.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FlyCommand.class,
"FLY", "fly (cancel) [<entity>|...] (controller:<player>) (origin:<location>) (destinations:<location>|...) (speed:<#.#>) (rotationthreshold:<#.#>)", 1);
// <--[command]
// @Name Follow
// @Usage follow (stop) (lead:<#.#>) (target:<entity>)
// @Required 0
// @Stable unstable
// @Short Causes the NPC to follow a target (Currently experiencing bugs with lead: )
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FollowCommand.class,
"FOLLOW", "follow (stop) (lead:<#.#>) (target:<entity>)", 0);
// <--[command]
// @Name ForEach
// @Usage foreach [<object>|...] [<commands>]
// @Required 2
// @Stable stable
// @Short Loops through a dList, running a set of commands for each item.
// @Author Morphan1, mcmonkey
//
// @Description
// Loops through a dList of any type. For each item in the dList, the specified commands will be ran for
// that item. To call the value of the item while in the loop, you can use %value%.
//
// @Tags
// None
// @Usage
// Use to run commands on multiple items.
// - foreach li@e@123|n@424|p@BobBarker {
// - announce "There's something at <%value%.location>!"
// }
//
// -->
registerCoreMember(ForEachCommand.class,
"FOREACH", "foreach [<object>|...] [<commands>]", 2);
// <--[command]
// @Name Give
// @Usage give [money/<item>|...] (qty:<#>) (engrave) (to:<inventory>)
// @Required 1
// @Stable stable
// @Short Gives the player an item or money.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(GiveCommand.class,
"GIVE", "give [money/<item>|...] (qty:<#>) (engrave) (to:<inventory>)", 1);
// <--[command]
// @Name Group
// @Usage group [add/remove] [<group>] (world:<name>)
// @Required 2
// @Stable Todo
// @Short Adds a player to or removes a player from a permissions group.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_group[<group>]>
// <[email protected]_group[<group>].global>
// <[email protected]_group[<group>].world>
// @Usage
// Todo
// -->
registerCoreMember(GroupCommand.class,
"GROUP", "group [add/remove] [<group>] (world:<name>)", 2);
// <--[command]
// @Name Head
// @Usage head (<entity>|...) [skin:<player>]
// @Required 1
// @Stable stable
// @Short Makes players or NPCs wear a specific player's head.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(HeadCommand.class,
"HEAD", "head (<entity>|...) [skin:<player>]", 1);
// <--[command]
// @Name Heal
// @Usage heal (<#.#>) (<entity>|...)
// @Required 0
// @Stable stable
// @Short Heals the player.
// @Author aufdemrand, Jeebiss, morphan1, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HealCommand.class,
"HEAL", "heal (<#.#>) (<entity>|...)", 0);
// <--[command]
// @Name Health
// @Usage health (target:player/{npc}) [<#>]
// @Required 1
// @Stable stable
// @Short Changes the target's maximum health.
// @Author mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HealthCommand.class,
"HEALTH", "health (target:player/{npc}) [<#>]", 1);
// <--[command]
// @Name Hurt
// @Usage hurt (<#.#>) (<entity>|...)
// @Required 0
// @Stable stable
// @Short Hurts the player.
// @Author aufdemrand, Jeebiss, morphan1, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HurtCommand.class,
"HURT", "hurt (<#.#>) (<entity>|...)", 0);
// <--[command]
// @Name If
// @Usage if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)
// @Required 2
// @Stable stable
// @Short Compares values, and runs one script if they match, or a different script if they don't match.
// @Author aufdemrand, David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(IfCommand.class,
"IF", "if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)", 2);
// <--[command]
// @Name Inventory
// @Usage inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] (destination:<inventory>) (origin:<inventory>)
// @Required 1
// @Stable stable
// @Short Edits the inventory of a player, NPC, or chest.
// @Author David Cernat, morphan1
// @Description
// Todo
// @Tags
// <player.inventory>
// <npc.inventory>
// <location.inventory>
// @Usage
// Todo
// -->
registerCoreMember(InventoryCommand.class,
"INVENTORY", "inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] (destination:<inventory>) (origin:<inventory>)", 1);
// <--[command]
// @Name Inject
// @Usage inject (locally) [<script>] (path:<name>) (instantly)
// @Required 1
// @Stable stable
// @Short Runs a script in the current ScriptQueue.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(InjectCommand.class,
"INJECT", "inject (locally) [<script>] (path:<name>) (instantly)", 1);
// <--[command]
// @Name Invisible
// @Usage invisible [player/npc] [state:true/false/toggle]
// @Required 2
// @Stable unstable
// @Short Makes the player or NPC turn invisible. (Does not fully work currently)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(InvisibleCommand.class,
"INVISIBLE", "invisible [player/npc] [state:true/false/toggle]", 2);
// <--[command]
// @Name Leash
// @Usage leash (cancel) [<entity>|...] (holder:<entity>/<location>)
// @Required 1
// @Stable stable
// @Short Sticks a leash on target entity, held by a fence post or another entity.
// @Author Alain Blanquet, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]_leashed>
// <[email protected]_leash_holder>
// @Usage
// Todo
// -->
registerCoreMember(LeashCommand.class,
"LEASH", "leash (cancel) [<entity>|...] (holder:<entity>/<location>)", 1);
// <--[command]
// @Name Listen
// @Usage listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)
// @Required 2
// @Stable unstable
// @Short Listens for the player achieving various actions and runs a script when they are completed.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ListenCommand.class,
"LISTEN", "listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)", 2);
// <--[command]
// @Name Log
// @Usage log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]
// @Required 2
// @Stable Todo
// @Short Logs some debugging info to a file.
// @Author spaceemotion
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(LogCommand.class,
"LOG", "log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]", 2);
// <--[command]
// @Name Look
// @Usage look (<entity>|...) [<location>] (duration:<duration>)
// @Required 1
// @Stable stable
// @Short Causes the NPC or other entity to look at a target location.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(LookCommand.class,
"LOOK", "look (<entity>|...) [<location>] (duration:<duration>)", 1);
// <--[command]
// @Name LookClose
// @Usage lookclose [state:true/false]
// @Required 1
// @Stable unstable
// @Short Toggles whether the NPC will automatically look at nearby players.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(LookcloseCommand.class,
"LOOKCLOSE", "lookclose [state:true/false]", 1);
// <--[command]
// @Name Midi
// @Usage midi (cancel) [<file>] (<location>/<entity>|...) (tempo:<#.#>)
// @Required 1
// @Stable stable
// @Short Plays a midi file at a given location or to a list of players using note block sounds.
// @Author David Cernat
// @Description
// This will fully load a midi song file stored in plugins/Denizen/midi/
// The file must be a valid midi file with the extension .mid
// It will continuously play the song as noteblock songs at the given location or group of players until the song ends.
// By default, this will play for the connected player only.
// @Tags
// None.
// @Usage
// Use to play a midi song file at a given location
// - midi file:Mysong <player.location>
//
// @Usage
// Use to play a midi song file at a given location to the specified player
// - midi file:Mysong <server.list_online_players>
// -->
registerCoreMember(MidiCommand.class,
"MIDI", "midi (cancel) [<file>] (<location>/<entity>|...) (tempo:<#.#>)", 1);
// <--[command]
// @Name Mount
// @Usage mount (cancel) [<entity>|...] (<location>)
// @Required 0
// @Stable stable
// @Short Mounts one entity onto another.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_vehicle>
// <[email protected]_inside_vehicle>
// @Usage
// Todo
// -->
registerCoreMember(MountCommand.class,
"MOUNT", "mount (cancel) [<entity>|...] (<location>)", 0);
// <--[command]
// @Name ModifyBlock
// @Usage modifyblock [<location>] [<material>] (radius:<#>) (height:<#>) (depth:<#>)
// @Required 2
// @Stable unstable
// @Short Changes a block's material.
// @Author Jeebiss
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(ModifyBlockCommand.class,
"MODIFYBLOCK", "modifyblock [<location>] [<material>] (radius:<#>) (height:<#>) (depth:<#>)", 2);
// <--[command]
// @Name Nameplate
// @Usage nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib
// @Required 1
// @Stable unstable
// @Short Changes something's nameplate, requires ProtocolLib (Unstable and broken!)
// @Author spaceemotion
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NameplateCommand.class,
"NAMEPLATE", "nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib", 1);
// <--[command]
// @Name Narrate
// @Usage narrate ["<text>"] (targets:<player>|...) (format:<name>)
// @Required 1
// @Stable stable
// @Short Shows some text to the player.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NarrateCommand.class,
"NARRATE", "narrate [\"<text>\"] (targets:<player>|...) (format:<name>)", 1);
// <--[command]
// @Name Note
// @Usage note [<Notable dObject>] [as:<name>]
// @Required 2
// @Stable unstable
// @Short Adds a new notable object.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NoteCommand.class,
"NOTE", "note [<Notable dObject>] [as:<name>]", 2);
// <--[command]
// @Name Oxygen
// @Usage oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]
// @Required 1
// @Stable unstable
// @Short Gives or takes breath from the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(OxygenCommand.class,
"OXYGEN", "oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]", 1);
// <--[command]
// @Name Pause
// @Usage pause [waypoints/navigation]
// @Required 1
// @Stable unstable
// @Short Pauses an NPC's navigation.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(PauseCommand.class,
"PAUSE", "pause [waypoints/navigation]", 1);
// <--[command]
// @Name PlayEffect
// @Usage playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)
// @Required 2
// @Stable stable
// @Short Plays a visible or audible effect at the location.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PlayEffectCommand.class,
"PLAYEFFECT", "playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)", 2);
// <--[command]
// @Name PlaySound
// @Usage playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)
// @Required 2
// @Stable stable
// @Short Plays a sound at the location.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PlaySoundCommand.class,
"PLAYSOUND", "playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)", 2);
// <--[command]
// @Name Permission
// @Usage permission [add/remove] [permission] (player:<name>) (group:<name>) (world:<name>)
// @Required 2
// @Stable unstable
// @Short Gives or takes a permission node to/from the player or group.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_permission[permission.node]>
// <[email protected]_permission[permission.node].global>
// <[email protected]_permission[permission.node].world>
// @Usage
// Todo
// -->
registerCoreMember(PermissionCommand.class,
"PERMISSION", "permission [add/remove] [permission] (player:<name>) (group:<name>) (world:<name>)", 2);
// <--[command]
// @Name Pose
// @Usage pose (player/npc) [id:<name>]
// @Required 1
// @Stable unstable
// @Short Rotates the player or NPC to match a pose.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PoseCommand.class,
"POSE", "pose (player/npc) [id:<name>]", 1);
// <--[command]
// @Name Push
// @Usage push [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (speed:<#.#>) (<duration>) (<script>)
// @Required 1
// @Stable mostly
// @Short Pushes entities through the air in a straight line.
// @Author David Cernat, mcmonkey
// @Description
// Pushes entities through the air in a straight line at a certain speed and for a certain duration, triggering a script when they hit an obstacle or stop flying.
// @Tags
// Todo
// @Usage
// Use to launch an arrow straight towards a target
// - push arrow destination:<player.location>
//
// @Usage
// Use to launch an entity into the air
// - push cow
//
// -->
registerCoreMember(PushCommand.class,
"PUSH", "push [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (speed:<#.#>) (<duration>) (<script>)", 1);
// <--[command]
// @Name Queue
// @Usage queue (queue:<id>) [clear/pause/resume/delay:<#>]
// @Required 1
// @Stable stable
// @Short Modifies the current state of a script queue.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(QueueCommand.class,
"QUEUE", "queue (queue:<id>) [clear/pause/resume/delay:<#>]", 1);
// <--[command]
// @Name Random
// @Usage random [<#>/{braced commands}]
// @Required 1
// @Stable stable
// @Short Selects a random choice from the following script commands.
// @Author aufdemrand, morphan1
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Use to choose randomly from the following commands
// - random 3
// - narrate "hi"
// - narrate "hello"
// - narrate "hey"
//
// @Usage
// Use to choose randomly from a braced set of commands
// - random {
// - narrate "hi"
// - narrate "hello"
// - narrate "hey"
// }
//
// -->
registerCoreMember(RandomCommand.class,
"RANDOM", "random [<#>/{braced commands}]", 1);
// <--[command]
// @Name Remove
// @Usage remove [<entity>|...] (region:<name>)
// @Required 0
// @Stable Todo
// @Short Despawns a list of entities.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_spawned>
// @Usage
// Todo
// -->
registerCoreMember(RemoveCommand.class,
"REMOVE", "remove [<entity>|...] (<world>) (region:<name>)", 0);
// <--[command]
// @Name Rename
// @Usage rename [<npc>] [<name>]
// @Required 1
// @Stable Todo
// @Short Renames an NPC.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(RenameCommand.class,
"RENAME", "rename [<npc>] [<name>]", 1);
// <--[command]
// @Name Repeat
// @Usage repeat [<amount>] [<commands>]
// @Required 1
// @Stable stable
// @Short Runs a series of braced commands several times.
// @Author morphan1, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RepeatCommand.class,
"REPEAT", "repeat [<amount>] [<commands>]", 1);
// <--[command]
// @Name Reset
// @Usage reset [fails/finishes/cooldown] (script:<name>)
// @Required 1
// @Stable unstable
// @Short Resets a script's fails, finishes, or cooldowns.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ResetCommand.class,
"RESET", "reset [fails/finishes/cooldown] (script:<name>)", 1);
// <--[command]
// @Name Rotate
// @Usage rotate (<entity>|...) (yaw:<value>) (pitch:<value>) (duration:<duration>) (frequency:<duration>)
// @Required 1
// @Stable stable
// @Short Rotates a list of entities.
// @Author David Cernat
// @Description
// Todo
// @Tags
// @Usage
// Todo
// -->
registerCoreMember(RotateCommand.class,
"ROTATE", "rotate (cancel) (<entity>|...) (yaw:<value>) (pitch:<value>) (duration:<duration>) (infinite/frequency:<duration>)", 0);
// <--[command]
// @Name Run
// @Usage run (locally) [<script>] (path:<name>) (as:<player>/<npc>) (def:<element>|...) (id:<name>) (instantly) (delay:<value>)
// @Required 1
// @Stable stable
// @Short Runs a script in a new ScriptQueue.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RunCommand.class,
"RUN", "run (locally) [<script>] (path:<name>) (as:<player>/<npc>) (def:<element>|...) (id:<name>) (instantly) (delay:<value>)", 1);
// <--[command]
// @Name RunTask
// @Deprecated This has been replaced by the Run command.
// @Usage runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)
// @Required 1
// @Stable unstable
// @Short Runs a task script.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RuntaskCommand.class,
"RUNTASK", "runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)", 1);
// <--[command]
// @Name Scoreboard
// @Usage scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)
// @Required 1
// @Stable unstable
// @Short Modifies a scoreboard (Not going to work much until Minecraft 1.7)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ScoreboardCommand.class,
"SCOREBOARD", "scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)", 1);
// <--[command]
// @Name Scribe
// @Usage scribe [script:<name>] (give/drop/equip) (<item>) (<location>)
// @Required 1
// @Stable Todo
// @Short Writes to a book.
// @Author Jeebiss
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ScribeCommand.class,
"SCRIBE", "scribe [script:<name>] (give/drop/equip) (<item>) (<location>)", 1);
// <--[command]
// @Name Shoot
// @Usage shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (height:<#.#>) (gravity:<#.#>) (script:<name>)
// @Required 1
// @Stable stable
// @Short Shoots an entity through the air up to a certain height.
// @Author David Cernat
// @Description
// Shoots an entity through the air up to a certain height, optionally using a custom gravity value and triggering a script on impact with a surface.
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ShootCommand.class,
"SHOOT", "shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (height:<#.#>) (gravity:<#.#>) (script:<name>)", 1);
// <--[command]
// @Name ShowFake
// @Usage showfake [<material>] [<location>|...] (d:<duration>{10s})
// @Required 2
// @Stable stable
// @Short Makes the player see a block change that didn't actually happen.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ShowFakeCommand.class,
"SHOWFAKE", "showfake [<material>] [<location>|...] (d:<duration>{10s})", 2);
// <--[command]
// @Name Sign
// @Usage sign (type:{sign_post}/wall_sign) ["<line>|..."] [<location>] (direction:n/e/w/s)
// @Required 1
// @Stable stable
// @Short Modifies a sign.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(SignCommand.class,
"SIGN", "sign (type:{sign_post}/wall_sign) [\"<line>|...\"] [<location>] (direction:n/e/w/s)", 1);
// <--[command]
// @Name Sit
// @Usage sit (<location>)
// @Required 0
// @Stable unstable
// @Short Causes the NPC to sit. (Does not currently work!)
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_contents>
// @Usage
// Todo
// -->
registerCoreMember(SitCommand.class,
"SIT", "sit (<location>)", 0);
// <--[command]
// @Name Spawn
// @Usage spawn [<entity>|...] (<location>) (target:<entity>)
// @Required 1
// @Stable stable
// @Short Spawns a list of entities at a certain location.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_spawned>
// <util.entity_is_spawned[<entity>]>
// @Usage
// Todo
// -->
registerCoreMember(SpawnCommand.class,
"SPAWN", "spawn [<entity>|...] (<location>) (target:<entity>)", 1);
// <--[command]
// @Name Stand
// @Usage stand
// @Required 0
// @Stable unstable
// @Short Causes the NPC to stand. (Does not currently work!)
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(StandCommand.class,
"STAND", "stand", 0);
// <--[command]
// @Name Strike
// @Usage strike (no_damage) [<location>]
// @Required 1
// @Stable stable
// @Short Strikes lightning down upon the location.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(StrikeCommand.class,
"STRIKE", "strike (no_damage) [<location>]", 1);
// <--[command]
// @Name Switch
// @Usage switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)
// @Required 1
// @Stable stable
// @Short Switches a lever.
// @Author aufdemrand, Jeebiss, David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(SwitchCommand.class,
"SWITCH", "switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)", 1);
// <--[command]
// @Name Take
// @Usage take [money/iteminhand/<item>|...] (qty:<#>) (from:<inventory>)
// @Required 1
// @Stable stable
// @Short Takes an item from the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_in_hand>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TakeCommand.class,
"TAKE", "take [money/iteminhand/<item>|...] (qty:<#>) (from:<inventory>)", 1);
// <--[command]
// @Name Teleport
// @Usage teleport (<entity>|...) [<location>]
// @Required 1
// @Stable stable
// @Short Teleports the player or NPC to a new location.
// @Author David Cernat, aufdemrand
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TeleportCommand.class,
"TELEPORT", "teleport (<entity>|...) [<location>]", 1);
// <--[command]
// @Name Time
// @Usage time [type:{global}/player] [<value>] (world:<name>)
// @Required 1
// @Stable Todo
// @Short Changes the current time in the minecraft world.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TimeCommand.class,
"TIME", "time [type:{global}/player] [<value>] (world:<name>)", 1);
// <--[command]
// @Name Trait
// @Usage trait (state:true/false/{toggle}) [<trait>]
// @Required 1
// @Stable Stable
// @Short Adds or removes a trait from an NPC.
// @Author Morphan1
// @Description
// Todo
// @Tags
// <[email protected]_trait[<trait>]>
// <[email protected]_traits>
// @Usage
// Todo
// -->
registerCoreMember(TraitCommand.class,
"TRAIT", "trait (state:true/false/{toggle}) [<trait>]", 1);
// <--[command]
// @Name Trigger
// @Usage trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)
// @Required 2
// @Stable stable
// @Short Enables or disables a trigger.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(TriggerCommand.class,
"TRIGGER", "trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)", 2);
// <--[command]
// @Name Viewer
// @Usage viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)
// @Required 1
// @Stable unstable
// @Short Creates a sign that auto-updates with information.
// @Author Morphan1
//
// @Description
// Creates a sign that auto-updates with information about a player, including their location, score, and
// whether they're logged in or not.
//
// @Tags
// None
//
// @Usage
// Create a sign that shows the location of a player on a wall
// - viewer player:ThatGuy create 113,76,-302,world id:PlayerLoc1 type:wall_sign display:location
//
// -->
registerCoreMember(ViewerCommand.class,
"VIEWER", "viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)", 2);
// <--[command]
// @Name Vulnerable
// @Usage vulnerable (state:{true}/false/toggle)
// @Required 0
// @Stable unstable
// @Short Sets whether an NPC is vulnerable.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(VulnerableCommand.class,
"VULNERABLE", "vulnerable (state:{true}/false/toggle)", 0);
// <--[command]
// @Name Wait
// @Usage wait (<duration>) (queue:<name>)
// @Required 0
// @Stable stable
// @Short Delays a script for a specified amount of time.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(WaitCommand.class,
"WAIT", "wait (<duration>) (queue:<name>)", 0);
// <--[command]
// @Name Walk, WalkTo
// @Usage walk [<location>] (speed:<#>) (auto_range)
// @Required 1
// @Stable stable
// @Short Causes the NPC to walk to another location.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <npc.navigator. * >
// @Usage
// Todo
// -->
registerCoreMember(WalkCommand.class,
"WALK, WALKTO", "walk [<location>] (speed:<#>) (auto_range)", 1);
// <--[command]
// @Name Weather
// @Usage weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)
// @Required 1
// @Stable Todo
// @Short Changes the current weather in the minecraft world.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(WeatherCommand.class,
"WEATHER", "weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)", 1);
// <--[command]
// @Name Yaml
// @Usage yaml [load/create/savefile:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]
// @Required 1
// @Stable Todo
// @Short Edits a YAML configuration file.
// @Author Todo
// @Description
// Todo
// @Tags
// <yaml[<idname>].contains[<path>]>
// <yaml[<idname>].read[<path>]>
// <yaml[<idname>].list_keys[<path>]>
// @Usage
// Todo
// -->
registerCoreMember(YamlCommand.class,
"YAML", "yaml [load/create/savefile:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]", 1);
// <--[command]
// @Name Zap
// @Usage zap (<script>:)[<step>] (<duration>)
// @Required 0
// @Stable stable
// @Short Changes the current script step.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ZapCommand.class,
"ZAP", "zap (<script>:)[<step>] (<duration>)", 0);
dB.echoApproval("Loaded core commands: " + instances.keySet().toString());
}
private <T extends AbstractCommand> void registerCoreMember(Class<T> cmd, String names, String hint, int args) {
for (String name : names.split(", ")) {
try {
cmd.newInstance().activate().as(name).withOptions(hint, args);
} catch(Exception e) {
dB.echoError("Could not register command " + name + ": " + e.getMessage());
if (dB.showStackTraces) e.printStackTrace();
}
}
}
@Override
public void disableCoreMembers() {
for (RegistrationableInstance member : instances.values())
try {
member.onDisable();
} catch (Exception e) {
dB.echoError("Unable to disable '" + member.getClass().getName() + "'!");
if (dB.showStackTraces) e.printStackTrace();
}
}
}
| true | true | public void registerCoreMembers() {
// <--[command]
// @Name Age
// @Usage age [<entity>|...] (adult/baby/<age>) (lock)
// @Required 1
// @Stable 1.0
// @Short Sets the ages of a list of entities, optionally locking them in those ages.
// @Author David Cernat
// @Description
// Some living entity types are 'ageable' which can affect an entities ability to breed, or whether they appear
// as a baby or an adult. Using the 'age' command allows modification of an entity's age.
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AgeCommand.class,
"AGE", "age [<entity>|...] (adult/baby/<age>) (lock)", 1);
// <--[command]
// @Name Anchor
// @Usage anchor [id:<name>] [assume/remove/add <location>/walkto/walknear (r:#)]
// @Required 2
// @Stable stable
// @Short Controls a NPC's Anchor Trait.
// @Author aufdemrand
// @Description
// The anchor system inside Citizens2 allows locations to be 'bound' to a NPC, saved by an 'id'. The anchor
// command can add and remove new anchors, as well as the ability to teleport NPCs to anchors with the 'assume'
// argument.
// The Anchors Trait can also be used as a sort of 'waypoints' system. For ease of use, the anchor command
// provides function for NPCs to walk to or walk near an anchor.
// As the Anchor command is a NPC specific command, a valid npc object must be referenced in the script entry.
// If none is provided by default, the use of the 'npc:n@id' argument, replacing the id with the npcid of the
// NPC desired, can create a link, or alternatively override the default linked npc.
// @Tags
// <[email protected][anchor_name]>
// @Usage
// Use to add and remove anchors to a npc.
// - define location_name <context.message>
// - chat "I have saved this location as %location_name%.'
// - anchor add <npc.location> "id:%location_name%"
// @Usage
// Use to make a NPC walk to or walk near a saved anchor.
// - anchor walkto i:waypoint_1
// - anchor walknear i:waypoint_2 r:5
// -->
registerCoreMember(AnchorCommand.class,
"ANCHOR", "anchor [id:<name>] [assume/remove/add <location>/walkto/walknear (r:#)]", 2);
// <--[command]
// @Name Animate
// @Usage animate [<entity>|...] [animation:<name>]
// @Required 1
// @Stable stable
// @Short Makes a list of entities perform a certain animation.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnimateCommand.class,
"ANIMATE", "animate [<entity>|...] [animation:<name>]", 1);
// <--[command]
// @Name AnimateChest
// @Usage animatechest [<location>] ({open}/close) (sound:{true}/false)
// @Required 1
// @Stable unstable
// @Short Makes a chest open or close.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnimateChestCommand.class,
"ANIMATECHEST", "animatechest [<location>] ({open}/close) (sound:{true}/false)", 1);
// <--[command]
// @Name Announce
// @Usage announce ["<text>"] (to_ops) (to_flagged:<flag>) (format:<name>)
// @Required 1
// @Stable stable
// @Short Announces a message for everyone online to read.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnnounceCommand.class,
"ANNOUNCE", "announce [\"<text>\"] (to_ops) (to_flagged:<flag>) (format:<name>)", 1);
// <--[command]
// @Name Assignment
// @Usage assignment [{set}/remove] (script:<name>)
// @Required 1
// @Stable unstable
// @Short Changes an NPC's assignment.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(AssignmentCommand.class,
"ASSIGNMENT", "assignment [{set}/remove] (script:<name>)", 1);
// <--[command]
// @Name Attack
// @Usage attack (cancel) (<entity>|...) (target:<entity>)
// @Required 0
// @Stable stable
// @Short Makes a list of entities attack a target.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AttackCommand.class,
"ATTACK", "attack (cancel) (<entity>|...) (target:<entity>)", 0);
// <--[command]
// @Name Break
// @Usage break [<location>] (entity:<entity>) (radius:<#.#>)
// @Required 1
// @Stable unstable
// @Short Makes the NPC walk over and break a block. (Doesn't work!)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(BreakCommand.class,
"BREAK", "break [<location>] (entity:<entity>) (radius:<#.#>)", 1);
// <--[command]
// @Name Burn
// @Usage burn [<entity>|...] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Sets a list of entities on fire.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_time>
// @Usage
// Todo
// -->
registerCoreMember(BurnCommand.class,
"BURN", "burn [<entity>|...] (duration:<value>)", 1);
// <--[command]
// @Name Cast, Potion
// @Usage cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)
// @Required 1
// @Stable Stable
// @Short Casts a potion effect to a list of entities.
// @Author aufdemrand, Jeebiss, Morphan1
// @Description
// Casts or removes a potion effect to or from a list of entities. If you don't specify a duration,
// it defaults to 60 seconds. If you don't specify a power level, it defaults to 1.
// @Tags
// <[email protected]_effect[<effect>]> will return true if the entity has an effect.
// @Usage
// Use to apply an effect to an entity
// - potion jump <player> d:120 p:3
// - narrate "You have been given the temporary ability to jump like a kangaroo."
// @Usage
// Use to remove an effect from an entity
// - if <[email protected]_effect[jump]> {
// - potion jump remove <player>
// }
//
// -->
registerCoreMember(CastCommand.class,
"CAST, POTION", "cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)", 1);
// <--[command]
// @Name Chat
// @Usage chat ["<text>"] (targets:<entity>|...)
// @Required 1
// @Stable stable
// @Short Causes the NPC to send a chat message to nearby players.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ChatCommand.class,
"CHAT", "chat [\"<text>\"] (targets:<entity>|...)", 1);
// <--[command]
// @Name ChunkLoad
// @Usage chunkload ({add}/remove/removeall) [<location>] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Keeps a chunk actively loaded and allowing NPC activity.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ChunkLoadCommand.class,
"CHUNKLOAD", "chunkload ({add}/remove/removeall) [<location>] (duration:<value>)", 1);
// <--[command]
// @Name Compass
// @Usage compass [<location>]
// @Required 1
// @Stable stable
// @Short Redirects the player's compass to target the given location.
// @Author mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(CompassCommand.class,
"COMPASS", "compass [<location>]", 1);
// <--[command]
// @Name Cooldown
// @Usage cooldown [<duration>] (global) (s:<script>)
// @Required 1
// @Stable stable
// @Short Temporarily disables a script-container from meeting requirements.
// @Author aufdemrand
// @Description
// Cools down a script-container. If an interact-container, when on cooldown, scripts will not pass a
// requirements check allowing the next highest priority script to trigger. If any other type of script, a
// manual requirements check (<s@script_name.requirements.check>) will also return false until the cooldown
// period is completed. Cooldown requires a type (player or global), a script, and a duration. It also requires
// a valid link to a dPlayer if using player-type cooldown.
//
// Cooldown periods are persistent through a server restart as they are saved in the saves.yml.
// @Tags
// <s@script_name.cooled_down[player]> will return whether the script is cooled down
// <s@script_name.cooldown> will return the duration of the cooldown in progress.
// <[email protected]> will also check script cooldown, as well as any requirements.
// @Usage
// Use to keep the current interact script from meeting requirements.
// - cooldown 20m
// @Usage
// Use to keep a player from activating a script for a specified duration.
// - cooldown 11h s:s@bonus_script
// - cooldown 5s s:s@hit_indicator
// @Usage
// Use the 'global' argument to indicate the script to be on cooldown for all players.
// - cooldown global 24h s:s@daily_treasure_offering
// -->
registerCoreMember(CooldownCommand.class,
"COOLDOWN", "cooldown [<duration>] (global) (s:<script>)", 1);
// <--[command]
// @Name CopyBlock
// @Usage copyblock [location:<location>] [to:<location>]
// @Required 1
// @Stable unstable
// @Short Copies a block to another location, keeping all metadata.
// @Author aufdemrand, David Cernat
// @Description
// Todo
// @Tags
// <[email protected]. * >
// @Usage
// Todo
// -->
registerCoreMember(CopyBlockCommand.class,
"COPYBLOCK", "copyblock [location:<location>] [to:<location>]", 1);
// <--[command]
// @Name CreateWorld
// @Usage createworld [<name>] (g:<generator>)
// @Required 1
// @Stable unstable
// @Short Creates a new world
// @Author Todo
// @Description
// Todo
// @Tags
// <server.list_worlds>
// @Usage
// Todo
// -->
registerCoreMember(CreateWorldCommand.class,
"CREATEWORLD", "createworld [<name>] (g:<generator>)", 1);
// <--[command]
// @Name Define
// @Usage define [<id>] [<value>]
// @Required 2
// @Stable stable
// @Short Creates a temporary variable inside a script queue.
// @Author aufdemrand
//
// @Description
// Definitions are queue-level (or script-level) 'variables' that can be used throughout a script, once
// defined, by using %'s around the definition id/name. Definitions are only valid on the current queue and are
// not transferred to any new queues constructed within the script, such as a 'run' command, without explicitly
// specifying to do so.
//
// Definitions are lighter and faster than creating a temporary flag, but unlike flags, are only a single entry,
// that is, you can't add or remove from the definition, but you can re-create it if you wish to specify a new
// value. Definitions are also automatically destroyed when the queue is completed, so there is no worry for
// leaving unused data hanging around.
//
// Definitions are also resolved before replaceable tags, meaning you can use them within tags, even as an
// attribute. ie. <%player%.name>
//
// @Tags
// %DefinedItem%
// @Usage
// Use to make complex tags look less complex, and scripts more readable.
// - narrate 'You invoke your power of notice...'
// - define range '<player.flag[range_level].mul[3]>'
// - define blocks '<player.flag[noticeable_blocks>'
// - narrate '[NOTICE] You have noticed <player.location.find.blocks[%blocks%].within[%range].size>
// blocks in the area that may be of interest.'
//
// @Usage
// Use to keep the value of a replaceable tag that you might use many times within a single script. Definitions
// can be faster and cleaner than reusing a replaceable tag over and over.
// - define arg1 <c.args.get[1]>
// - if %arg1% == hello narrate 'Hello!'
// - if %arg1% == goodbye narrate 'Goodbye!'
//
// @Usage
// Use to pass some important information (arguments) on to another queue.
// - run 'new_task' d:hello|world
// 'new_task' now has some definitions, %1% and %2%, that contains the contents specified, 'hello' and 'world'.
//
// -->
registerCoreMember(DefineCommand.class,
"DEFINE", "define [<id>] [<value>]", 2);
// <--[command]
// @Name Determine
// @Usage determine [<value>]
// @Required 1
// @Stable stable
// @Short Sets the outcome of an event.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DetermineCommand.class,
"DETERMINE", "determine [<value>]", 1);
// <--[command]
// @Name Disengage
// @Usage disengage (npc:<npc>)
// @Required 0
// @Stable stable
// @Short Enables a NPCs triggers that have been temporarily disabled by the engage command.
// @Author aufdemrand
//
// @Description
// Re-enables any toggled triggers that have been disabled by disengage. Using
// disengage inside scripts must have a NPC to reference, or one may be specified
// by supplying a valid dNPC object with the npc argument.
//
// This is mostly regarded as an 'interact script command', though it may be used inside
// other script types. This is because disengage works with the trigger system, which is an
// interact script-container feature.
//
// NPCs that are interacted with while engaged will fire an 'on unavailable' assignment
// script-container action.
//
// @Tags
// none
// @Usage
// Use to reenable a NPC's triggers, disabled via 'engage'.
// - engage
// - chat 'Be right there!'
// - walkto <player.location>
// - wait 5s
// - disengage
//
// -->
registerCoreMember(DisengageCommand.class,
"DISENGAGE", "disengage (npc:<npc>)", 0);
// <--[command]
// @Name DisplayItem
// @Usage displayitem [<item>] [<location>] (duration:<value>)
// @Required 2
// @Stable Todo
// @Short Makes a non-touchable item spawn for players to view.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DisplayItemCommand.class,
"DISPLAYITEM", "displayitem [<item>] [<location>] (duration:<value>)", 2);
// <--[command]
// @Name Drop
// @Usage drop [<item>/<entity>/xp] [<location>] (qty:<#>)
// @Required 1
// @Stable stable
// @Short Drops an item for players to pick up.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DropCommand.class,
"DROP", "drop [<item>/<entity>/xp] [<location>] (qty:<#>)", 1);
// <--[command]
// @Name Engage
// @Usage engage (<duration>) (npc:<npc>)
// @Required 0
// @Stable stable
// @Short Temporarily disables a NPCs toggled interact script-container triggers.
// @Author aufdemrand
//
// @Description
// Engaging a NPC will temporarily disable any interact script-container triggers. To reverse
// this behavior, use either the disengage command, or specify a duration in which the engage
// should timeout. Specifying an engage without a duration will render the NPC engaged until
// a disengage is used on the NPC. Engaging a NPC affects all players attempting to interact
// with the NPC.
//
// While engaged, all triggers and actions associated with triggers will not 'fire', except
// the 'on unavailable' assignment script-container action, which will fire for triggers that
// were enabled previous to the engage command.
//
// Engage can be useful when NPCs are carrying out a task that shouldn't be interrupted, or
// to provide a good way to avoid accidental 'retrigger'.
//
// @See Disengage Command
//
// @Tags
// <[email protected]> will return true if the NPC is currently engaged, false otherwise.
//
// @Usage
// Use to make a NPC appear 'busy'.
// - engage
// - chat 'Give me a few minutes while I mix you a potion!'
// - walkto <npc.anchor[mixing_station]>
// - wait 10s
// - walkto <npc.anchor[service_station]>
// - chat 'Here you go!'
// - give potion <player>
// - disengage
//
// @Usage
// Use to avoid 'retrigger'.
// - engage 5s
// - take quest_item
// - flag player finished_quests:->:super_quest
//
// -->
registerCoreMember(EngageCommand.class,
"ENGAGE", "engage (<duration>) (npc:<npc>)", 0);
// <--[command]
// @Name Engrave
// @Usage engrave (set/remove)
// @Required 0
// @Stable unstable
// @Short Locks an item to a player *does not work currently*
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(EngraveCommand.class,
"ENGRAVE", "engrave (set/remove)", 0);
// <--[command]
// @Name Equip
// @Usage equip (player/{npc}) (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)
// @Required 1
// @Stable unstable
// @Short Equips an item into the chosen inventory slot of the player or NPC.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(EquipCommand.class,
"EQUIP", "equip (player/{npc}) (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)", 1);
// <--[command]
// @Name Execute
// @Usage execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]
// @Required 2
// @Stable stable
// @Short Executes an arbitrary server command as if the player, NPC, or server typed it in.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ExecuteCommand.class,
"EXECUTE", "execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]", 2);
// <--[command]
// @Name Experience
// @Usage experience [{set}/give/take] (level) [<#>]
// @Required 2
// @Stable Todo
// @Short Gives or takes experience points to the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]_next_level>
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(ExperienceCommand.class,
"EXPERIENCE", "experience [{set}/give/take] (level) [<#>]", 2);
// <--[command]
// @Name Explode
// @Usage explode (power:<#.#>) (<location>) (fire) (breakblocks)
// @Required 0
// @Stable stable
// @Short Causes an explosion at the location.
// @Author Alain Blanquet
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ExplodeCommand.class,
"EXPLODE", "explode (power:<#.#>) (<location>) (fire) (breakblocks)", 0);
// <--[command]
// @Name Fail
// @Usage fail (script:<name>)
// @Required 0
// @Stable stable
// @Short Marks a script as having failed.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FailCommand.class,
"FAIL", "fail (script:<name>)", 0);
// <--[command]
// @Name Feed
// @Usage feed (amt:<#>) (target:<entity>|...)
// @Required 0
// @Stable unstable
// @Short Refills the player's food bar.
// @Author aufdemrand, Jeebiss
// @Description
// Todo
// @Tags
// <[email protected]_level>
// <[email protected]_level.formatted>
// @Usage
// Todo
// -->
registerCoreMember(FeedCommand.class,
"FEED", "feed (amt:<#>) (target:<entity>|...)", 0);
// <--[command]
// @Name Finish
// @Usage finish (script:<name>)
// @Required 0
// @Stable stable
// @Short Marks a script as having been completed successfully.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FinishCommand.class,
"FINISH", "finish (script:<name>)", 0);
// <--[command]
// @Name Firework
// @Usage firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)
// @Required 0
// @Stable Todo
// @Short Launches a firework.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FireworkCommand.class,
"FIREWORK", "firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)", 0);
// <--[command]
// @Name Fish
// @Usage fish (catchfish) (stop) (<location>) (catchpercent:<#>)
// @Required 1
// @Stable Todo
// @Short Causes an NPC to begin fishing
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FishCommand.class,
"FISH", "fish (catchfish) (stop) (<location>) (catchpercent:<#>)", 1);
// <--[command]
// @Name Flag
// @Usage flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Sets or modifies a flag on the player, NPC, or server.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <[email protected][<flag>]>
// <[email protected][<flag>]>
// <global.flag[<flag>]>
// @Usage
// Todo
// -->
registerCoreMember(FlagCommand.class,
"FLAG", "flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)", 1);
// <--[command]
// @Name Fly
// @Usage fly (cancel) [<entity>|...] (controller:<player>) (origin:<location>) (destinations:<location>|...) (speed:<#.#>) (rotationthreshold:<#.#>)
// @Required 1
// @Stable stable
// @Short Make an entity fly where its controller is looking or fly to waypoints.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FlyCommand.class,
"FLY", "fly (cancel) [<entity>|...] (controller:<player>) (origin:<location>) (destinations:<location>|...) (speed:<#.#>) (rotationthreshold:<#.#>)", 1);
// <--[command]
// @Name Follow
// @Usage follow (stop) (lead:<#.#>) (target:<entity>)
// @Required 0
// @Stable unstable
// @Short Causes the NPC to follow a target (Currently experiencing bugs with lead: )
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FollowCommand.class,
"FOLLOW", "follow (stop) (lead:<#.#>) (target:<entity>)", 0);
// <--[command]
// @Name ForEach
// @Usage foreach [<object>|...] [<commands>]
// @Required 2
// @Stable stable
// @Short Loops through a dList, running a set of commands for each item.
// @Author Morphan1, mcmonkey
//
// @Description
// Loops through a dList of any type. For each item in the dList, the specified commands will be ran for
// that item. To call the value of the item while in the loop, you can use %value%.
//
// @Tags
// None
// @Usage
// Use to run commands on multiple items.
// - foreach li@e@123|n@424|p@BobBarker {
// - announce "There's something at <%value%.location>!"
// }
//
// -->
registerCoreMember(ForEachCommand.class,
"FOREACH", "foreach [<object>|...] [<commands>]", 2);
// <--[command]
// @Name Give
// @Usage give [money/<item>|...] (qty:<#>) (engrave) (to:<inventory>)
// @Required 1
// @Stable stable
// @Short Gives the player an item or money.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(GiveCommand.class,
"GIVE", "give [money/<item>|...] (qty:<#>) (engrave) (to:<inventory>)", 1);
// <--[command]
// @Name Group
// @Usage group [add/remove] [<group>] (world:<name>)
// @Required 2
// @Stable Todo
// @Short Adds a player to or removes a player from a permissions group.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_group[<group>]>
// <[email protected]_group[<group>].global>
// <[email protected]_group[<group>].world>
// @Usage
// Todo
// -->
registerCoreMember(GroupCommand.class,
"GROUP", "group [add/remove] [<group>] (world:<name>)", 2);
// <--[command]
// @Name Head
// @Usage head (<entity>|...) [skin:<player>]
// @Required 1
// @Stable stable
// @Short Makes players or NPCs wear a specific player's head.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(HeadCommand.class,
"HEAD", "head (<entity>|...) [skin:<player>]", 1);
// <--[command]
// @Name Heal
// @Usage heal (<#.#>) (<entity>|...)
// @Required 0
// @Stable stable
// @Short Heals the player.
// @Author aufdemrand, Jeebiss, morphan1, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HealCommand.class,
"HEAL", "heal (<#.#>) (<entity>|...)", 0);
// <--[command]
// @Name Health
// @Usage health (target:player/{npc}) [<#>]
// @Required 1
// @Stable stable
// @Short Changes the target's maximum health.
// @Author mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HealthCommand.class,
"HEALTH", "health (target:player/{npc}) [<#>]", 1);
// <--[command]
// @Name Hurt
// @Usage hurt (<#.#>) (<entity>|...)
// @Required 0
// @Stable stable
// @Short Hurts the player.
// @Author aufdemrand, Jeebiss, morphan1, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HurtCommand.class,
"HURT", "hurt (<#.#>) (<entity>|...)", 0);
// <--[command]
// @Name If
// @Usage if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)
// @Required 2
// @Stable stable
// @Short Compares values, and runs one script if they match, or a different script if they don't match.
// @Author aufdemrand, David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(IfCommand.class,
"IF", "if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)", 2);
// <--[command]
// @Name Inventory
// @Usage inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] (destination:<inventory>) (origin:<inventory>)
// @Required 1
// @Stable stable
// @Short Edits the inventory of a player, NPC, or chest.
// @Author David Cernat, morphan1
// @Description
// Todo
// @Tags
// <player.inventory>
// <npc.inventory>
// <location.inventory>
// @Usage
// Todo
// -->
registerCoreMember(InventoryCommand.class,
"INVENTORY", "inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] (destination:<inventory>) (origin:<inventory>)", 1);
// <--[command]
// @Name Inject
// @Usage inject (locally) [<script>] (path:<name>) (instantly)
// @Required 1
// @Stable stable
// @Short Runs a script in the current ScriptQueue.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(InjectCommand.class,
"INJECT", "inject (locally) [<script>] (path:<name>) (instantly)", 1);
// <--[command]
// @Name Invisible
// @Usage invisible [player/npc] [state:true/false/toggle]
// @Required 2
// @Stable unstable
// @Short Makes the player or NPC turn invisible. (Does not fully work currently)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(InvisibleCommand.class,
"INVISIBLE", "invisible [player/npc] [state:true/false/toggle]", 2);
// <--[command]
// @Name Leash
// @Usage leash (cancel) [<entity>|...] (holder:<entity>/<location>)
// @Required 1
// @Stable stable
// @Short Sticks a leash on target entity, held by a fence post or another entity.
// @Author Alain Blanquet, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]_leashed>
// <[email protected]_leash_holder>
// @Usage
// Todo
// -->
registerCoreMember(LeashCommand.class,
"LEASH", "leash (cancel) [<entity>|...] (holder:<entity>/<location>)", 1);
// <--[command]
// @Name Listen
// @Usage listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)
// @Required 2
// @Stable unstable
// @Short Listens for the player achieving various actions and runs a script when they are completed.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ListenCommand.class,
"LISTEN", "listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)", 2);
// <--[command]
// @Name Log
// @Usage log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]
// @Required 2
// @Stable Todo
// @Short Logs some debugging info to a file.
// @Author spaceemotion
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(LogCommand.class,
"LOG", "log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]", 2);
// <--[command]
// @Name Look
// @Usage look (<entity>|...) [<location>] (duration:<duration>)
// @Required 1
// @Stable stable
// @Short Causes the NPC or other entity to look at a target location.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(LookCommand.class,
"LOOK", "look (<entity>|...) [<location>] (duration:<duration>)", 1);
// <--[command]
// @Name LookClose
// @Usage lookclose [state:true/false]
// @Required 1
// @Stable unstable
// @Short Toggles whether the NPC will automatically look at nearby players.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(LookcloseCommand.class,
"LOOKCLOSE", "lookclose [state:true/false]", 1);
// <--[command]
// @Name Midi
// @Usage midi (cancel) [<file>] (<location>/<entity>|...) (tempo:<#.#>)
// @Required 1
// @Stable stable
// @Short Plays a midi file at a given location or to a list of players using note block sounds.
// @Author David Cernat
// @Description
// This will fully load a midi song file stored in plugins/Denizen/midi/
// The file must be a valid midi file with the extension .mid
// It will continuously play the song as noteblock songs at the given location or group of players until the song ends.
// By default, this will play for the connected player only.
// @Tags
// None.
// @Usage
// Use to play a midi song file at a given location
// - midi file:Mysong <player.location>
//
// @Usage
// Use to play a midi song file at a given location to the specified player
// - midi file:Mysong <server.list_online_players>
// -->
registerCoreMember(MidiCommand.class,
"MIDI", "midi (cancel) [<file>] (<location>/<entity>|...) (tempo:<#.#>)", 1);
// <--[command]
// @Name Mount
// @Usage mount (cancel) [<entity>|...] (<location>)
// @Required 0
// @Stable stable
// @Short Mounts one entity onto another.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_vehicle>
// <[email protected]_inside_vehicle>
// @Usage
// Todo
// -->
registerCoreMember(MountCommand.class,
"MOUNT", "mount (cancel) [<entity>|...] (<location>)", 0);
// <--[command]
// @Name ModifyBlock
// @Usage modifyblock [<location>] [<material>] (radius:<#>) (height:<#>) (depth:<#>)
// @Required 2
// @Stable unstable
// @Short Changes a block's material.
// @Author Jeebiss
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(ModifyBlockCommand.class,
"MODIFYBLOCK", "modifyblock [<location>] [<material>] (radius:<#>) (height:<#>) (depth:<#>)", 2);
// <--[command]
// @Name Nameplate
// @Usage nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib
// @Required 1
// @Stable unstable
// @Short Changes something's nameplate, requires ProtocolLib (Unstable and broken!)
// @Author spaceemotion
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NameplateCommand.class,
"NAMEPLATE", "nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib", 1);
// <--[command]
// @Name Narrate
// @Usage narrate ["<text>"] (targets:<player>|...) (format:<name>)
// @Required 1
// @Stable stable
// @Short Shows some text to the player.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NarrateCommand.class,
"NARRATE", "narrate [\"<text>\"] (targets:<player>|...) (format:<name>)", 1);
// <--[command]
// @Name Note
// @Usage note [<Notable dObject>] [as:<name>]
// @Required 2
// @Stable unstable
// @Short Adds a new notable object.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NoteCommand.class,
"NOTE", "note [<Notable dObject>] [as:<name>]", 2);
// <--[command]
// @Name Oxygen
// @Usage oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]
// @Required 1
// @Stable unstable
// @Short Gives or takes breath from the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(OxygenCommand.class,
"OXYGEN", "oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]", 1);
// <--[command]
// @Name Pause
// @Usage pause [waypoints/navigation]
// @Required 1
// @Stable unstable
// @Short Pauses an NPC's navigation.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(PauseCommand.class,
"PAUSE", "pause [waypoints/navigation]", 1);
// <--[command]
// @Name PlayEffect
// @Usage playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)
// @Required 2
// @Stable stable
// @Short Plays a visible or audible effect at the location.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PlayEffectCommand.class,
"PLAYEFFECT", "playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)", 2);
// <--[command]
// @Name PlaySound
// @Usage playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)
// @Required 2
// @Stable stable
// @Short Plays a sound at the location.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PlaySoundCommand.class,
"PLAYSOUND", "playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)", 2);
// <--[command]
// @Name Permission
// @Usage permission [add/remove] [permission] (player:<name>) (group:<name>) (world:<name>)
// @Required 2
// @Stable unstable
// @Short Gives or takes a permission node to/from the player or group.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_permission[permission.node]>
// <[email protected]_permission[permission.node].global>
// <[email protected]_permission[permission.node].world>
// @Usage
// Todo
// -->
registerCoreMember(PermissionCommand.class,
"PERMISSION", "permission [add/remove] [permission] (player:<name>) (group:<name>) (world:<name>)", 2);
// <--[command]
// @Name Pose
// @Usage pose (player/npc) [id:<name>]
// @Required 1
// @Stable unstable
// @Short Rotates the player or NPC to match a pose.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PoseCommand.class,
"POSE", "pose (player/npc) [id:<name>]", 1);
// <--[command]
// @Name Push
// @Usage push [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (speed:<#.#>) (<duration>) (<script>)
// @Required 1
// @Stable mostly
// @Short Pushes entities through the air in a straight line.
// @Author David Cernat, mcmonkey
// @Description
// Pushes entities through the air in a straight line at a certain speed and for a certain duration, triggering a script when they hit an obstacle or stop flying.
// @Tags
// Todo
// @Usage
// Use to launch an arrow straight towards a target
// - push arrow destination:<player.location>
//
// @Usage
// Use to launch an entity into the air
// - push cow
//
// -->
registerCoreMember(PushCommand.class,
"PUSH", "push [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (speed:<#.#>) (<duration>) (<script>)", 1);
// <--[command]
// @Name Queue
// @Usage queue (queue:<id>) [clear/pause/resume/delay:<#>]
// @Required 1
// @Stable stable
// @Short Modifies the current state of a script queue.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(QueueCommand.class,
"QUEUE", "queue (queue:<id>) [clear/pause/resume/delay:<#>]", 1);
// <--[command]
// @Name Random
// @Usage random [<#>/{braced commands}]
// @Required 1
// @Stable stable
// @Short Selects a random choice from the following script commands.
// @Author aufdemrand, morphan1
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Use to choose randomly from the following commands
// - random 3
// - narrate "hi"
// - narrate "hello"
// - narrate "hey"
//
// @Usage
// Use to choose randomly from a braced set of commands
// - random {
// - narrate "hi"
// - narrate "hello"
// - narrate "hey"
// }
//
// -->
registerCoreMember(RandomCommand.class,
"RANDOM", "random [<#>/{braced commands}]", 1);
// <--[command]
// @Name Remove
// @Usage remove [<entity>|...] (region:<name>)
// @Required 0
// @Stable Todo
// @Short Despawns a list of entities.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_spawned>
// @Usage
// Todo
// -->
registerCoreMember(RemoveCommand.class,
"REMOVE", "remove [<entity>|...] (<world>) (region:<name>)", 0);
// <--[command]
// @Name Rename
// @Usage rename [<npc>] [<name>]
// @Required 1
// @Stable Todo
// @Short Renames an NPC.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(RenameCommand.class,
"RENAME", "rename [<npc>] [<name>]", 1);
// <--[command]
// @Name Repeat
// @Usage repeat [<amount>] [<commands>]
// @Required 1
// @Stable stable
// @Short Runs a series of braced commands several times.
// @Author morphan1, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RepeatCommand.class,
"REPEAT", "repeat [<amount>] [<commands>]", 1);
// <--[command]
// @Name Reset
// @Usage reset [fails/finishes/cooldown] (script:<name>)
// @Required 1
// @Stable unstable
// @Short Resets a script's fails, finishes, or cooldowns.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ResetCommand.class,
"RESET", "reset [fails/finishes/cooldown] (script:<name>)", 1);
// <--[command]
// @Name Rotate
// @Usage rotate (<entity>|...) (yaw:<value>) (pitch:<value>) (duration:<duration>) (frequency:<duration>)
// @Required 1
// @Stable stable
// @Short Rotates a list of entities.
// @Author David Cernat
// @Description
// Todo
// @Tags
// @Usage
// Todo
// -->
registerCoreMember(RotateCommand.class,
"ROTATE", "rotate (cancel) (<entity>|...) (yaw:<value>) (pitch:<value>) (duration:<duration>) (infinite/frequency:<duration>)", 0);
// <--[command]
// @Name Run
// @Usage run (locally) [<script>] (path:<name>) (as:<player>/<npc>) (def:<element>|...) (id:<name>) (instantly) (delay:<value>)
// @Required 1
// @Stable stable
// @Short Runs a script in a new ScriptQueue.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RunCommand.class,
"RUN", "run (locally) [<script>] (path:<name>) (as:<player>/<npc>) (def:<element>|...) (id:<name>) (instantly) (delay:<value>)", 1);
// <--[command]
// @Name RunTask
// @Deprecated This has been replaced by the Run command.
// @Usage runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)
// @Required 1
// @Stable unstable
// @Short Runs a task script.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RuntaskCommand.class,
"RUNTASK", "runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)", 1);
// <--[command]
// @Name Scoreboard
// @Usage scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)
// @Required 1
// @Stable unstable
// @Short Modifies a scoreboard (Not going to work much until Minecraft 1.7)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ScoreboardCommand.class,
"SCOREBOARD", "scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)", 1);
// <--[command]
// @Name Scribe
// @Usage scribe [script:<name>] (give/drop/equip) (<item>) (<location>)
// @Required 1
// @Stable Todo
// @Short Writes to a book.
// @Author Jeebiss
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ScribeCommand.class,
"SCRIBE", "scribe [script:<name>] (give/drop/equip) (<item>) (<location>)", 1);
// <--[command]
// @Name Shoot
// @Usage shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (height:<#.#>) (gravity:<#.#>) (script:<name>)
// @Required 1
// @Stable stable
// @Short Shoots an entity through the air up to a certain height.
// @Author David Cernat
// @Description
// Shoots an entity through the air up to a certain height, optionally using a custom gravity value and triggering a script on impact with a surface.
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ShootCommand.class,
"SHOOT", "shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (height:<#.#>) (gravity:<#.#>) (script:<name>)", 1);
// <--[command]
// @Name ShowFake
// @Usage showfake [<material>] [<location>|...] (d:<duration>{10s})
// @Required 2
// @Stable stable
// @Short Makes the player see a block change that didn't actually happen.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ShowFakeCommand.class,
"SHOWFAKE", "showfake [<material>] [<location>|...] (d:<duration>{10s})", 2);
// <--[command]
// @Name Sign
// @Usage sign (type:{sign_post}/wall_sign) ["<line>|..."] [<location>] (direction:n/e/w/s)
// @Required 1
// @Stable stable
// @Short Modifies a sign.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(SignCommand.class,
"SIGN", "sign (type:{sign_post}/wall_sign) [\"<line>|...\"] [<location>] (direction:n/e/w/s)", 1);
// <--[command]
// @Name Sit
// @Usage sit (<location>)
// @Required 0
// @Stable unstable
// @Short Causes the NPC to sit. (Does not currently work!)
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_contents>
// @Usage
// Todo
// -->
registerCoreMember(SitCommand.class,
"SIT", "sit (<location>)", 0);
// <--[command]
// @Name Spawn
// @Usage spawn [<entity>|...] (<location>) (target:<entity>)
// @Required 1
// @Stable stable
// @Short Spawns a list of entities at a certain location.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_spawned>
// <util.entity_is_spawned[<entity>]>
// @Usage
// Todo
// -->
registerCoreMember(SpawnCommand.class,
"SPAWN", "spawn [<entity>|...] (<location>) (target:<entity>)", 1);
// <--[command]
// @Name Stand
// @Usage stand
// @Required 0
// @Stable unstable
// @Short Causes the NPC to stand. (Does not currently work!)
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(StandCommand.class,
"STAND", "stand", 0);
// <--[command]
// @Name Strike
// @Usage strike (no_damage) [<location>]
// @Required 1
// @Stable stable
// @Short Strikes lightning down upon the location.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(StrikeCommand.class,
"STRIKE", "strike (no_damage) [<location>]", 1);
// <--[command]
// @Name Switch
// @Usage switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)
// @Required 1
// @Stable stable
// @Short Switches a lever.
// @Author aufdemrand, Jeebiss, David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(SwitchCommand.class,
"SWITCH", "switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)", 1);
// <--[command]
// @Name Take
// @Usage take [money/iteminhand/<item>|...] (qty:<#>) (from:<inventory>)
// @Required 1
// @Stable stable
// @Short Takes an item from the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_in_hand>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TakeCommand.class,
"TAKE", "take [money/iteminhand/<item>|...] (qty:<#>) (from:<inventory>)", 1);
// <--[command]
// @Name Teleport
// @Usage teleport (<entity>|...) [<location>]
// @Required 1
// @Stable stable
// @Short Teleports the player or NPC to a new location.
// @Author David Cernat, aufdemrand
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TeleportCommand.class,
"TELEPORT", "teleport (<entity>|...) [<location>]", 1);
// <--[command]
// @Name Time
// @Usage time [type:{global}/player] [<value>] (world:<name>)
// @Required 1
// @Stable Todo
// @Short Changes the current time in the minecraft world.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TimeCommand.class,
"TIME", "time [type:{global}/player] [<value>] (world:<name>)", 1);
// <--[command]
// @Name Trait
// @Usage trait (state:true/false/{toggle}) [<trait>]
// @Required 1
// @Stable Stable
// @Short Adds or removes a trait from an NPC.
// @Author Morphan1
// @Description
// Todo
// @Tags
// <[email protected]_trait[<trait>]>
// <[email protected]_traits>
// @Usage
// Todo
// -->
registerCoreMember(TraitCommand.class,
"TRAIT", "trait (state:true/false/{toggle}) [<trait>]", 1);
// <--[command]
// @Name Trigger
// @Usage trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)
// @Required 2
// @Stable stable
// @Short Enables or disables a trigger.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(TriggerCommand.class,
"TRIGGER", "trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)", 2);
// <--[command]
// @Name Viewer
// @Usage viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)
// @Required 1
// @Stable unstable
// @Short Creates a sign that auto-updates with information.
// @Author Morphan1
//
// @Description
// Creates a sign that auto-updates with information about a player, including their location, score, and
// whether they're logged in or not.
//
// @Tags
// None
//
// @Usage
// Create a sign that shows the location of a player on a wall
// - viewer player:ThatGuy create 113,76,-302,world id:PlayerLoc1 type:wall_sign display:location
//
// -->
registerCoreMember(ViewerCommand.class,
"VIEWER", "viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)", 2);
// <--[command]
// @Name Vulnerable
// @Usage vulnerable (state:{true}/false/toggle)
// @Required 0
// @Stable unstable
// @Short Sets whether an NPC is vulnerable.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(VulnerableCommand.class,
"VULNERABLE", "vulnerable (state:{true}/false/toggle)", 0);
// <--[command]
// @Name Wait
// @Usage wait (<duration>) (queue:<name>)
// @Required 0
// @Stable stable
// @Short Delays a script for a specified amount of time.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(WaitCommand.class,
"WAIT", "wait (<duration>) (queue:<name>)", 0);
// <--[command]
// @Name Walk, WalkTo
// @Usage walk [<location>] (speed:<#>) (auto_range)
// @Required 1
// @Stable stable
// @Short Causes the NPC to walk to another location.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <npc.navigator. * >
// @Usage
// Todo
// -->
registerCoreMember(WalkCommand.class,
"WALK, WALKTO", "walk [<location>] (speed:<#>) (auto_range)", 1);
// <--[command]
// @Name Weather
// @Usage weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)
// @Required 1
// @Stable Todo
// @Short Changes the current weather in the minecraft world.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(WeatherCommand.class,
"WEATHER", "weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)", 1);
// <--[command]
// @Name Yaml
// @Usage yaml [load/create/savefile:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]
// @Required 1
// @Stable Todo
// @Short Edits a YAML configuration file.
// @Author Todo
// @Description
// Todo
// @Tags
// <yaml[<idname>].contains[<path>]>
// <yaml[<idname>].read[<path>]>
// <yaml[<idname>].list_keys[<path>]>
// @Usage
// Todo
// -->
registerCoreMember(YamlCommand.class,
"YAML", "yaml [load/create/savefile:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]", 1);
// <--[command]
// @Name Zap
// @Usage zap (<script>:)[<step>] (<duration>)
// @Required 0
// @Stable stable
// @Short Changes the current script step.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ZapCommand.class,
"ZAP", "zap (<script>:)[<step>] (<duration>)", 0);
dB.echoApproval("Loaded core commands: " + instances.keySet().toString());
}
| public void registerCoreMembers() {
// <--[command]
// @Name Age
// @Usage age [<entity>|...] (adult/baby/<age>) (lock)
// @Required 1
// @Stable stable
// @Short Sets the ages of a list of entities, optionally locking them in those ages.
// @Author David Cernat
// @Description
// Some living entity types are 'ageable' which can affect an entities ability to breed, or whether they appear
// as a baby or an adult. Using the 'age' command allows modification of an entity's age.
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AgeCommand.class,
"AGE", "age [<entity>|...] (adult/baby/<age>) (lock)", 1);
// <--[command]
// @Name Anchor
// @Usage anchor [id:<name>] [assume/remove/add <location>/walkto/walknear (r:#)]
// @Required 2
// @Stable stable
// @Short Controls a NPC's Anchor Trait.
// @Author aufdemrand
// @Description
// The anchor system inside Citizens2 allows locations to be 'bound' to a NPC, saved by an 'id'. The anchor
// command can add and remove new anchors, as well as the ability to teleport NPCs to anchors with the 'assume'
// argument.
// The Anchors Trait can also be used as a sort of 'waypoints' system. For ease of use, the anchor command
// provides function for NPCs to walk to or walk near an anchor.
// As the Anchor command is a NPC specific command, a valid npc object must be referenced in the script entry.
// If none is provided by default, the use of the 'npc:n@id' argument, replacing the id with the npcid of the
// NPC desired, can create a link, or alternatively override the default linked npc.
// @Tags
// <[email protected][anchor_name]>
// @Usage
// Use to add and remove anchors to a npc.
// - define location_name <context.message>
// - chat "I have saved this location as %location_name%.'
// - anchor add <npc.location> "id:%location_name%"
// @Usage
// Use to make a NPC walk to or walk near a saved anchor.
// - anchor walkto i:waypoint_1
// - anchor walknear i:waypoint_2 r:5
// -->
registerCoreMember(AnchorCommand.class,
"ANCHOR", "anchor [id:<name>] [assume/remove/add <location>/walkto/walknear (r:#)]", 2);
// <--[command]
// @Name Animate
// @Usage animate [<entity>|...] [animation:<name>]
// @Required 1
// @Stable stable
// @Short Makes a list of entities perform a certain animation.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnimateCommand.class,
"ANIMATE", "animate [<entity>|...] [animation:<name>]", 1);
// <--[command]
// @Name AnimateChest
// @Usage animatechest [<location>] ({open}/close) (sound:{true}/false)
// @Required 1
// @Stable unstable
// @Short Makes a chest open or close.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnimateChestCommand.class,
"ANIMATECHEST", "animatechest [<location>] ({open}/close) (sound:{true}/false)", 1);
// <--[command]
// @Name Announce
// @Usage announce ["<text>"] (to_ops) (to_flagged:<flag>) (format:<name>)
// @Required 1
// @Stable stable
// @Short Announces a message for everyone online to read.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AnnounceCommand.class,
"ANNOUNCE", "announce [\"<text>\"] (to_ops) (to_flagged:<flag>) (format:<name>)", 1);
// <--[command]
// @Name Assignment
// @Usage assignment [{set}/remove] (script:<name>)
// @Required 1
// @Stable unstable
// @Short Changes an NPC's assignment.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(AssignmentCommand.class,
"ASSIGNMENT", "assignment [{set}/remove] (script:<name>)", 1);
// <--[command]
// @Name Attack
// @Usage attack (cancel) (<entity>|...) (target:<entity>)
// @Required 0
// @Stable stable
// @Short Makes a list of entities attack a target.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(AttackCommand.class,
"ATTACK", "attack (cancel) (<entity>|...) (target:<entity>)", 0);
// <--[command]
// @Name Break
// @Usage break [<location>] (entity:<entity>) (radius:<#.#>)
// @Required 1
// @Stable unstable
// @Short Makes the NPC walk over and break a block. (Doesn't work!)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(BreakCommand.class,
"BREAK", "break [<location>] (entity:<entity>) (radius:<#.#>)", 1);
// <--[command]
// @Name Burn
// @Usage burn [<entity>|...] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Sets a list of entities on fire.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_time>
// @Usage
// Todo
// -->
registerCoreMember(BurnCommand.class,
"BURN", "burn [<entity>|...] (duration:<value>)", 1);
// <--[command]
// @Name Cast, Potion
// @Usage cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)
// @Required 1
// @Stable Stable
// @Short Casts a potion effect to a list of entities.
// @Author aufdemrand, Jeebiss, Morphan1
// @Description
// Casts or removes a potion effect to or from a list of entities. If you don't specify a duration,
// it defaults to 60 seconds. If you don't specify a power level, it defaults to 1.
// @Tags
// <[email protected]_effect[<effect>]> will return true if the entity has an effect.
// @Usage
// Use to apply an effect to an entity
// - potion jump <player> d:120 p:3
// - narrate "You have been given the temporary ability to jump like a kangaroo."
// @Usage
// Use to remove an effect from an entity
// - if <[email protected]_effect[jump]> {
// - potion jump remove <player>
// }
//
// -->
registerCoreMember(CastCommand.class,
"CAST, POTION", "cast [<effect>] (remove) (duration:<value>) (power:<#>) (<entity>|...)", 1);
// <--[command]
// @Name Chat
// @Usage chat ["<text>"] (targets:<entity>|...)
// @Required 1
// @Stable stable
// @Short Causes the NPC to send a chat message to nearby players.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ChatCommand.class,
"CHAT", "chat [\"<text>\"] (targets:<entity>|...)", 1);
// <--[command]
// @Name ChunkLoad
// @Usage chunkload ({add}/remove/removeall) [<location>] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Keeps a chunk actively loaded and allowing NPC activity.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ChunkLoadCommand.class,
"CHUNKLOAD", "chunkload ({add}/remove/removeall) [<location>] (duration:<value>)", 1);
// <--[command]
// @Name Compass
// @Usage compass [<location>]
// @Required 1
// @Stable stable
// @Short Redirects the player's compass to target the given location.
// @Author mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(CompassCommand.class,
"COMPASS", "compass [<location>]", 1);
// <--[command]
// @Name Cooldown
// @Usage cooldown [<duration>] (global) (s:<script>)
// @Required 1
// @Stable stable
// @Short Temporarily disables a script-container from meeting requirements.
// @Author aufdemrand
// @Description
// Cools down a script-container. If an interact-container, when on cooldown, scripts will not pass a
// requirements check allowing the next highest priority script to trigger. If any other type of script, a
// manual requirements check (<s@script_name.requirements.check>) will also return false until the cooldown
// period is completed. Cooldown requires a type (player or global), a script, and a duration. It also requires
// a valid link to a dPlayer if using player-type cooldown.
//
// Cooldown periods are persistent through a server restart as they are saved in the saves.yml.
// @Tags
// <s@script_name.cooled_down[player]> will return whether the script is cooled down
// <s@script_name.cooldown> will return the duration of the cooldown in progress.
// <[email protected]> will also check script cooldown, as well as any requirements.
// @Usage
// Use to keep the current interact script from meeting requirements.
// - cooldown 20m
// @Usage
// Use to keep a player from activating a script for a specified duration.
// - cooldown 11h s:s@bonus_script
// - cooldown 5s s:s@hit_indicator
// @Usage
// Use the 'global' argument to indicate the script to be on cooldown for all players.
// - cooldown global 24h s:s@daily_treasure_offering
// -->
registerCoreMember(CooldownCommand.class,
"COOLDOWN", "cooldown [<duration>] (global) (s:<script>)", 1);
// <--[command]
// @Name CopyBlock
// @Usage copyblock [location:<location>] [to:<location>]
// @Required 1
// @Stable unstable
// @Short Copies a block to another location, keeping all metadata.
// @Author aufdemrand, David Cernat
// @Description
// Todo
// @Tags
// <[email protected]. * >
// @Usage
// Todo
// -->
registerCoreMember(CopyBlockCommand.class,
"COPYBLOCK", "copyblock [location:<location>] [to:<location>]", 1);
// <--[command]
// @Name CreateWorld
// @Usage createworld [<name>] (g:<generator>)
// @Required 1
// @Stable unstable
// @Short Creates a new world
// @Author Todo
// @Description
// Todo
// @Tags
// <server.list_worlds>
// @Usage
// Todo
// -->
registerCoreMember(CreateWorldCommand.class,
"CREATEWORLD", "createworld [<name>] (g:<generator>)", 1);
// <--[command]
// @Name Define
// @Usage define [<id>] [<value>]
// @Required 2
// @Stable stable
// @Short Creates a temporary variable inside a script queue.
// @Author aufdemrand
//
// @Description
// Definitions are queue-level (or script-level) 'variables' that can be used throughout a script, once
// defined, by using %'s around the definition id/name. Definitions are only valid on the current queue and are
// not transferred to any new queues constructed within the script, such as a 'run' command, without explicitly
// specifying to do so.
//
// Definitions are lighter and faster than creating a temporary flag, but unlike flags, are only a single entry,
// that is, you can't add or remove from the definition, but you can re-create it if you wish to specify a new
// value. Definitions are also automatically destroyed when the queue is completed, so there is no worry for
// leaving unused data hanging around.
//
// Definitions are also resolved before replaceable tags, meaning you can use them within tags, even as an
// attribute. ie. <%player%.name>
//
// @Tags
// %DefinedItem%
// @Usage
// Use to make complex tags look less complex, and scripts more readable.
// - narrate 'You invoke your power of notice...'
// - define range '<player.flag[range_level].mul[3]>'
// - define blocks '<player.flag[noticeable_blocks>'
// - narrate '[NOTICE] You have noticed <player.location.find.blocks[%blocks%].within[%range].size>
// blocks in the area that may be of interest.'
//
// @Usage
// Use to keep the value of a replaceable tag that you might use many times within a single script. Definitions
// can be faster and cleaner than reusing a replaceable tag over and over.
// - define arg1 <c.args.get[1]>
// - if %arg1% == hello narrate 'Hello!'
// - if %arg1% == goodbye narrate 'Goodbye!'
//
// @Usage
// Use to pass some important information (arguments) on to another queue.
// - run 'new_task' d:hello|world
// 'new_task' now has some definitions, %1% and %2%, that contains the contents specified, 'hello' and 'world'.
//
// -->
registerCoreMember(DefineCommand.class,
"DEFINE", "define [<id>] [<value>]", 2);
// <--[command]
// @Name Determine
// @Usage determine [<value>]
// @Required 1
// @Stable stable
// @Short Sets the outcome of an event.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DetermineCommand.class,
"DETERMINE", "determine [<value>]", 1);
// <--[command]
// @Name Disengage
// @Usage disengage (npc:<npc>)
// @Required 0
// @Stable stable
// @Short Enables a NPCs triggers that have been temporarily disabled by the engage command.
// @Author aufdemrand
//
// @Description
// Re-enables any toggled triggers that have been disabled by disengage. Using
// disengage inside scripts must have a NPC to reference, or one may be specified
// by supplying a valid dNPC object with the npc argument.
//
// This is mostly regarded as an 'interact script command', though it may be used inside
// other script types. This is because disengage works with the trigger system, which is an
// interact script-container feature.
//
// NPCs that are interacted with while engaged will fire an 'on unavailable' assignment
// script-container action.
//
// @Tags
// none
// @Usage
// Use to reenable a NPC's triggers, disabled via 'engage'.
// - engage
// - chat 'Be right there!'
// - walkto <player.location>
// - wait 5s
// - disengage
//
// -->
registerCoreMember(DisengageCommand.class,
"DISENGAGE", "disengage (npc:<npc>)", 0);
// <--[command]
// @Name DisplayItem
// @Usage displayitem [<item>] [<location>] (duration:<value>)
// @Required 2
// @Stable Todo
// @Short Makes a non-touchable item spawn for players to view.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DisplayItemCommand.class,
"DISPLAYITEM", "displayitem [<item>] [<location>] (duration:<value>)", 2);
// <--[command]
// @Name Drop
// @Usage drop [<item>/<entity>/xp] [<location>] (qty:<#>)
// @Required 1
// @Stable stable
// @Short Drops an item for players to pick up.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(DropCommand.class,
"DROP", "drop [<item>/<entity>/xp] [<location>] (qty:<#>)", 1);
// <--[command]
// @Name Engage
// @Usage engage (<duration>) (npc:<npc>)
// @Required 0
// @Stable stable
// @Short Temporarily disables a NPCs toggled interact script-container triggers.
// @Author aufdemrand
//
// @Description
// Engaging a NPC will temporarily disable any interact script-container triggers. To reverse
// this behavior, use either the disengage command, or specify a duration in which the engage
// should timeout. Specifying an engage without a duration will render the NPC engaged until
// a disengage is used on the NPC. Engaging a NPC affects all players attempting to interact
// with the NPC.
//
// While engaged, all triggers and actions associated with triggers will not 'fire', except
// the 'on unavailable' assignment script-container action, which will fire for triggers that
// were enabled previous to the engage command.
//
// Engage can be useful when NPCs are carrying out a task that shouldn't be interrupted, or
// to provide a good way to avoid accidental 'retrigger'.
//
// @See Disengage Command
//
// @Tags
// <[email protected]> will return true if the NPC is currently engaged, false otherwise.
//
// @Usage
// Use to make a NPC appear 'busy'.
// - engage
// - chat 'Give me a few minutes while I mix you a potion!'
// - walkto <npc.anchor[mixing_station]>
// - wait 10s
// - walkto <npc.anchor[service_station]>
// - chat 'Here you go!'
// - give potion <player>
// - disengage
//
// @Usage
// Use to avoid 'retrigger'.
// - engage 5s
// - take quest_item
// - flag player finished_quests:->:super_quest
//
// -->
registerCoreMember(EngageCommand.class,
"ENGAGE", "engage (<duration>) (npc:<npc>)", 0);
// <--[command]
// @Name Engrave
// @Usage engrave (set/remove)
// @Required 0
// @Stable unstable
// @Short Locks an item to a player *does not work currently*
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(EngraveCommand.class,
"ENGRAVE", "engrave (set/remove)", 0);
// <--[command]
// @Name Equip
// @Usage equip (player/{npc}) (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)
// @Required 1
// @Stable unstable
// @Short Equips an item into the chosen inventory slot of the player or NPC.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(EquipCommand.class,
"EQUIP", "equip (player/{npc}) (hand:<item>) (head:<item>) (chest:<item>) (legs:<item>) (boots:<item>)", 1);
// <--[command]
// @Name Execute
// @Usage execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]
// @Required 2
// @Stable stable
// @Short Executes an arbitrary server command as if the player, NPC, or server typed it in.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ExecuteCommand.class,
"EXECUTE", "execute [as_player/as_op/as_npc/as_server] [<Bukkit command>]", 2);
// <--[command]
// @Name Experience
// @Usage experience [{set}/give/take] (level) [<#>]
// @Required 2
// @Stable Todo
// @Short Gives or takes experience points to the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]_next_level>
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(ExperienceCommand.class,
"EXPERIENCE", "experience [{set}/give/take] (level) [<#>]", 2);
// <--[command]
// @Name Explode
// @Usage explode (power:<#.#>) (<location>) (fire) (breakblocks)
// @Required 0
// @Stable stable
// @Short Causes an explosion at the location.
// @Author Alain Blanquet
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ExplodeCommand.class,
"EXPLODE", "explode (power:<#.#>) (<location>) (fire) (breakblocks)", 0);
// <--[command]
// @Name Fail
// @Usage fail (script:<name>)
// @Required 0
// @Stable stable
// @Short Marks a script as having failed.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FailCommand.class,
"FAIL", "fail (script:<name>)", 0);
// <--[command]
// @Name Feed
// @Usage feed (amt:<#>) (target:<entity>|...)
// @Required 0
// @Stable unstable
// @Short Refills the player's food bar.
// @Author aufdemrand, Jeebiss
// @Description
// Todo
// @Tags
// <[email protected]_level>
// <[email protected]_level.formatted>
// @Usage
// Todo
// -->
registerCoreMember(FeedCommand.class,
"FEED", "feed (amt:<#>) (target:<entity>|...)", 0);
// <--[command]
// @Name Finish
// @Usage finish (script:<name>)
// @Required 0
// @Stable stable
// @Short Marks a script as having been completed successfully.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FinishCommand.class,
"FINISH", "finish (script:<name>)", 0);
// <--[command]
// @Name Firework
// @Usage firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)
// @Required 0
// @Stable Todo
// @Short Launches a firework.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FireworkCommand.class,
"FIREWORK", "firework (<location>) (power:<#>) (type:<name>/random) (primary:<color>|...) (fade:<color>|...) (flicker) (trail)", 0);
// <--[command]
// @Name Fish
// @Usage fish (catchfish) (stop) (<location>) (catchpercent:<#>)
// @Required 1
// @Stable Todo
// @Short Causes an NPC to begin fishing
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FishCommand.class,
"FISH", "fish (catchfish) (stop) (<location>) (catchpercent:<#>)", 1);
// <--[command]
// @Name Flag
// @Usage flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)
// @Required 1
// @Stable stable
// @Short Sets or modifies a flag on the player, NPC, or server.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <[email protected][<flag>]>
// <[email protected][<flag>]>
// <global.flag[<flag>]>
// @Usage
// Todo
// -->
registerCoreMember(FlagCommand.class,
"FLAG", "flag ({player}/npc/global) [<name>([<#>])](:<action>)[:<value>] (duration:<value>)", 1);
// <--[command]
// @Name Fly
// @Usage fly (cancel) [<entity>|...] (controller:<player>) (origin:<location>) (destinations:<location>|...) (speed:<#.#>) (rotationthreshold:<#.#>)
// @Required 1
// @Stable stable
// @Short Make an entity fly where its controller is looking or fly to waypoints.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FlyCommand.class,
"FLY", "fly (cancel) [<entity>|...] (controller:<player>) (origin:<location>) (destinations:<location>|...) (speed:<#.#>) (rotationthreshold:<#.#>)", 1);
// <--[command]
// @Name Follow
// @Usage follow (stop) (lead:<#.#>) (target:<entity>)
// @Required 0
// @Stable unstable
// @Short Causes the NPC to follow a target (Currently experiencing bugs with lead: )
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(FollowCommand.class,
"FOLLOW", "follow (stop) (lead:<#.#>) (target:<entity>)", 0);
// <--[command]
// @Name ForEach
// @Usage foreach [<object>|...] [<commands>]
// @Required 2
// @Stable stable
// @Short Loops through a dList, running a set of commands for each item.
// @Author Morphan1, mcmonkey
//
// @Description
// Loops through a dList of any type. For each item in the dList, the specified commands will be ran for
// that item. To call the value of the item while in the loop, you can use %value%.
//
// @Tags
// None
// @Usage
// Use to run commands on multiple items.
// - foreach li@e@123|n@424|p@BobBarker {
// - announce "There's something at <%value%.location>!"
// }
//
// -->
registerCoreMember(ForEachCommand.class,
"FOREACH", "foreach [<object>|...] [<commands>]", 2);
// <--[command]
// @Name Give
// @Usage give [money/<item>|...] (qty:<#>) (engrave) (to:<inventory>)
// @Required 1
// @Stable stable
// @Short Gives the player an item or money.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(GiveCommand.class,
"GIVE", "give [money/<item>|...] (qty:<#>) (engrave) (to:<inventory>)", 1);
// <--[command]
// @Name Group
// @Usage group [add/remove] [<group>] (world:<name>)
// @Required 2
// @Stable Todo
// @Short Adds a player to or removes a player from a permissions group.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_group[<group>]>
// <[email protected]_group[<group>].global>
// <[email protected]_group[<group>].world>
// @Usage
// Todo
// -->
registerCoreMember(GroupCommand.class,
"GROUP", "group [add/remove] [<group>] (world:<name>)", 2);
// <--[command]
// @Name Head
// @Usage head (<entity>|...) [skin:<player>]
// @Required 1
// @Stable stable
// @Short Makes players or NPCs wear a specific player's head.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(HeadCommand.class,
"HEAD", "head (<entity>|...) [skin:<player>]", 1);
// <--[command]
// @Name Heal
// @Usage heal (<#.#>) (<entity>|...)
// @Required 0
// @Stable stable
// @Short Heals the player.
// @Author aufdemrand, Jeebiss, morphan1, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HealCommand.class,
"HEAL", "heal (<#.#>) (<entity>|...)", 0);
// <--[command]
// @Name Health
// @Usage health (target:player/{npc}) [<#>]
// @Required 1
// @Stable stable
// @Short Changes the target's maximum health.
// @Author mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HealthCommand.class,
"HEALTH", "health (target:player/{npc}) [<#>]", 1);
// <--[command]
// @Name Hurt
// @Usage hurt (<#.#>) (<entity>|...)
// @Required 0
// @Stable stable
// @Short Hurts the player.
// @Author aufdemrand, Jeebiss, morphan1, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(HurtCommand.class,
"HURT", "hurt (<#.#>) (<entity>|...)", 0);
// <--[command]
// @Name If
// @Usage if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)
// @Required 2
// @Stable stable
// @Short Compares values, and runs one script if they match, or a different script if they don't match.
// @Author aufdemrand, David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(IfCommand.class,
"IF", "if [<value>] (!)(<operator> <value>) (&&/|| ...) [<commands>] (else <commands>)", 2);
// <--[command]
// @Name Inventory
// @Usage inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] (destination:<inventory>) (origin:<inventory>)
// @Required 1
// @Stable stable
// @Short Edits the inventory of a player, NPC, or chest.
// @Author David Cernat, morphan1
// @Description
// Todo
// @Tags
// <player.inventory>
// <npc.inventory>
// <location.inventory>
// @Usage
// Todo
// -->
registerCoreMember(InventoryCommand.class,
"INVENTORY", "inventory [open/copy/move/swap/add/remove/keep/exclude/fill/clear] (destination:<inventory>) (origin:<inventory>)", 1);
// <--[command]
// @Name Inject
// @Usage inject (locally) [<script>] (path:<name>) (instantly)
// @Required 1
// @Stable stable
// @Short Runs a script in the current ScriptQueue.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(InjectCommand.class,
"INJECT", "inject (locally) [<script>] (path:<name>) (instantly)", 1);
// <--[command]
// @Name Invisible
// @Usage invisible [player/npc] [state:true/false/toggle]
// @Required 2
// @Stable unstable
// @Short Makes the player or NPC turn invisible. (Does not fully work currently)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(InvisibleCommand.class,
"INVISIBLE", "invisible [player/npc] [state:true/false/toggle]", 2);
// <--[command]
// @Name Leash
// @Usage leash (cancel) [<entity>|...] (holder:<entity>/<location>)
// @Required 1
// @Stable stable
// @Short Sticks a leash on target entity, held by a fence post or another entity.
// @Author Alain Blanquet, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]_leashed>
// <[email protected]_leash_holder>
// @Usage
// Todo
// -->
registerCoreMember(LeashCommand.class,
"LEASH", "leash (cancel) [<entity>|...] (holder:<entity>/<location>)", 1);
// <--[command]
// @Name Listen
// @Usage listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)
// @Required 2
// @Stable unstable
// @Short Listens for the player achieving various actions and runs a script when they are completed.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ListenCommand.class,
"LISTEN", "listen ({new}/cancel/finish) [kill/block/item/itemdrop/travel] [<requirements>] [script:<name>] (id:<name>)", 2);
// <--[command]
// @Name Log
// @Usage log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]
// @Required 2
// @Stable Todo
// @Short Logs some debugging info to a file.
// @Author spaceemotion
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(LogCommand.class,
"LOG", "log [<text>] (type:severe/info/warning/fine/finer/finest) [file:<name>]", 2);
// <--[command]
// @Name Look
// @Usage look (<entity>|...) [<location>] (duration:<duration>)
// @Required 1
// @Stable stable
// @Short Causes the NPC or other entity to look at a target location.
// @Author aufdemrand, mcmonkey
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(LookCommand.class,
"LOOK", "look (<entity>|...) [<location>] (duration:<duration>)", 1);
// <--[command]
// @Name LookClose
// @Usage lookclose [state:true/false]
// @Required 1
// @Stable unstable
// @Short Toggles whether the NPC will automatically look at nearby players.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(LookcloseCommand.class,
"LOOKCLOSE", "lookclose [state:true/false]", 1);
// <--[command]
// @Name Midi
// @Usage midi (cancel) [<file>] (<location>/<entity>|...) (tempo:<#.#>)
// @Required 1
// @Stable stable
// @Short Plays a midi file at a given location or to a list of players using note block sounds.
// @Author David Cernat
// @Description
// This will fully load a midi song file stored in plugins/Denizen/midi/
// The file must be a valid midi file with the extension .mid
// It will continuously play the song as noteblock songs at the given location or group of players until the song ends.
// By default, this will play for the connected player only.
// @Tags
// None.
// @Usage
// Use to play a midi song file at a given location
// - midi file:Mysong <player.location>
//
// @Usage
// Use to play a midi song file at a given location to the specified player
// - midi file:Mysong <server.list_online_players>
// -->
registerCoreMember(MidiCommand.class,
"MIDI", "midi (cancel) [<file>] (<location>/<entity>|...) (tempo:<#.#>)", 1);
// <--[command]
// @Name Mount
// @Usage mount (cancel) [<entity>|...] (<location>)
// @Required 0
// @Stable stable
// @Short Mounts one entity onto another.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_vehicle>
// <[email protected]_inside_vehicle>
// @Usage
// Todo
// -->
registerCoreMember(MountCommand.class,
"MOUNT", "mount (cancel) [<entity>|...] (<location>)", 0);
// <--[command]
// @Name ModifyBlock
// @Usage modifyblock [<location>] [<material>] (radius:<#>) (height:<#>) (depth:<#>)
// @Required 2
// @Stable unstable
// @Short Changes a block's material.
// @Author Jeebiss
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(ModifyBlockCommand.class,
"MODIFYBLOCK", "modifyblock [<location>] [<material>] (radius:<#>) (height:<#>) (depth:<#>)", 2);
// <--[command]
// @Name Nameplate
// @Usage nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib
// @Required 1
// @Stable unstable
// @Short Changes something's nameplate, requires ProtocolLib (Unstable and broken!)
// @Author spaceemotion
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NameplateCommand.class,
"NAMEPLATE", "nameplate [<chatcolor>] [set:<text>] (target:<player>) +--> Requires ProtocolLib", 1);
// <--[command]
// @Name Narrate
// @Usage narrate ["<text>"] (targets:<player>|...) (format:<name>)
// @Required 1
// @Stable stable
// @Short Shows some text to the player.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NarrateCommand.class,
"NARRATE", "narrate [\"<text>\"] (targets:<player>|...) (format:<name>)", 1);
// <--[command]
// @Name Note
// @Usage note [<Notable dObject>] [as:<name>]
// @Required 2
// @Stable unstable
// @Short Adds a new notable object.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(NoteCommand.class,
"NOTE", "note [<Notable dObject>] [as:<name>]", 2);
// <--[command]
// @Name Oxygen
// @Usage oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]
// @Required 1
// @Stable unstable
// @Short Gives or takes breath from the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(OxygenCommand.class,
"OXYGEN", "oxygen (type:maximum/remaining) (mode:set/add/remove) [qty:<#>]", 1);
// <--[command]
// @Name Pause
// @Usage pause [waypoints/navigation]
// @Required 1
// @Stable unstable
// @Short Pauses an NPC's navigation.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(PauseCommand.class,
"PAUSE", "pause [waypoints/navigation]", 1);
// <--[command]
// @Name PlayEffect
// @Usage playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)
// @Required 2
// @Stable stable
// @Short Plays a visible or audible effect at the location.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PlayEffectCommand.class,
"PLAYEFFECT", "playeffect [<location>] [effect:<name>] (data:<#.#>) (visibility:<#.#>) (qty:<#>) (offset:<#.#>)", 2);
// <--[command]
// @Name PlaySound
// @Usage playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)
// @Required 2
// @Stable stable
// @Short Plays a sound at the location.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PlaySoundCommand.class,
"PLAYSOUND", "playsound [<location>] [sound:<name>] (volume:<#.#>) (pitch:<#.#>)", 2);
// <--[command]
// @Name Permission
// @Usage permission [add/remove] [permission] (player:<name>) (group:<name>) (world:<name>)
// @Required 2
// @Stable unstable
// @Short Gives or takes a permission node to/from the player or group.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_permission[permission.node]>
// <[email protected]_permission[permission.node].global>
// <[email protected]_permission[permission.node].world>
// @Usage
// Todo
// -->
registerCoreMember(PermissionCommand.class,
"PERMISSION", "permission [add/remove] [permission] (player:<name>) (group:<name>) (world:<name>)", 2);
// <--[command]
// @Name Pose
// @Usage pose (player/npc) [id:<name>]
// @Required 1
// @Stable unstable
// @Short Rotates the player or NPC to match a pose.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(PoseCommand.class,
"POSE", "pose (player/npc) [id:<name>]", 1);
// <--[command]
// @Name Push
// @Usage push [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (speed:<#.#>) (<duration>) (<script>)
// @Required 1
// @Stable mostly
// @Short Pushes entities through the air in a straight line.
// @Author David Cernat, mcmonkey
// @Description
// Pushes entities through the air in a straight line at a certain speed and for a certain duration, triggering a script when they hit an obstacle or stop flying.
// @Tags
// Todo
// @Usage
// Use to launch an arrow straight towards a target
// - push arrow destination:<player.location>
//
// @Usage
// Use to launch an entity into the air
// - push cow
//
// -->
registerCoreMember(PushCommand.class,
"PUSH", "push [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (speed:<#.#>) (<duration>) (<script>)", 1);
// <--[command]
// @Name Queue
// @Usage queue (queue:<id>) [clear/pause/resume/delay:<#>]
// @Required 1
// @Stable stable
// @Short Modifies the current state of a script queue.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(QueueCommand.class,
"QUEUE", "queue (queue:<id>) [clear/pause/resume/delay:<#>]", 1);
// <--[command]
// @Name Random
// @Usage random [<#>/{braced commands}]
// @Required 1
// @Stable stable
// @Short Selects a random choice from the following script commands.
// @Author aufdemrand, morphan1
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Use to choose randomly from the following commands
// - random 3
// - narrate "hi"
// - narrate "hello"
// - narrate "hey"
//
// @Usage
// Use to choose randomly from a braced set of commands
// - random {
// - narrate "hi"
// - narrate "hello"
// - narrate "hey"
// }
//
// -->
registerCoreMember(RandomCommand.class,
"RANDOM", "random [<#>/{braced commands}]", 1);
// <--[command]
// @Name Remove
// @Usage remove [<entity>|...] (region:<name>)
// @Required 0
// @Stable Todo
// @Short Despawns a list of entities.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_spawned>
// @Usage
// Todo
// -->
registerCoreMember(RemoveCommand.class,
"REMOVE", "remove [<entity>|...] (<world>) (region:<name>)", 0);
// <--[command]
// @Name Rename
// @Usage rename [<npc>] [<name>]
// @Required 1
// @Stable Todo
// @Short Renames an NPC.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(RenameCommand.class,
"RENAME", "rename [<npc>] [<name>]", 1);
// <--[command]
// @Name Repeat
// @Usage repeat [<amount>] [<commands>]
// @Required 1
// @Stable stable
// @Short Runs a series of braced commands several times.
// @Author morphan1, mcmonkey
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RepeatCommand.class,
"REPEAT", "repeat [<amount>] [<commands>]", 1);
// <--[command]
// @Name Reset
// @Usage reset [fails/finishes/cooldown] (script:<name>)
// @Required 1
// @Stable unstable
// @Short Resets a script's fails, finishes, or cooldowns.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ResetCommand.class,
"RESET", "reset [fails/finishes/cooldown] (script:<name>)", 1);
// <--[command]
// @Name Rotate
// @Usage rotate (<entity>|...) (yaw:<value>) (pitch:<value>) (duration:<duration>) (frequency:<duration>)
// @Required 1
// @Stable stable
// @Short Rotates a list of entities.
// @Author David Cernat
// @Description
// Todo
// @Tags
// @Usage
// Todo
// -->
registerCoreMember(RotateCommand.class,
"ROTATE", "rotate (cancel) (<entity>|...) (yaw:<value>) (pitch:<value>) (duration:<duration>) (infinite/frequency:<duration>)", 0);
// <--[command]
// @Name Run
// @Usage run (locally) [<script>] (path:<name>) (as:<player>/<npc>) (def:<element>|...) (id:<name>) (instantly) (delay:<value>)
// @Required 1
// @Stable stable
// @Short Runs a script in a new ScriptQueue.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RunCommand.class,
"RUN", "run (locally) [<script>] (path:<name>) (as:<player>/<npc>) (def:<element>|...) (id:<name>) (instantly) (delay:<value>)", 1);
// <--[command]
// @Name RunTask
// @Deprecated This has been replaced by the Run command.
// @Usage runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)
// @Required 1
// @Stable unstable
// @Short Runs a task script.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(RuntaskCommand.class,
"RUNTASK", "runtask [<name>] (instantly) (queue(:<name>)) (delay:<#>) (define:<element>|...)", 1);
// <--[command]
// @Name Scoreboard
// @Usage scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)
// @Required 1
// @Stable unstable
// @Short Modifies a scoreboard (Not going to work much until Minecraft 1.7)
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ScoreboardCommand.class,
"SCOREBOARD", "scoreboard [set/remove/show/hide] [<name>] [value:<name>] (priority:<#>)", 1);
// <--[command]
// @Name Scribe
// @Usage scribe [script:<name>] (give/drop/equip) (<item>) (<location>)
// @Required 1
// @Stable Todo
// @Short Writes to a book.
// @Author Jeebiss
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ScribeCommand.class,
"SCRIBE", "scribe [script:<name>] (give/drop/equip) (<item>) (<location>)", 1);
// <--[command]
// @Name Shoot
// @Usage shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (height:<#.#>) (gravity:<#.#>) (script:<name>)
// @Required 1
// @Stable stable
// @Short Shoots an entity through the air up to a certain height.
// @Author David Cernat
// @Description
// Shoots an entity through the air up to a certain height, optionally using a custom gravity value and triggering a script on impact with a surface.
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ShootCommand.class,
"SHOOT", "shoot [<entity>|...] (origin:<entity>/<location>) (destination:<location>) (height:<#.#>) (gravity:<#.#>) (script:<name>)", 1);
// <--[command]
// @Name ShowFake
// @Usage showfake [<material>] [<location>|...] (d:<duration>{10s})
// @Required 2
// @Stable stable
// @Short Makes the player see a block change that didn't actually happen.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ShowFakeCommand.class,
"SHOWFAKE", "showfake [<material>] [<location>|...] (d:<duration>{10s})", 2);
// <--[command]
// @Name Sign
// @Usage sign (type:{sign_post}/wall_sign) ["<line>|..."] [<location>] (direction:n/e/w/s)
// @Required 1
// @Stable stable
// @Short Modifies a sign.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(SignCommand.class,
"SIGN", "sign (type:{sign_post}/wall_sign) [\"<line>|...\"] [<location>] (direction:n/e/w/s)", 1);
// <--[command]
// @Name Sit
// @Usage sit (<location>)
// @Required 0
// @Stable unstable
// @Short Causes the NPC to sit. (Does not currently work!)
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_contents>
// @Usage
// Todo
// -->
registerCoreMember(SitCommand.class,
"SIT", "sit (<location>)", 0);
// <--[command]
// @Name Spawn
// @Usage spawn [<entity>|...] (<location>) (target:<entity>)
// @Required 1
// @Stable stable
// @Short Spawns a list of entities at a certain location.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]_spawned>
// <util.entity_is_spawned[<entity>]>
// @Usage
// Todo
// -->
registerCoreMember(SpawnCommand.class,
"SPAWN", "spawn [<entity>|...] (<location>) (target:<entity>)", 1);
// <--[command]
// @Name Stand
// @Usage stand
// @Required 0
// @Stable unstable
// @Short Causes the NPC to stand. (Does not currently work!)
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(StandCommand.class,
"STAND", "stand", 0);
// <--[command]
// @Name Strike
// @Usage strike (no_damage) [<location>]
// @Required 1
// @Stable stable
// @Short Strikes lightning down upon the location.
// @Author Todo
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(StrikeCommand.class,
"STRIKE", "strike (no_damage) [<location>]", 1);
// <--[command]
// @Name Switch
// @Usage switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)
// @Required 1
// @Stable stable
// @Short Switches a lever.
// @Author aufdemrand, Jeebiss, David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(SwitchCommand.class,
"SWITCH", "switch [<location>] (state:[{toggle}/on/off]) (duration:<value>)", 1);
// <--[command]
// @Name Take
// @Usage take [money/iteminhand/<item>|...] (qty:<#>) (from:<inventory>)
// @Required 1
// @Stable stable
// @Short Takes an item from the player.
// @Author Todo
// @Description
// Todo
// @Tags
// <[email protected]_in_hand>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TakeCommand.class,
"TAKE", "take [money/iteminhand/<item>|...] (qty:<#>) (from:<inventory>)", 1);
// <--[command]
// @Name Teleport
// @Usage teleport (<entity>|...) [<location>]
// @Required 1
// @Stable stable
// @Short Teleports the player or NPC to a new location.
// @Author David Cernat, aufdemrand
// @Description
// Todo
// @Tags
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TeleportCommand.class,
"TELEPORT", "teleport (<entity>|...) [<location>]", 1);
// <--[command]
// @Name Time
// @Usage time [type:{global}/player] [<value>] (world:<name>)
// @Required 1
// @Stable Todo
// @Short Changes the current time in the minecraft world.
// @Author David Cernat
// @Description
// Todo
// @Tags
// <[email protected]>
// <[email protected]>
// @Usage
// Todo
// -->
registerCoreMember(TimeCommand.class,
"TIME", "time [type:{global}/player] [<value>] (world:<name>)", 1);
// <--[command]
// @Name Trait
// @Usage trait (state:true/false/{toggle}) [<trait>]
// @Required 1
// @Stable Stable
// @Short Adds or removes a trait from an NPC.
// @Author Morphan1
// @Description
// Todo
// @Tags
// <[email protected]_trait[<trait>]>
// <[email protected]_traits>
// @Usage
// Todo
// -->
registerCoreMember(TraitCommand.class,
"TRAIT", "trait (state:true/false/{toggle}) [<trait>]", 1);
// <--[command]
// @Name Trigger
// @Usage trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)
// @Required 2
// @Stable stable
// @Short Enables or disables a trigger.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(TriggerCommand.class,
"TRIGGER", "trigger [name:chat/click/damage/proximity] (state:true/false) (cooldown:<#.#>) (radius:<#>)", 2);
// <--[command]
// @Name Viewer
// @Usage viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)
// @Required 1
// @Stable unstable
// @Short Creates a sign that auto-updates with information.
// @Author Morphan1
//
// @Description
// Creates a sign that auto-updates with information about a player, including their location, score, and
// whether they're logged in or not.
//
// @Tags
// None
//
// @Usage
// Create a sign that shows the location of a player on a wall
// - viewer player:ThatGuy create 113,76,-302,world id:PlayerLoc1 type:wall_sign display:location
//
// -->
registerCoreMember(ViewerCommand.class,
"VIEWER", "viewer ({create <location>}/modify/remove) [id:<name>] (type:{sign_post}/wall_sign) (display:{location}/score/logged_in) (direction:n/e/w/s)", 2);
// <--[command]
// @Name Vulnerable
// @Usage vulnerable (state:{true}/false/toggle)
// @Required 0
// @Stable unstable
// @Short Sets whether an NPC is vulnerable.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(VulnerableCommand.class,
"VULNERABLE", "vulnerable (state:{true}/false/toggle)", 0);
// <--[command]
// @Name Wait
// @Usage wait (<duration>) (queue:<name>)
// @Required 0
// @Stable stable
// @Short Delays a script for a specified amount of time.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(WaitCommand.class,
"WAIT", "wait (<duration>) (queue:<name>)", 0);
// <--[command]
// @Name Walk, WalkTo
// @Usage walk [<location>] (speed:<#>) (auto_range)
// @Required 1
// @Stable stable
// @Short Causes the NPC to walk to another location.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// <npc.navigator. * >
// @Usage
// Todo
// -->
registerCoreMember(WalkCommand.class,
"WALK, WALKTO", "walk [<location>] (speed:<#>) (auto_range)", 1);
// <--[command]
// @Name Weather
// @Usage weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)
// @Required 1
// @Stable Todo
// @Short Changes the current weather in the minecraft world.
// @Author David Cernat
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(WeatherCommand.class,
"WEATHER", "weather [type:{global}/player] [sunny/storm/thunder] (world:<name>)", 1);
// <--[command]
// @Name Yaml
// @Usage yaml [load/create/savefile:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]
// @Required 1
// @Stable Todo
// @Short Edits a YAML configuration file.
// @Author Todo
// @Description
// Todo
// @Tags
// <yaml[<idname>].contains[<path>]>
// <yaml[<idname>].read[<path>]>
// <yaml[<idname>].list_keys[<path>]>
// @Usage
// Todo
// -->
registerCoreMember(YamlCommand.class,
"YAML", "yaml [load/create/savefile:<file>]/[write:<key>]/[write:<key> value:<value>] [id:<name>]", 1);
// <--[command]
// @Name Zap
// @Usage zap (<script>:)[<step>] (<duration>)
// @Required 0
// @Stable stable
// @Short Changes the current script step.
// @Author aufdemrand
// @Description
// Todo
// @Tags
// Todo
// @Usage
// Todo
// -->
registerCoreMember(ZapCommand.class,
"ZAP", "zap (<script>:)[<step>] (<duration>)", 0);
dB.echoApproval("Loaded core commands: " + instances.keySet().toString());
}
|
diff --git a/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java b/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java
index 17d69a870..4fe4657a1 100644
--- a/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java
+++ b/clients/android/NewsBlur/src/com/newsblur/activity/Reading.java
@@ -1,538 +1,543 @@
package com.newsblur.activity;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.newsblur.R;
import com.newsblur.activity.Main;
import com.newsblur.domain.Story;
import com.newsblur.domain.UserDetails;
import com.newsblur.fragment.ReadingItemFragment;
import com.newsblur.fragment.ShareDialogFragment;
import com.newsblur.fragment.SyncUpdateFragment;
import com.newsblur.fragment.TextSizeDialogFragment;
import com.newsblur.network.APIManager;
import com.newsblur.util.AppConstants;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.PrefConstants;
import com.newsblur.util.PrefsUtils;
import com.newsblur.util.UIUtils;
import com.newsblur.util.ViewUtils;
import com.newsblur.view.NonfocusScrollview.ScrollChangeListener;
public abstract class Reading extends NbFragmentActivity implements OnPageChangeListener, SyncUpdateFragment.SyncUpdateFragmentInterface, OnSeekBarChangeListener, ScrollChangeListener {
public static final String EXTRA_FEED = "feed_selected";
public static final String EXTRA_POSITION = "feed_position";
public static final String EXTRA_USERID = "user_id";
public static final String EXTRA_USERNAME = "username";
public static final String EXTRA_FOLDERNAME = "foldername";
public static final String EXTRA_FEED_IDS = "feed_ids";
private static final String TEXT_SIZE = "textsize";
private static final int OVERLAY_RANGE_TOP_DP = 45;
private static final int OVERLAY_RANGE_BOT_DP = 60;
/** The longest time (in seconds) the UI will wait for API pages to load while
searching for the next unread story. */
private static final long UNREAD_SEARCH_LOAD_WAIT_SECONDS = 30;
private final Object UNREAD_SEARCH_MUTEX = new Object();
private CountDownLatch unreadSearchLatch;
protected int passedPosition;
protected int currentState;
protected ViewPager pager;
protected Button overlayLeft, overlayRight;
protected ProgressBar overlayProgress;
protected FragmentManager fragmentManager;
protected ReadingAdapter readingAdapter;
protected ContentResolver contentResolver;
private APIManager apiManager;
protected SyncUpdateFragment syncFragment;
protected Cursor stories;
private boolean noMoreApiPages;
protected volatile boolean requestedPage; // set high iff a syncservice request for stories is already in flight
private int currentApiPage = 0;
private Set<Story> storiesToMarkAsRead;
// unread counts for the circular progress overlay. set to nonzero to activate the progress indicator overlay
protected int startingUnreadCount = 0;
protected int currentUnreadCount = 0;
// A list of stories we have marked as read during this reading session. Needed to help keep track of unread
// counts since it would be too costly to query and update the DB on every page change.
private Set<Story> storiesAlreadySeen;
private float overlayRangeTopPx;
private float overlayRangeBotPx;
private List<Story> pageHistory;
@Override
protected void onCreate(Bundle savedInstanceBundle) {
requestWindowFeature(Window.FEATURE_PROGRESS);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceBundle);
setContentView(R.layout.activity_reading);
this.overlayLeft = (Button) findViewById(R.id.reading_overlay_left);
this.overlayRight = (Button) findViewById(R.id.reading_overlay_right);
this.overlayProgress = (ProgressBar) findViewById(R.id.reading_overlay_progress);
fragmentManager = getSupportFragmentManager();
storiesToMarkAsRead = new HashSet<Story>();
storiesAlreadySeen = new HashSet<Story>();
passedPosition = getIntent().getIntExtra(EXTRA_POSITION, 0);
currentState = getIntent().getIntExtra(ItemsList.EXTRA_STATE, 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contentResolver = getContentResolver();
this.apiManager = new APIManager(this);
// this value is expensive to compute but doesn't change during a single runtime
this.overlayRangeTopPx = (float) UIUtils.convertDPsToPixels(this, OVERLAY_RANGE_TOP_DP);
this.overlayRangeBotPx = (float) UIUtils.convertDPsToPixels(this, OVERLAY_RANGE_BOT_DP);
this.pageHistory = new ArrayList<Story>();
}
/**
* Sets up the local pager widget. Should be called from onCreate() after both the cursor and
* adapter are created.
*/
protected void setupPager() {
syncFragment = (SyncUpdateFragment) fragmentManager.findFragmentByTag(SyncUpdateFragment.TAG);
if (syncFragment == null) {
syncFragment = new SyncUpdateFragment();
fragmentManager.beginTransaction().add(syncFragment, SyncUpdateFragment.TAG).commit();
}
pager = (ViewPager) findViewById(R.id.reading_pager);
pager.setPageMargin(UIUtils.convertDPsToPixels(getApplicationContext(), 1));
pager.setPageMarginDrawable(R.drawable.divider_light);
pager.setOnPageChangeListener(this);
pager.setAdapter(readingAdapter);
pager.setCurrentItem(passedPosition);
// setCurrentItem sometimes fails to pass the first page to the callback, so call it manually
// for the first one.
this.onPageSelected(passedPosition);
this.enableOverlays();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.reading, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int currentItem = pager.getCurrentItem();
Story story = readingAdapter.getStory(currentItem);
UserDetails user = PrefsUtils.getUserDetails(this);
if (item.getItemId() == android.R.id.home) {
finish();
return true;
} else if (item.getItemId() == R.id.menu_reading_original) {
if (story != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(story.permalink));
startActivity(i);
}
return true;
} else if (item.getItemId() == R.id.menu_reading_sharenewsblur) {
if (story != null) {
ReadingItemFragment currentFragment = (ReadingItemFragment) readingAdapter.instantiateItem(pager, currentItem);
DialogFragment newFragment = ShareDialogFragment.newInstance(currentFragment, story, currentFragment.previouslySavedShareText);
newFragment.show(getSupportFragmentManager(), "dialog");
}
return true;
} else if (item.getItemId() == R.id.menu_shared) {
FeedUtils.shareStory(story, this);
return true;
} else if (item.getItemId() == R.id.menu_textsize) {
float currentValue = getSharedPreferences(PrefConstants.PREFERENCES, 0).getFloat(PrefConstants.PREFERENCE_TEXT_SIZE, 0.5f);
TextSizeDialogFragment textSize = TextSizeDialogFragment.newInstance(currentValue);
textSize.show(getSupportFragmentManager(), TEXT_SIZE);
return true;
} else if (item.getItemId() == R.id.menu_reading_save) {
FeedUtils.saveStory(story, Reading.this, apiManager);
return true;
} else if (item.getItemId() == R.id.menu_reading_markunread) {
this.markStoryUnread(story);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
// interface OnPageChangeListener
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
Story story = readingAdapter.getStory(position);
if (story != null) {
synchronized (this.pageHistory) {
// if the history is just starting out or the last entry in it isn't this page, add this page
if ((this.pageHistory.size() < 1) || (!story.equals(this.pageHistory.get(this.pageHistory.size()-1)))) {
this.pageHistory.add(story);
}
}
addStoryToMarkAsRead(story);
checkStoryCount(position);
}
this.enableOverlays();
}
// interface ScrollChangeListener
@Override
public void scrollChanged(int hPos, int vPos, int currentWidth, int currentHeight) {
int scrollMax = currentHeight - findViewById(android.R.id.content).getMeasuredHeight();
int posFromBot = (scrollMax - vPos);
float newAlpha = 0.0f;
if ((vPos < this.overlayRangeTopPx) && (posFromBot < this.overlayRangeBotPx)) {
// if we have a super-tiny scroll window such that we never leave either top or bottom,
// just leave us at full alpha.
newAlpha = 1.0f;
} else if (vPos < this.overlayRangeTopPx) {
float delta = this.overlayRangeTopPx - ((float) vPos);
newAlpha = delta / this.overlayRangeTopPx;
} else if (posFromBot < this.overlayRangeBotPx) {
float delta = this.overlayRangeBotPx - ((float) posFromBot);
newAlpha = delta / this.overlayRangeBotPx;
}
this.setOverlayAlpha(newAlpha);
}
private void setOverlayAlpha(float a) {
UIUtils.setViewAlpha(this.overlayLeft, a);
UIUtils.setViewAlpha(this.overlayRight, a);
UIUtils.setViewAlpha(this.overlayProgress, a);
}
/**
* Check and correct the display status of the overlays. Call this any time
* an event happens that might change our list position.
*/
private void enableOverlays() {
this.overlayLeft.setEnabled(this.getLastReadPosition(false) != -1);
this.overlayRight.setText((this.currentUnreadCount > 0) ? R.string.overlay_next : R.string.overlay_done);
this.overlayRight.setBackgroundResource((this.currentUnreadCount > 0) ? R.drawable.selector_overlay_bg_right : R.drawable.overlay_right_done);
if (this.startingUnreadCount == 0 ) {
// sessions with no unreads just show a full progress bar
this.overlayProgress.setMax(1);
this.overlayProgress.setProgress(1);
} else {
int unreadProgress = this.startingUnreadCount - this.currentUnreadCount;
this.overlayProgress.setMax(this.startingUnreadCount);
this.overlayProgress.setProgress(unreadProgress);
}
this.overlayProgress.invalidate();
this.setOverlayAlpha(1.0f);
}
@Override
public void updateAfterSync() {
this.requestedPage = false;
updateSyncStatus(false);
stories.requery();
readingAdapter.notifyDataSetChanged();
this.enableOverlays();
checkStoryCount(pager.getCurrentItem());
if (this.unreadSearchLatch != null) {
this.unreadSearchLatch.countDown();
}
}
@Override
public void updatePartialSync() {
stories.requery();
readingAdapter.notifyDataSetChanged();
this.enableOverlays();
checkStoryCount(pager.getCurrentItem());
if (this.unreadSearchLatch != null) {
this.unreadSearchLatch.countDown();
}
}
/**
* Lets us know that there are no more pages of stories to load, ever, and will cause
* us to stop requesting them.
*/
@Override
public void setNothingMoreToUpdate() {
this.noMoreApiPages = true;
if (this.unreadSearchLatch !=null) {
this.unreadSearchLatch.countDown();
}
}
/**
* While navigating the story list and at the specified position, see if it is possible
* and desirable to start loading more stories in the background. Note that if a load
* is triggered, this method will be called again by the callback to ensure another
* load is not needed and all latches are tripped.
*/
private void checkStoryCount(int position) {
// if the pager is at or near the number of stories loaded, check for more unless we know we are at the end of the list
if (((position + 2) >= stories.getCount()) && !noMoreApiPages && !requestedPage) {
currentApiPage += 1;
requestedPage = true;
triggerRefresh(currentApiPage);
}
}
@Override
public void updateSyncStatus(final boolean syncRunning) {
runOnUiThread(new Runnable() {
public void run() {
setSupportProgressBarIndeterminateVisibility(syncRunning);
}
});
}
public abstract void triggerRefresh(int page);
@Override
protected void onPause() {
flushStoriesMarkedRead();
super.onPause();
}
/**
* Log a story as having been read. The local DB and remote server will be updated
* batch-wise when the activity pauses.
*/
protected void addStoryToMarkAsRead(Story story) {
if (story == null) return;
if (story.read) return;
synchronized (this.storiesToMarkAsRead) {
this.storiesToMarkAsRead.add(story);
}
// flush immediately if the batch reaches a sufficient size
if (this.storiesToMarkAsRead.size() >= AppConstants.MAX_MARK_READ_BATCH) {
flushStoriesMarkedRead();
}
if (!this.storiesAlreadySeen.contains(story)) {
// only decrement the cached story count if the story wasn't already read
this.storiesAlreadySeen.add(story);
this.currentUnreadCount--;
}
this.enableOverlays();
}
private void flushStoriesMarkedRead() {
synchronized(this.storiesToMarkAsRead) {
if (this.storiesToMarkAsRead.size() > 0) {
FeedUtils.markStoriesAsRead(this.storiesToMarkAsRead, this);
this.storiesToMarkAsRead.clear();
}
}
}
private void markStoryUnread(Story story) {
// first, ensure the story isn't queued up to be marked as read
this.storiesToMarkAsRead.remove(story);
// next, call the API to un-mark it as read, just in case we missed the batch
// operation, or it was read long before now.
FeedUtils.markStoryUnread(story, Reading.this, this.apiManager);
this.currentUnreadCount++;
this.storiesAlreadySeen.remove(story);
this.enableOverlays();
}
// NB: this callback is for the text size slider
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
getSharedPreferences(PrefConstants.PREFERENCES, 0).edit().putFloat(PrefConstants.PREFERENCE_TEXT_SIZE, (float) progress / AppConstants.FONT_SIZE_INCREMENT_FACTOR).commit();
Intent data = new Intent(ReadingItemFragment.TEXT_SIZE_CHANGED);
data.putExtra(ReadingItemFragment.TEXT_SIZE_VALUE, (float) progress / AppConstants.FONT_SIZE_INCREMENT_FACTOR);
sendBroadcast(data);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
/**
* Click handler for the righthand overlay nav button.
*/
public void overlayRight(View v) {
if (this.currentUnreadCount == 0) {
// if there are no unread stories, go back to the feed list
Intent i = new Intent(this, Main.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
} else {
// if there are unreads, go to the next one
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
nextUnread();
return null;
}
}.execute();
//}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
/**
* Search our set of stories for the next unread one. This requires some heavy
* cooperation with the way stories are automatically loaded in the background
* as we walk through the list.
*/
private void nextUnread() {
synchronized (UNREAD_SEARCH_MUTEX) {
int candidate = 0;
boolean unreadFound = false;
+ boolean error = false;
unreadSearch:while (!unreadFound) {
Story story = readingAdapter.getStory(candidate);
if (story == null) {
if (this.noMoreApiPages) {
// this is odd. if there were no unreads, how was the button even enabled?
Log.e(this.getClass().getName(), "Ran out of stories while looking for unreads.");
- Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} else {
if ((candidate == pager.getCurrentItem()) || (story.read) || (this.storiesAlreadySeen.contains(story))) {
candidate++;
continue unreadSearch;
} else {
unreadFound = true;
break unreadSearch;
}
}
// if we didn't find a story trigger a check to see if there are any more to search before proceeding
this.unreadSearchLatch = new CountDownLatch(1);
this.checkStoryCount(candidate+1);
try {
boolean unlatched = this.unreadSearchLatch.await(UNREAD_SEARCH_LOAD_WAIT_SECONDS, TimeUnit.SECONDS);
if (unlatched) {
continue unreadSearch;
} else {
Log.e(this.getClass().getName(), "Timed out waiting for next API page while looking for unreads.");
- Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} catch (InterruptedException ie) {
Log.e(this.getClass().getName(), "Interrupted waiting for next API page while looking for unreads.");
- Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
}
+ if (error) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ Toast.makeText(Reading.this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
+ }
+ });
+ }
if (unreadFound) {
final int page = candidate;
runOnUiThread(new Runnable() {
public void run() {
pager.setCurrentItem(page, true);
}
});
}
}
}
/**
* Click handler for the lefthand overlay nav button.
*/
public void overlayLeft(View v) {
int targetPosition = this.getLastReadPosition(true);
if (targetPosition != -1) {
pager.setCurrentItem(targetPosition, true);
} else {
Log.e(this.getClass().getName(), "reading history contained item not found in cursor.");
}
}
/**
* Get the pager position of the last story read during this activity or -1 if there is nothing
* in the history.
*
* @param trimHistory optionally trim the history of the currently displayed page iff the
* back button has been pressed.
*/
private int getLastReadPosition(boolean trimHistory) {
synchronized (this.pageHistory) {
// the last item is always the currently shown page, do not count it
if (this.pageHistory.size() < 2) {
return -1;
}
Story targetStory = this.pageHistory.get(this.pageHistory.size()-2);
int targetPosition = this.readingAdapter.getPosition(targetStory);
if (trimHistory && (targetPosition != -1)) {
this.pageHistory.remove(this.pageHistory.size()-1);
}
return targetPosition;
}
}
/**
* Click handler for the progress indicator on the righthand overlay nav button.
*/
public void overlayCount(View v) {
String unreadText = getString((this.currentUnreadCount == 1) ? R.string.overlay_count_toast_1 : R.string.overlay_count_toast_N);
Toast.makeText(this, String.format(unreadText, this.currentUnreadCount), Toast.LENGTH_SHORT).show();
}
}
| false | true | private void nextUnread() {
synchronized (UNREAD_SEARCH_MUTEX) {
int candidate = 0;
boolean unreadFound = false;
unreadSearch:while (!unreadFound) {
Story story = readingAdapter.getStory(candidate);
if (story == null) {
if (this.noMoreApiPages) {
// this is odd. if there were no unreads, how was the button even enabled?
Log.e(this.getClass().getName(), "Ran out of stories while looking for unreads.");
Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} else {
if ((candidate == pager.getCurrentItem()) || (story.read) || (this.storiesAlreadySeen.contains(story))) {
candidate++;
continue unreadSearch;
} else {
unreadFound = true;
break unreadSearch;
}
}
// if we didn't find a story trigger a check to see if there are any more to search before proceeding
this.unreadSearchLatch = new CountDownLatch(1);
this.checkStoryCount(candidate+1);
try {
boolean unlatched = this.unreadSearchLatch.await(UNREAD_SEARCH_LOAD_WAIT_SECONDS, TimeUnit.SECONDS);
if (unlatched) {
continue unreadSearch;
} else {
Log.e(this.getClass().getName(), "Timed out waiting for next API page while looking for unreads.");
Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
} catch (InterruptedException ie) {
Log.e(this.getClass().getName(), "Interrupted waiting for next API page while looking for unreads.");
Toast.makeText(this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
break unreadSearch;
}
}
if (unreadFound) {
final int page = candidate;
runOnUiThread(new Runnable() {
public void run() {
pager.setCurrentItem(page, true);
}
});
}
}
}
| private void nextUnread() {
synchronized (UNREAD_SEARCH_MUTEX) {
int candidate = 0;
boolean unreadFound = false;
boolean error = false;
unreadSearch:while (!unreadFound) {
Story story = readingAdapter.getStory(candidate);
if (story == null) {
if (this.noMoreApiPages) {
// this is odd. if there were no unreads, how was the button even enabled?
Log.e(this.getClass().getName(), "Ran out of stories while looking for unreads.");
break unreadSearch;
}
} else {
if ((candidate == pager.getCurrentItem()) || (story.read) || (this.storiesAlreadySeen.contains(story))) {
candidate++;
continue unreadSearch;
} else {
unreadFound = true;
break unreadSearch;
}
}
// if we didn't find a story trigger a check to see if there are any more to search before proceeding
this.unreadSearchLatch = new CountDownLatch(1);
this.checkStoryCount(candidate+1);
try {
boolean unlatched = this.unreadSearchLatch.await(UNREAD_SEARCH_LOAD_WAIT_SECONDS, TimeUnit.SECONDS);
if (unlatched) {
continue unreadSearch;
} else {
Log.e(this.getClass().getName(), "Timed out waiting for next API page while looking for unreads.");
break unreadSearch;
}
} catch (InterruptedException ie) {
Log.e(this.getClass().getName(), "Interrupted waiting for next API page while looking for unreads.");
break unreadSearch;
}
}
if (error) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Reading.this, R.string.toast_unread_search_error, Toast.LENGTH_LONG).show();
}
});
}
if (unreadFound) {
final int page = candidate;
runOnUiThread(new Runnable() {
public void run() {
pager.setCurrentItem(page, true);
}
});
}
}
}
|
diff --git a/Examples/TantalumS40BBCReader/src/org/tantalum/canvasrssreader/RSSReader.java b/Examples/TantalumS40BBCReader/src/org/tantalum/canvasrssreader/RSSReader.java
index 44de5b02..7bb18383 100644
--- a/Examples/TantalumS40BBCReader/src/org/tantalum/canvasrssreader/RSSReader.java
+++ b/Examples/TantalumS40BBCReader/src/org/tantalum/canvasrssreader/RSSReader.java
@@ -1,154 +1,154 @@
/*
Copyright © 2012 Paul Houghton and Futurice on behalf of the Tantalum Project.
All rights reserved.
Tantalum software shall be used to make the world a better place for everyone.
This software is licensed for use under the Apache 2 open source software license,
http://www.apache.org/licenses/LICENSE-2.0.html
You are kindly requested to return your improvements to this library to the
open source community at http://projects.developer.nokia.com/Tantalum
The above copyright and license notice 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.tantalum.canvasrssreader;
import javax.microedition.lcdui.*;
import org.tantalum.Task;
import org.tantalum.TimeoutException;
import org.tantalum.Worker;
import org.tantalum.j2me.TantalumMIDlet;
import org.tantalum.util.L;
/**
* @author ssaa
*/
public class RSSReader extends TantalumMIDlet implements CommandListener {
// This is read from the JAD-file
public static final String INITIAL_FEED_URL = "http://feeds.bbci.co.uk/news/rss.xml";
private RSSReaderCanvas canvas;
private Displayable currentDisplayable;
public static int COLOR_BACKGROUND;
public static int COLOR_HIGHLIGHTED_BACKGROUND;
public static int COLOR_FOREGROUND;
public static int COLOR_HIGHLIGHTED_FOREGROUND;
public static int COLOR_BORDER;
public static int COLOR_HIGHLIGHTED_BORDER;
public RSSReader() {
super(DEFAULT_NUMBER_OF_WORKER_THREADS);
}
/**
* Switches a current displayable in a display. The
* <code>display</code> instance is taken from
* <code>getDisplay</code> method. This method is used by all actions in the
* design for switching displayable.
*
* @param alert the Alert which is temporarily set to the display; if
* <code>null</code>, then <code>nextDisplayable</code> is set immediately
* @param nextDisplayable the Displayable to be set
*/
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
final Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
}
/**
* Called by a system to indicated that a command has been invoked on a
* particular displayable.
*
* @param command the Command that was invoked
* @param displayable the Displayable where the command was invoked
*/
public void commandAction(Command command, Displayable displayable) {
if (displayable instanceof Alert) {
switchDisplayable(null, currentDisplayable);
}
}
/**
* Returns an initiliazed instance of canvas component.
*
* @return the initialized component instance
*/
public RSSReaderCanvas getCanvas() {
if (canvas == null) {
canvas = new RSSReaderCanvas(this);
}
return canvas;
}
/**
* Shows an error popup
*
* @param errorMessage
*/
public void showError(final String errorMessage) {
Alert alert = new Alert("Error", errorMessage, null, AlertType.ERROR);
alert.addCommand(new Command("Ok", Command.OK, 0));
alert.setCommandListener(this);
alert.setTimeout(Alert.FOREVER);
currentDisplayable = getDisplay().getCurrent();
switchDisplayable(alert, currentDisplayable);
}
/**
* Returns a display instance.
*
* @return the display instance.
*/
public Display getDisplay() {
return Display.getDisplay(this);
}
/**
* Called when MIDlet is started. Checks whether the MIDlet have been
* already started and initialize/starts or resumes the MIDlet.
*/
public void startApp() {
try {
final Task reloadTask = new Task() {
public Object exec(final Object params) {
getCanvas().getListView().reloadAsync(false);
return null;
}
};
final Display display = getDisplay();
COLOR_BACKGROUND = display.getColor(Display.COLOR_BACKGROUND);
COLOR_HIGHLIGHTED_BACKGROUND = display.getColor(Display.COLOR_HIGHLIGHTED_BACKGROUND);
COLOR_FOREGROUND = display.getColor(Display.COLOR_FOREGROUND);
COLOR_HIGHLIGHTED_FOREGROUND = display.getColor(Display.COLOR_HIGHLIGHTED_FOREGROUND);
COLOR_BORDER = display.getColor(Display.COLOR_BORDER);
COLOR_HIGHLIGHTED_BORDER = display.getColor(Display.COLOR_HIGHLIGHTED_BORDER);
try {
- reloadTask.fork().join(1000);
- } catch (TimeoutException ex) {
+ reloadTask.join(200);
+ } catch (Exception ex) {
//#debug
L.e("Startup reloadAsync timeout", "This is normal if loading from the net", ex);
}
switchDisplayable(null, canvas);
} catch (Exception ex) {
//#debug
L.e("Startup execption", "", ex);
Worker.shutdown(false);
}
}
}
| true | true | public void startApp() {
try {
final Task reloadTask = new Task() {
public Object exec(final Object params) {
getCanvas().getListView().reloadAsync(false);
return null;
}
};
final Display display = getDisplay();
COLOR_BACKGROUND = display.getColor(Display.COLOR_BACKGROUND);
COLOR_HIGHLIGHTED_BACKGROUND = display.getColor(Display.COLOR_HIGHLIGHTED_BACKGROUND);
COLOR_FOREGROUND = display.getColor(Display.COLOR_FOREGROUND);
COLOR_HIGHLIGHTED_FOREGROUND = display.getColor(Display.COLOR_HIGHLIGHTED_FOREGROUND);
COLOR_BORDER = display.getColor(Display.COLOR_BORDER);
COLOR_HIGHLIGHTED_BORDER = display.getColor(Display.COLOR_HIGHLIGHTED_BORDER);
try {
reloadTask.fork().join(1000);
} catch (TimeoutException ex) {
//#debug
L.e("Startup reloadAsync timeout", "This is normal if loading from the net", ex);
}
switchDisplayable(null, canvas);
} catch (Exception ex) {
//#debug
L.e("Startup execption", "", ex);
Worker.shutdown(false);
}
}
| public void startApp() {
try {
final Task reloadTask = new Task() {
public Object exec(final Object params) {
getCanvas().getListView().reloadAsync(false);
return null;
}
};
final Display display = getDisplay();
COLOR_BACKGROUND = display.getColor(Display.COLOR_BACKGROUND);
COLOR_HIGHLIGHTED_BACKGROUND = display.getColor(Display.COLOR_HIGHLIGHTED_BACKGROUND);
COLOR_FOREGROUND = display.getColor(Display.COLOR_FOREGROUND);
COLOR_HIGHLIGHTED_FOREGROUND = display.getColor(Display.COLOR_HIGHLIGHTED_FOREGROUND);
COLOR_BORDER = display.getColor(Display.COLOR_BORDER);
COLOR_HIGHLIGHTED_BORDER = display.getColor(Display.COLOR_HIGHLIGHTED_BORDER);
try {
reloadTask.join(200);
} catch (Exception ex) {
//#debug
L.e("Startup reloadAsync timeout", "This is normal if loading from the net", ex);
}
switchDisplayable(null, canvas);
} catch (Exception ex) {
//#debug
L.e("Startup execption", "", ex);
Worker.shutdown(false);
}
}
|
diff --git a/src/org/zaproxy/zap/extension/ascanrulesBeta/SessionFixation.java b/src/org/zaproxy/zap/extension/ascanrulesBeta/SessionFixation.java
index b699764..788633e 100644
--- a/src/org/zaproxy/zap/extension/ascanrulesBeta/SessionFixation.java
+++ b/src/org/zaproxy/zap/extension/ascanrulesBeta/SessionFixation.java
@@ -1,1011 +1,1011 @@
/**
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* 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.zaproxy.zap.extension.ascanrulesBeta;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.core.scanner.AbstractAppPlugin;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Category;
import org.parosproxy.paros.network.HtmlParameter;
import org.parosproxy.paros.network.HtmlParameter.Type;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;
import org.parosproxy.paros.network.HttpStatusCode;
import org.zaproxy.zap.extension.auth.ExtensionAuth;
/**
* The SessionFixation plugin identifies Session Fixation vulnerabilities with
* - cookie fields (a more common scenario, but also more secure, even when the vulnerability occurs)
* - url fields (less common, but also less secure when the vulnerability occurs)
* - session ids built into the url path, and typically extracted by means of url rewriting
* TODO: implement a check for session fixation issues on form parameters (by checking what?? resulting form params?)
*
* @author Colm O'Flaherty, Encription Ireland Ltd
*/
public class SessionFixation extends AbstractAppPlugin {
/**
* plugin dependencies
*/
private static final String[] dependency = {};
/**
* for logging.
*/
private static Logger log = Logger.getLogger(SessionFixation.class);
/**
* determines if we should output Debug level logging
*/
private boolean debugEnabled = log.isDebugEnabled();
@Override
public int getId() {
return 40013;
}
@Override
public String getName() {
return Constant.messages.getString("ascanbeta.sessionfixation.name");
}
@Override
public String[] getDependency() {
return dependency;
}
@Override
public String getDescription() {
return Constant.messages.getString("ascanbeta.sessionfixation.desc");
}
@Override
public int getCategory() {
return Category.MISC;
}
@Override
public String getSolution() {
return Constant.messages.getString("ascanbeta.sessionfixation.soln");
}
@Override
public String getReference() {
return Constant.messages.getString("ascanbeta.sessionfixation.refs");
}
@Override
public void init() {
//DEBUG: turn on for debugging
//TODO: turn this off
//log.setLevel(org.apache.log4j.Level.DEBUG);
//this.debugEnabled = true;
if ( this.debugEnabled ) log.debug("Initialising");
}
/**
* scans all GET, Cookie params for Session fields, and looks for SessionFixation vulnerabilities
*/
@Override
public void scan() {
//TODO: scan the POST (form) params for session id fields.
try {
boolean loginUrl = false;
//are we dealing with the login url? Will be important later
try {
ExtensionAuth extAuth = (ExtensionAuth) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAuth.NAME);
URI loginUri = extAuth.getApi().getLoginRequest(1).getRequestHeader().getURI();
URI requestUri = getBaseMsg().getRequestHeader().getURI();
if ( requestUri.getScheme().equals(loginUri.getScheme()) &&
requestUri.getHost().equals(loginUri.getHost()) &&
requestUri.getPort() == loginUri.getPort() &&
requestUri.getPath().equals(loginUri.getPath()) ) {
//we got this far.. only the method (GET/POST), user details, query params, fragment, and POST params
//are possibly different from the login page.
loginUrl = true;
}
}
catch (Exception e) {
log.debug("For the Session Fixation scanner to actually do anything, a Login Page *must* be set!");
}
//For now (from Zap 2.0), the Session Fixation scanner will only run for logon pages
if (loginUrl == false) return;
//find all params set in the request (GET/POST/Cookie)
//Note: this will be the full set, before we delete anything.
TreeSet<HtmlParameter> htmlParams = new TreeSet<> ();
htmlParams.addAll(getBaseMsg().getRequestHeader().getCookieParams()); //request cookies only. no response cookies
htmlParams.addAll(getBaseMsg().getFormParams()); //add in the POST params
htmlParams.addAll(getBaseMsg().getUrlParams()); //add in the GET params
//Now add in the pseudo parameters set in the URL itself, such as in the following:
//http://www.example.com/someurl;JSESSIONID=abcdefg?x=123&y=456
//as opposed to the url parameters in the following example, which are already picked up by getUrlParams()
//http://www.example.com/someurl?JSESSIONID=abcdefg&x=123&y=456
//get the URL
URI requestUri = getBaseMsg().getRequestHeader().getURI();
//convert from org.apache.commons.httpclient.URI to a String
String requestUrl= "Unknown URL";
try {
requestUrl = new URL (requestUri.getScheme(), requestUri.getHost(), requestUri.getPort(), requestUri.getPath()).toString();
}
catch (Exception e) {
// no point in continuing. The URL is invalid. This is a peculiarity in the Zap core,
// and can happen when
// - the user browsed to http://www.example.com/bodgeit and
// - the user did not browse to http://www.example.com or to http://www.example.com/
// so the Zap GUI displays "http://www.example.com" as a node under "Sites",
// and under that, it displays the actual urls to which the user browsed
// (http://www.example.com/bodgeit, for instance)
// When the user selects the node "http://www.example.com", and tries to scan it with
// the session fixation scanner, the URI that is passed is "http://www.example.com",
// which is *not* a valid url.
// If the user actually browses to "http://www.example.com" (even without the trailing slash)
// the web browser appends the trailing slash, and so Zap records the URI as
// "http://www.example.com/", which IS a valid url, and which can (and should) be scanned.
//
// In short.. if this happens, we do not want to scan the URL anyway
// (because the user never browsed to it), so just do nothing instead.
log.error("Cannot convert URI ["+requestUri+"] to a URL: "+e.getMessage());
return;
}
//suck out any pseudo url parameters from the url
Set<HtmlParameter> pseudoUrlParams = getPseudoUrlParameters (requestUrl);
htmlParams.addAll(pseudoUrlParams);
if ( this.debugEnabled ) log.debug("Pseudo url params of URL ["+ requestUrl+ "] : ["+pseudoUrlParams+"]");
////for each parameter in turn,
//int counter = 0;
for (Iterator<HtmlParameter> iter = htmlParams.iterator(); iter.hasNext(); ) {
HttpMessage msg1Final;
HttpMessage msg1Initial = getNewMsg();
////debug logic only.. to do first field only
//counter ++;
//if ( counter > 1 )
// return;
HtmlParameter currentHtmlParameter = iter.next();
//Useful for debugging, but I can't find a way to view this data in the GUI, so leave it out for now.
//msg1Initial.setNote("Message 1 for parameter "+ currentHtmlParameter);
if ( this.debugEnabled ) log.debug("Scanning URL ["+ msg1Initial.getRequestHeader().getMethod()+ "] ["+ msg1Initial.getRequestHeader().getURI() + "], ["+ currentHtmlParameter.getType()+"] field ["+ currentHtmlParameter.getName() + "] with value ["+currentHtmlParameter.getValue()+"] for Session Fixation");
if ( currentHtmlParameter.getType().equals (HtmlParameter.Type.cookie)) {
//careful to pick up the cookies from the Request, and not to include cookies set in any earlier response
TreeSet <HtmlParameter> cookieRequestParams = msg1Initial.getRequestHeader().getCookieParams();
//delete the original cookie from the parameters
cookieRequestParams.remove(currentHtmlParameter);
msg1Initial.setCookieParams(cookieRequestParams);
//send the message, minus the cookie parameter, and see how it comes back.
//Note: do NOT automatically follow redirects.. handle those here instead.
sendAndReceive(msg1Initial, false, false);
/////////////////////////////
//create a copy of msg1Initial to play with to handle redirects (if any).
//we use a copy because if we change msg1Initial itself, it messes the URL and params displayed on the GUI.
msg1Final=msg1Initial;
HtmlParameter cookieBack1 = getResponseCookie (msg1Initial, currentHtmlParameter.getName());
long cookieBack1TimeReceived = System.currentTimeMillis(); //in ms. when was the cookie received? Important if it has a Max-Age directive
Date cookieBack1ExpiryDate=null;
HttpMessage temp = msg1Initial;
int redirectsFollowed1 = 0;
while ( HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode())) {
//Note that we need to clone the Request and the Response..
//we seem to need to track the secure flag now to make sure its set later
boolean secure1 = temp.getRequestHeader().getSecure();
temp = temp.cloneAll(); //clone the previous message
redirectsFollowed1++;
if ( redirectsFollowed1 > 10 ) {
throw new Exception ("Too many redirects were specified in the first message");
}
//create a new URI from the absolute location returned, and interpret it as escaped
//note that the standard says that the Location returned should be absolute, but it ain't always so...
URI newLocation = new URI (temp.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//and follow the forward url
//need to clear the params (which would come from the initial POST, otherwise)
temp.getRequestHeader().setGetParams(new TreeSet<HtmlParameter>());
temp.setRequestBody("");
temp.setResponseBody(""); //make sure no values accidentally carry from one iteration to the next
try {
temp.getRequestHeader().setURI(newLocation);
} catch (Exception e) {
//the Location field contents may not be standards compliant. Lets generate a uri to use as a workaround where a relative path was
//given instead of an absolute one
URI newLocationWorkaround = new URI(temp.getRequestHeader().getURI(), temp.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//try again, except this time, if it fails, don't try to handle it
if (this.debugEnabled) log.debug("The Location ["+ newLocation + "] specified in a redirect was not valid. Trying workaround url ["+ newLocationWorkaround + "]");
temp.getRequestHeader().setURI(newLocationWorkaround);
}
temp.getRequestHeader().setSecure(secure1);
temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp.getRequestHeader().setContentLength(0); //since we send a GET, the body will be 0 long
if ( cookieBack1 != null) {
//if the previous request sent back a cookie, we need to set that cookie when following redirects, as a browser would
if ( this.debugEnabled ) log.debug("Adding in cookie ["+ cookieBack1+ "] for a redirect");
TreeSet <HtmlParameter> forwardCookieParams = temp.getRequestHeader().getCookieParams();
forwardCookieParams.add(cookieBack1);
temp.getRequestHeader().setCookieParams(forwardCookieParams);
}
if ( this.debugEnabled ) log.debug("DEBUG: Cookie Message 1 causes us to follow redirect to ["+ newLocation +"]");
sendAndReceive(temp, false, false); //do NOT redirect.. handle it here
//handle any cookies set from following redirects that override the cookie set in the redirect itself (if any)
//note that this will handle the case where a latter cookie unsets one set earlier.
HtmlParameter cookieBack1Temp = getResponseCookie (temp, currentHtmlParameter.getName());
if ( cookieBack1Temp != null ) {
cookieBack1 = cookieBack1Temp;
cookieBack1TimeReceived=System.currentTimeMillis(); //in ms. record when we got the cookie.. in case it has a Max-Age directive
}
//reset the "final" version of message1 to use the final response in the chain
msg1Final=temp;
}
///////////////////////////
//if non-200 on the final response for message 1, no point in continuing. Bale out.
if (msg1Final.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg1Final.getResponseHeader().getStatusCode()+"] when sending ["+msg1Initial.getRequestHeader().getURI()+ "] with param ["+ currentHtmlParameter.getName() +"] = NULL (possibly somewhere in the redirects)");
continue;
}
//now check that the response set a cookie. if it didn't, then either..
//1) we are messing with the wrong field
//2) the app doesn't do sessions
//either way, there is not much point in continuing to look at this field..
if ( cookieBack1 == null || cookieBack1.getValue() == null ) {
//no cookie was set, or the cookie param was set to a null value
if ( this.debugEnabled ) log.debug("The Cookie parameter was NOT set in the response, when cookie param ["+ currentHtmlParameter.getName() + "] was set to NULL: "+cookieBack1);
continue;
}
//////////////////////////////////////////////////////////////////////
//at this point, before continuing to check for Session Fixation, do some other checks on the session cookie we got back
//that might cause us to raise additional alerts (in addition to doing the main check for Session Fixation)
//////////////////////////////////////////////////////////////////////
//Check 1: was the session cookie sent and received securely by the server?
//If not, alert this fact
if ( (! msg1Final.getRequestHeader().getSecure()) ||
(! cookieBack1.getFlags().contains("secure")) ) {
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
if (! cookieBack1.getFlags().contains("secure")) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo.secureflagnotset"));
}
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
String attack = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.soln");
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id sent insecurely", or words to that effect.
bingo(risk, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
//////////////////////////////////////////////////////////////////////
//Check 2: is the session cookie that was set accessible to Javascript?
//If so, alert this fact too
if ( ! cookieBack1.getFlags().contains("httponly")) {
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
String attack = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.soln");
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id accessible in Javascript", or words to that effect.
bingo(risk, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
//////////////////////////////////////////////////////////////////////
//Check 3: is the session cookie set to expire soon? when the browser session closes? never?
//the longer the session cookie is valid, the greater the risk. alert it accordingly
String cookieBack1Expiry=null;
int sessionExpiryRiskLevel;
String sessionExpiryDescription = null;
//check for the Expires header
for ( Iterator <String> i = cookieBack1.getFlags().iterator(); i.hasNext(); ) {
String cookieBack1Flag = i.next();
//if ( this.debugEnabled ) log.debug("Cookie back 1 flag (checking for Expires): "+ cookieBack1Flag);
//match in a case insensitive manner. never know what case various web servers are going to send back.
//if (cookieBack1Flag.matches("(?i)expires=.*")) {
if ( cookieBack1Flag.toLowerCase(Locale.ENGLISH).startsWith("expires=")) {
String [] cookieBack1FlagValues = cookieBack1Flag.split("=");
if (cookieBack1FlagValues.length > 1) {
if ( this.debugEnabled ) log.debug("Cookie Expiry: "+ cookieBack1FlagValues[1]);
cookieBack1Expiry=cookieBack1FlagValues[1]; //the Date String
sessionExpiryDescription = cookieBack1FlagValues[1]; //the Date String
cookieBack1ExpiryDate = DateUtil.parseDate(cookieBack1Expiry); //the actual Date
}
}
}
//also check for the Max-Age header, which overrides the Expires header.
//WARNING: this Directive is reported to be ignored by IE, so if both Expires and Max-Age are present
//and we report based on the Max-Age value, but the user is using IE, then the results reported
//by us here may be different from those actually experienced by the user! (we use Max-Age, IE uses Expires)
for ( Iterator <String> i = cookieBack1.getFlags().iterator(); i.hasNext(); ) {
String cookieBack1Flag = i.next();
//if ( this.debugEnabled ) log.debug("Cookie back 1 flag (checking for Max-Age): "+ cookieBack1Flag);
//match in a case insensitive manner. never know what case various web servers are going to send back.
if ( cookieBack1Flag.toLowerCase(Locale.ENGLISH).startsWith("max-age=")) {
String [] cookieBack1FlagValues = cookieBack1Flag.split("=");
if (cookieBack1FlagValues.length > 1) {
//now the Max-Age value is the number of seconds relative to the time the browser received the cookie
//(as stored in cookieBack1TimeReceived)
if ( this.debugEnabled ) log.debug("Cookie Max Age: "+ cookieBack1FlagValues[1]);
long cookie1DropDeadMS = cookieBack1TimeReceived + (Long.parseLong(cookieBack1FlagValues[1])*1000);
cookieBack1ExpiryDate = new Date (cookie1DropDeadMS); //the actual Date the cookie expires (by Max-Age)
cookieBack1Expiry = DateUtil.formatDate(cookieBack1ExpiryDate, DateUtil.PATTERN_RFC1123);
sessionExpiryDescription = cookieBack1Expiry; //needs to the Date String
}
}
}
String sessionExpiryRiskDescription = null;
//check the Expiry/Max-Age details garnered (if any)
//and figure out the risk, depending on whether it is a login page
//and how long the session will live before expiring
if ( cookieBack1ExpiryDate == null ) {
//session expires when the browser closes.. rate this as medium risk?
sessionExpiryRiskLevel = Alert.RISK_MEDIUM;
- sessionExpiryRiskDescription="sessionidexpiry.browserclose";
+ sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.browserclose";
sessionExpiryDescription = Constant.messages.getString(sessionExpiryRiskDescription);
} else {
long datediffSeconds = ( cookieBack1ExpiryDate.getTime() - cookieBack1TimeReceived) / 1000;
long anHourSeconds = 3600;
long aDaySeconds = anHourSeconds * 24;
long aWeekSeconds = aDaySeconds * 7;
if ( datediffSeconds < 0 ) {
if ( this.debugEnabled ) log.debug("The session cookie has expired already");
- sessionExpiryRiskDescription = "sessionidexpiry.timeexpired";
+ sessionExpiryRiskDescription = "ascanbeta.sessionidexpiry.timeexpired";
sessionExpiryRiskLevel = Alert.RISK_INFO; // no risk.. the cookie has expired already
}
else if (datediffSeconds > aWeekSeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than a week!");
- sessionExpiryRiskDescription="sessionidexpiry.timemorethanoneweek";
+ sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timemorethanoneweek";
sessionExpiryRiskLevel = Alert.RISK_HIGH;
}
else if (datediffSeconds > aDaySeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than a day");
- sessionExpiryRiskDescription="sessionidexpiry.timemorethanoneday";
+ sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timemorethanoneday";
sessionExpiryRiskLevel = Alert.RISK_MEDIUM;
}
else if (datediffSeconds > anHourSeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than an hour");
- sessionExpiryRiskDescription="sessionidexpiry.timemorethanonehour";
+ sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timemorethanonehour";
sessionExpiryRiskLevel = Alert.RISK_LOW;
}
else {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for less than an hour!");
- sessionExpiryRiskDescription="sessionidexpiry.timelessthanonehour";
+ sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timelessthanonehour";
sessionExpiryRiskLevel = Alert.RISK_INFO;
}
}
if (! loginUrl) {
//decrement the risk if it's not a login page
sessionExpiryRiskLevel--;
}
//alert it if the default session expiry risk level is more than informational
if (sessionExpiryRiskLevel > Alert.RISK_INFO) {
//pass the original param value here, not the new value
String cookieReceivedTime = cookieBack1Expiry = DateUtil.formatDate( new Date (cookieBack1TimeReceived), DateUtil.PATTERN_RFC1123);
String extraInfo = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue(), sessionExpiryDescription, cookieReceivedTime);
String attack = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidexpiry.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidexpiry.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidexpiry.soln");
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidexpiry.alert.extrainfo.loginpage"));
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session Id Expiry Time is excessive", or words to that effect.
bingo(sessionExpiryRiskLevel, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName(),
sessionExpiryDescription);
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
////////////////////////////////////////////////////////////////////////////////////////////
/// Message 2 - processing starts here
////////////////////////////////////////////////////////////////////////////////////////////
//so now that we know the URL responds with 200 (OK), and that it sets a cookie, lets re-issue the original request,
//but lets add in the new (valid) session cookie that was just issued.
//we will re-send it. the aim is then to see if it accepts the cookie (BAD, in some circumstances),
//or if it issues a new session cookie (GOOD, in most circumstances)
if ( this.debugEnabled ) log.debug("A Cookie was set by the URL for the correct param, when param ["+ currentHtmlParameter.getName() + "] was set to NULL: "+cookieBack1);
//use a copy of msg2Initial, since it has already had the correct cookie removed in the request..
//do NOT use msg2Initial itself, as this will cause both requests in the GUI to show the modified data..
//finally send the second message, and see how it comes back.
HttpMessage msg2Initial= msg1Initial.cloneRequest();
TreeSet<HtmlParameter> cookieParams2Set = msg2Initial.getRequestHeader().getCookieParams();
cookieParams2Set.add(cookieBack1);
msg2Initial.setCookieParams(cookieParams2Set);
//resend the copy of the initial message, but with the valid session cookie added in, to see if it is accepted
//do not automatically follow redirects, as we need to check these for cookies being set.
sendAndReceive(msg2Initial, false, false);
//create a copy of msg2Initial to play with to handle redirects (if any).
//we use a copy because if we change msg2Initial itself, it messes the URL and params displayed on the GUI.
HttpMessage temp2 = msg2Initial;
HttpMessage msg2Final=msg2Initial;
HtmlParameter cookieBack2Previous=cookieBack1;
HtmlParameter cookieBack2 = getResponseCookie (msg2Initial, currentHtmlParameter.getName());
int redirectsFollowed2 = 0;
while ( HttpStatusCode.isRedirection(temp2.getResponseHeader().getStatusCode())) {
//clone the previous message
boolean secure2 = temp2.getRequestHeader().getSecure();
temp2 = temp2.cloneAll();
redirectsFollowed2++;
if ( redirectsFollowed2 > 10 ) {
throw new Exception ("Too many redirects were specified in the second message");
}
//create a new URI from the absolute location returned, and interpret it as escaped
//note that the standard says that the Location returned should be absolute, but it ain't always so...
URI newLocation = new URI (temp2.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//and follow the forward url
//need to clear the params (which would come from the initial POST, otherwise)
temp2.getRequestHeader().setGetParams(new TreeSet<HtmlParameter>());
temp2.setRequestBody("");
temp2.setResponseBody(""); //make sure no values accidentally carry from one iteration to the next
try {
temp2.getRequestHeader().setURI(newLocation);
} catch (Exception e) {
//the Location field contents may not be standards compliant. Lets generate a uri to use as a workaround where a relative path was
//given instead of an absolute one
URI newLocationWorkaround = new URI(temp2.getRequestHeader().getURI(), temp2.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//try again, except this time, if it fails, don't try to handle it
if (this.debugEnabled) log.debug("The Location ["+ newLocation + "] specified in a redirect was not valid. Trying workaround url ["+ newLocationWorkaround + "]");
temp2.getRequestHeader().setURI(newLocationWorkaround);
}
temp2.getRequestHeader().setSecure(secure2);
temp2.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp2.getRequestHeader().setContentLength(0); //since we send a GET, the body will be 0 long
if ( cookieBack2 != null) {
//if the previous request sent back a cookie, we need to set that cookie when following redirects, as a browser would
//also make sure to delete the previous value set for the cookie value
if ( this.debugEnabled ) {
log.debug("Deleting old cookie ["+ cookieBack2Previous + "], and adding in cookie ["+ cookieBack2+ "] for a redirect");
}
TreeSet <HtmlParameter> forwardCookieParams = temp2.getRequestHeader().getCookieParams();
forwardCookieParams.remove(cookieBack2Previous);
forwardCookieParams.add(cookieBack2);
temp2.getRequestHeader().setCookieParams(forwardCookieParams);
}
sendAndReceive(temp2, false, false); //do NOT automatically redirect.. handle redirects here
//handle any cookies set from following redirects that override the cookie set in the redirect itself (if any)
//note that this will handle the case where a latter cookie unsets one set earlier.
HtmlParameter cookieBack2Temp = getResponseCookie (temp2, currentHtmlParameter.getName());
if ( cookieBack2Temp != null ) {
cookieBack2Previous=cookieBack2;
cookieBack2 = cookieBack2Temp;
}
//reset the "final" version of message2 to use the final response in the chain
msg2Final=temp2;
}
if ( this.debugEnabled ) log.debug("Done following redirects");
//final result was non-200, no point in continuing. Bale out.
if (msg2Final.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg2Final.getResponseHeader().getStatusCode()+"] when sending ["+msg2Initial.getRequestHeader().getURI()+ "] with a borrowed cookie (or by following a redirect) for param ["+currentHtmlParameter.getName()+"]");
continue; //to next parameter
}
//and what we've been waiting for.. do we get a *different* cookie being set in the response of message 2??
//or do we get a new cookie back at all?
//No cookie back => the borrowed cookie was accepted. Not ideal
//Cookie back, but same as the one we sent in => the borrowed cookie was accepted. Not ideal
if ( (cookieBack2== null) || cookieBack2.getValue().equals(cookieBack1.getValue())) {
//no cookie back, when a borrowed cookie is in use.. suspicious!
//use the cookie extrainfo message, which is specific to the case of cookies
//pretty much everything else is generic to all types of Session Fixation vulnerabilities
String extraInfo = Constant.messages.getString("ascanbeta.sessionfixation.alert.cookie.extrainfo", currentHtmlParameter.getName(), cookieBack1.getValue(), (cookieBack2== null?"NULL": cookieBack2.getValue()));
String attack = Constant.messages.getString("ascanbeta.sessionfixation.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionfixation.alert.cookie.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
bingo(risk, Alert.WARNING, msg2Initial.getRequestHeader().getURI().getURI(), currentHtmlParameter.getName(), attack, extraInfo, msg2Initial);
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionfixation.alert.logmessage", msg2Initial.getRequestHeader().getMethod(), msg2Initial.getRequestHeader().getURI().getURI(), currentHtmlParameter.getType(), currentHtmlParameter.getName());
log.info(logMessage);
//}
}
continue; //jump to the next iteration of the loop (ie, the next parameter)
} //end of the cookie code.
//start of the url parameter code
//note that this actually caters for
//- actual URL parameters
//- pseudo URL parameters, where the sessionid was in the path portion of the URL, in conjunction with URL re-writing
if ( currentHtmlParameter.getType().equals (HtmlParameter.Type.url)) {
boolean isPseudoUrlParameter=false; //is this "url parameter" actually a url parameter, or was it path of the path (+url re-writing)?
String possibleSessionIdIssuedForUrlParam=null;
//remove the named url parameter from the request..
TreeSet <HtmlParameter> urlRequestParams = msg1Initial.getUrlParams(); //get parameters?
if ( ! urlRequestParams.remove(currentHtmlParameter)) {
isPseudoUrlParameter=true;
//was not removed because it was a pseudo Url parameter, not a real url parameter.. (so it would not be in the url params)
//in this case, we will need to "rewrite" (ie hack) the URL path to remove the pseudo url parameter portion
//ie, we need to remove the ";jsessionid=<sessionid>" bit from the path (assuming the current field is named 'jsessionid')
//and replace it with ";jsessionid=" (ie, we nullify the possible "session" parameter in the hope that a new session will be issued)
//then we continue as usual to see if the URL is vulnerable to a Session Fixation issue
//Side note: quote the string to search for, and the replacement, so that regex special characters are treated as literals
String hackedUrl = requestUrl.replaceAll(
Pattern.quote(";"+ currentHtmlParameter.getName()+"=" + currentHtmlParameter.getValue()),
Matcher.quoteReplacement(";"+currentHtmlParameter.getName()+"="));
if (this.debugEnabled) log.debug("Removing the pseudo URL parameter from ["+requestUrl+"]: ["+hackedUrl+"]");
//Note: the URL is not escaped. Handle it.
msg1Initial.getRequestHeader().setURI(new URI(hackedUrl, false));
}
msg1Initial.setGetParams(urlRequestParams); //url parameters
//send the message, minus the value for the current parameter, and see how it comes back.
//Note: automatically follow redirects.. no need to look at any intermediate responses.
//this was only necessary for cookie-based session implementations
sendAndReceive(msg1Initial);
//if non-200 on the response for message 1, no point in continuing. Bale out.
if (msg1Initial.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg1Initial.getResponseHeader().getStatusCode()+"] when sending ["+msg1Initial.getRequestHeader().getURI()+ "] with param ["+ currentHtmlParameter.getName() +"] = NULL (possibly somewhere in the redirects)");
continue;
}
//now parse the HTML response for urls that contain the same parameter name, and look at the values for that parameter
//if no values are found for the parameter, then
//1) we are messing with the wrong field, or
//2) the app doesn't do sessions
//either way, there is not much point in continuing to look at this field..
//parse out links in HTML (assume for a moment that all the URLs are in links)
//this gives us a map of parameter value for the current parameter, to the number of times it was encountered in links in the HTML
SortedMap <String, Integer> parametersInHTMLURls = getParameterValueCountInHtml (msg1Initial.getResponseBody().toString(), currentHtmlParameter.getName(), isPseudoUrlParameter);
if (this.debugEnabled) log.debug("The count of the various values of the ["+ currentHtmlParameter.getName() + "] parameters in urls in the result of retrieving the url with a null value for parameter ["+ currentHtmlParameter.getName() + "]: "+ parametersInHTMLURls);
if (parametersInHTMLURls.isEmpty()) {
//setting the param to NULL did not cause any new values to be generated for it in the output..
//so either..
//it is not a session field, or
//it is a session field, but a session is only issued on authentication, and this is not an authentication url
//the app doesn't do sessions (etc)
//either way, the parameter/url combo is not vulnerable, so continue with the next parameter
if ( this.debugEnabled) log.debug("The URL parameter ["+ currentHtmlParameter.getName() + "] was NOT set in any links in the response, when "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "] was set to NULL in the request, so it is likely not a session id field");
continue; //to the next parameter
} else if (parametersInHTMLURls.size() == 1) {
//the parameter was set to just one value in the output
//so it's quite possible it is the session id field that we have been looking for
//caveat 1: check it is longer than 3 chars long, to remove false positives..
//we assume here that a real session id will always be greater than 3 characters long
//caveat 2: the value we got back for the param must be different from the value we
//over-wrote with NULL (empty) in the first place, otherwise it is very unlikely to
//be a session id field
possibleSessionIdIssuedForUrlParam=parametersInHTMLURls.firstKey();
//did we get back the same value we just nulled out in the original request?
//if so, use this to eliminate false positives, and to optimise.
if ( possibleSessionIdIssuedForUrlParam.equals (currentHtmlParameter.getValue())) {
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes 1 distinct values to be set for it in URLs in the output, but the possible session id value ["+ possibleSessionIdIssuedForUrlParam + "] is the same as the value we over-wrote with NULL. 'Sorry, kid. You got the gift, but it looks like you're waiting for something'");
continue; //to the next parameter
}
if (possibleSessionIdIssuedForUrlParam.length() > 3) {
//raise an alert here on an exposed session id, even if it is not subject to a session fixation vulnerability
//log.info("The URL parameter ["+ currentHtmlParameter.getName() + "] was set ["+ parametersInHTMLURls.get(possibleSessionIdIssuedForUrlParam)+ "] times to ["+ possibleSessionIdIssuedForUrlParam + "] in links in the response, when "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "] was set to NULL in the request. This likely indicates it is a session id field.");
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
String attack = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.attack", (isPseudoUrlParameter?"pseudo/URL rewritten ":"") + currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidexposedinurl.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidexposedinurl.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidexposedinurl.soln");
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.extrainfo.loginpage"));
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id exposed in url", or words to that effect.
bingo(Alert.RISK_MEDIUM, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
(isPseudoUrlParameter?"pseudo ":"") +currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
else {
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes 1 distinct values to be set for it in URLs in the output, but the possible session id value ["+ possibleSessionIdIssuedForUrlParam + "] is too short to be a real session id.");
continue; //to the next parameter
}
} else {
//strange scenario: setting the param to null causes multiple different values to be set for it in the output
//it could still be a session parameter, but we assume it is *not* a session id field
//log it, but assume it is not a session id
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes ["+ parametersInHTMLURls.size() + "] distinct values to be set for it in URLs in the output. Assuming it is NOT a session id as a consequence. This could be a false negative");
continue; //to the next parameter
}
////////////////////////////////////////////////////////////////////////////////////////////
/// Message 2 - processing starts here
////////////////////////////////////////////////////////////////////////////////////////////
//we now have a plausible session id field to play with, so set it to a borrowed value.
//ie: lets re-send the request, but add in the new (valid) session value that was just issued.
//the aim is then to see if it accepts the session without re-issuing the session id (BAD, in some circumstances),
//or if it issues a new session value (GOOD, in most circumstances)
//and set the (modified) session for the second message
//use a copy of msg2Initial, since it has already had the correct session removed in the request..
//do NOT use msg2Initial itself, as this will cause both requests in the GUI to show the modified data..
//finally send the second message, and see how it comes back.
HttpMessage msg2Initial= msg1Initial.cloneRequest();
//set the parameter to the new session id value (in different manners, depending on whether it is a real url param, or a pseudo url param)
if ( isPseudoUrlParameter ) {
//we need to "rewrite" (hack) the URL path to remove the pseudo url parameter portion
//id, we need to remove the ";jsessionid=<sessionid>" bit from the path
//and replace it with ";jsessionid=" (ie, we nullify the possible "session" parameter in the hope that a new session will be issued)
//then we continue as usual to see if the URL is vulnerable to a Session Fixation issue
//Side note: quote the string to search for, and the replacement, so that regex special characters are treated as literals
String hackedUrl = requestUrl.replaceAll(
Pattern.quote(";"+ currentHtmlParameter.getName()+"=" + currentHtmlParameter.getValue()),
Matcher.quoteReplacement(";" +currentHtmlParameter.getName()+"="+ possibleSessionIdIssuedForUrlParam));
if (this.debugEnabled) log.debug("Changing the pseudo URL parameter from ["+requestUrl+"]: ["+hackedUrl+"]");
//Note: the URL is not escaped
msg2Initial.getRequestHeader().setURI(new URI(hackedUrl, false));
msg2Initial.setGetParams(msg1Initial.getUrlParams()); //restore the GET params
} else {
//do it via the normal url parameters
TreeSet <HtmlParameter> urlRequestParams2 = msg2Initial.getUrlParams();
urlRequestParams2.add(new HtmlParameter(Type.url, currentHtmlParameter.getName(), possibleSessionIdIssuedForUrlParam));
msg2Initial.setGetParams(urlRequestParams2); //restore the GET params
}
//resend a copy of the initial message, but with the new valid session parameter added in, to see if it is accepted
//automatically follow redirects, which are irrelevant for the purposes of testing URL parameters
sendAndReceive(msg2Initial);
//final result was non-200, no point in continuing. Bale out.
if (msg2Initial.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg2Initial.getResponseHeader().getStatusCode()+"] when sending ["+msg2Initial.getRequestHeader().getURI()+ "] with a borrowed session (or by following a redirect) for param ["+currentHtmlParameter.getName()+"]");
continue; //next field!
}
//do the analysis on the parameters in link urls in the HTML output again to see if the session id was regenerated
SortedMap <String, Integer> parametersInHTMLURls2 = getParameterValueCountInHtml (msg2Initial.getResponseBody().toString(), currentHtmlParameter.getName(), isPseudoUrlParameter);
if ( this.debugEnabled ) log.debug("The count of the various values of the ["+ currentHtmlParameter.getName() + "] parameters in urls in the result of retrieving the url with a borrowed session value for parameter ["+ currentHtmlParameter.getName() + "]: "+ parametersInHTMLURls2);
if ( parametersInHTMLURls2.size() != 1) {
//either no values, or multiple values, but not 1 value. For a session that was regenerated, we would have expected to see
//just 1 new value
if (this.debugEnabled) log.debug("The HTML has spoken. ["+currentHtmlParameter.getName()+"] doesn't look like a session id field, because there are "+parametersInHTMLURls2.size()+" distinct values for this parameter in urls in the HTML output");
continue;
}
//there is but one value for this param in links in the HTML output. But is it vulnerable to Session Fixation? Ie, is it the same parameter?
String possibleSessionIdIssuedForUrlParam2=parametersInHTMLURls2.firstKey();
if ( possibleSessionIdIssuedForUrlParam2.equals (possibleSessionIdIssuedForUrlParam)) {
//same sessionid used in the output.. so it is likely that we have a SessionFixation issue..
//use the url param extrainfo message, which is specific to the case of url parameters and url re-writing Session Fixation issue
//pretty much everything else is generic to all types of Session Fixation vulnerabilities
String extraInfo = Constant.messages.getString("ascanbeta.sessionfixation.alert.url.extrainfo", currentHtmlParameter.getName(), possibleSessionIdIssuedForUrlParam, possibleSessionIdIssuedForUrlParam2);
String attack = Constant.messages.getString("ascanbeta.sessionfixation.alert.attack", (isPseudoUrlParameter?"pseudo/URL rewritten ":"") + currentHtmlParameter.getType(), currentHtmlParameter.getName());
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionfixation.alert.url.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
bingo(risk, Alert.WARNING, getBaseMsg().getRequestHeader().getURI().getURI(), currentHtmlParameter.getName(), attack, extraInfo, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionfixation.alert.logmessage", getBaseMsg().getRequestHeader().getMethod(), getBaseMsg().getRequestHeader().getURI().getURI(), (isPseudoUrlParameter?"pseudo ":"") +currentHtmlParameter.getType(), currentHtmlParameter.getName());
log.info(logMessage);
//}
continue; //jump to the next iteration of the loop (ie, the next parameter)
}
else {
//different sessionid used in the output.. so it is unlikely that we have a SessionFixation issue..
//more likely that the Session is being re-issued for every single request, or we have issues a login request, which
//normally causes a session to be reissued
if (this.debugEnabled) log.debug("The "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"") + " parameter ["+currentHtmlParameter.getName() + "] in url ["+ getBaseMsg().getRequestHeader().getMethod()+ "] ["+ getBaseMsg().getRequestHeader().getURI() + "] changes with requests, and so it likely not vulnerable to Session Fixation");
}
continue; //onto the next parameter
} //end of the url parameter code.
} //end of the for loop around the parameter list
} catch (Exception e) {
//Do not try to internationalise this.. we need an error message in any event..
//if it's in English, it's still better than not having it at all.
log.error("An error occurred checking a url for Session Fixation issues", e);
}
}
/**
* finds and returns the cookie matching the specified cookie name from the message response.
* @param message
* @param cookieName
* @return the HtmlParameter representing the cookie, or null if no matching cookie was found
*/
private HtmlParameter getResponseCookie (HttpMessage message, String cookieName) {
TreeSet<HtmlParameter> cookieBackParams = message.getResponseHeader().getCookieParams();
if ( cookieBackParams.size() == 0) {
//no cookies
return null;
}
for (Iterator <HtmlParameter> i = cookieBackParams.iterator(); i.hasNext(); ) {
HtmlParameter tempparam = i.next();
if ( tempparam.getName().equals(cookieName)) {
//found it. return it.
return tempparam;
}
}
//there were cookies, but none matching the name
return null;
}
/**
* returns a SortedMap of the count for the various values of the parameter specified, as found in links in the HTML
* @param html the HTML containing links to be parsed
* @param parametername the parameter to look for in links in the HTML
* @param pseudoUrlParameter is the parameter contained in the url itself, and processed using URL rewriting?
* @return
*/
private SortedMap <String, Integer> getParameterValueCountInHtml (String html, String parametername, boolean pseudoUrlParameter) throws Exception {
TreeMap <String, Integer> parametersInHTMLURls = new TreeMap <> ();
Source source=new Source (html);
//for now, just look at the HREF attribue in <a> tags (ie, in links in the HTML output)
List<Element> elementList=source.getAllElements(HTMLElementName.A);
for (Element element : elementList) {
if (element.getAttributes()!=null) {
String urlInResults = element.getAttributeValue("href");
if (this.debugEnabled) log.debug("A HREF in the HTML results of request with NULL value for parameter ["+parametername +"]: "+ urlInResults);
if ( urlInResults!= null) {
//now parse out and count the value of the url parm with the name: currentHtmlParameter.getName()
//depending on the type of url parameter, get the parameters set in the output by one of two mechanisms
Set<HtmlParameter> urlParams = null;
//it is a regular url parameter,so look at the regular url parameters in the links in the output
if (pseudoUrlParameter) {
urlParams = getPseudoUrlParameters (urlInResults);
if ( this.debugEnabled ) log.debug("Pseudo url params of Link URL ["+ urlInResults+ "] : ["+urlParams+"]");
}
else {
HttpMessage messageUrlInResults=null;
try {
messageUrlInResults = new HttpMessage (new URI(urlInResults,false));
}
catch (HttpMalformedHeaderException e) {
//the url is in the href is likely not valid. skip to the nexe one.
if ( this.debugEnabled ) log.debug ("URL ["+urlInResults + "] found in HTML results does not seem to be valid, and cannot be analysed for session ids. Skipping it.");
continue;
}
urlParams = messageUrlInResults.getUrlParams();
}
//now aggregate the param values by value, counting how many times we see each value.
for (Iterator<HtmlParameter> iterParamsInHRef = urlParams.iterator(); iterParamsInHRef.hasNext();) {
HtmlParameter urlParameter = iterParamsInHRef.next();
//if this parameter of the url returned matches the parameter name we are playing with
//record the value (and the number of instances in total found)
if (urlParameter.getName().equals(parametername)) {
//if (this.debugEnabled) log.debug("Found a match for the parameter ["+currentHtmlParameter.getName() +"] in a url in the results: "+urlParameter.getValue());
Integer parameterValueCount = parametersInHTMLURls.get(urlParameter.getValue());
if ( parameterValueCount == null) {
parameterValueCount = Integer.valueOf (0);
}
//increment the count for this particular value of the parameter and store it
parameterValueCount=parameterValueCount.intValue()+1;
parametersInHTMLURls.put(urlParameter.getValue(), parameterValueCount);
}
}
}
}
}
//we're outta here for the current url
return parametersInHTMLURls;
}
/**
* returns a Set of HtmlParameters (of type url) corresponding to pseudo URL parameters in the url
* @param url the url to parse for pseudo url parameters
* @return a Set of HtmlParameters
*/
Set <HtmlParameter> getPseudoUrlParameters (String url) {
TreeSet <HtmlParameter> pseudoUrlParams = new TreeSet <>();
String [] urlBreakdown = url.split("\\?"); //do this to get rid of parameters.. we just want the path (but we can live with the scheme, host, port, etc)
String[] pseudoUrlParamNames = urlBreakdown[0].split(";");
//start with the bit *after* the first ";", ie, start with i = 1
for (int i = 1; i<pseudoUrlParamNames.length; i++ ) {
//parse out the possible pseudo url parameters into x=y
String[] pseudoUrlParamKeyValue=pseudoUrlParamNames[i].split("=");
if (pseudoUrlParamKeyValue.length == 2) { //x=y should break into 2 parts.. no more, no less
if ( this.debugEnabled ) log.debug("Pseudo url arguments: ["+ pseudoUrlParamKeyValue[0] + "]= ["+pseudoUrlParamKeyValue[1]+"]");
//store it
pseudoUrlParams.add(new HtmlParameter(Type.url, pseudoUrlParamKeyValue[0], pseudoUrlParamKeyValue[1]));
}
}
//return them
return pseudoUrlParams;
}
@Override
public int getRisk() {
return Alert.RISK_HIGH;
}
}
| false | true | public void scan() {
//TODO: scan the POST (form) params for session id fields.
try {
boolean loginUrl = false;
//are we dealing with the login url? Will be important later
try {
ExtensionAuth extAuth = (ExtensionAuth) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAuth.NAME);
URI loginUri = extAuth.getApi().getLoginRequest(1).getRequestHeader().getURI();
URI requestUri = getBaseMsg().getRequestHeader().getURI();
if ( requestUri.getScheme().equals(loginUri.getScheme()) &&
requestUri.getHost().equals(loginUri.getHost()) &&
requestUri.getPort() == loginUri.getPort() &&
requestUri.getPath().equals(loginUri.getPath()) ) {
//we got this far.. only the method (GET/POST), user details, query params, fragment, and POST params
//are possibly different from the login page.
loginUrl = true;
}
}
catch (Exception e) {
log.debug("For the Session Fixation scanner to actually do anything, a Login Page *must* be set!");
}
//For now (from Zap 2.0), the Session Fixation scanner will only run for logon pages
if (loginUrl == false) return;
//find all params set in the request (GET/POST/Cookie)
//Note: this will be the full set, before we delete anything.
TreeSet<HtmlParameter> htmlParams = new TreeSet<> ();
htmlParams.addAll(getBaseMsg().getRequestHeader().getCookieParams()); //request cookies only. no response cookies
htmlParams.addAll(getBaseMsg().getFormParams()); //add in the POST params
htmlParams.addAll(getBaseMsg().getUrlParams()); //add in the GET params
//Now add in the pseudo parameters set in the URL itself, such as in the following:
//http://www.example.com/someurl;JSESSIONID=abcdefg?x=123&y=456
//as opposed to the url parameters in the following example, which are already picked up by getUrlParams()
//http://www.example.com/someurl?JSESSIONID=abcdefg&x=123&y=456
//get the URL
URI requestUri = getBaseMsg().getRequestHeader().getURI();
//convert from org.apache.commons.httpclient.URI to a String
String requestUrl= "Unknown URL";
try {
requestUrl = new URL (requestUri.getScheme(), requestUri.getHost(), requestUri.getPort(), requestUri.getPath()).toString();
}
catch (Exception e) {
// no point in continuing. The URL is invalid. This is a peculiarity in the Zap core,
// and can happen when
// - the user browsed to http://www.example.com/bodgeit and
// - the user did not browse to http://www.example.com or to http://www.example.com/
// so the Zap GUI displays "http://www.example.com" as a node under "Sites",
// and under that, it displays the actual urls to which the user browsed
// (http://www.example.com/bodgeit, for instance)
// When the user selects the node "http://www.example.com", and tries to scan it with
// the session fixation scanner, the URI that is passed is "http://www.example.com",
// which is *not* a valid url.
// If the user actually browses to "http://www.example.com" (even without the trailing slash)
// the web browser appends the trailing slash, and so Zap records the URI as
// "http://www.example.com/", which IS a valid url, and which can (and should) be scanned.
//
// In short.. if this happens, we do not want to scan the URL anyway
// (because the user never browsed to it), so just do nothing instead.
log.error("Cannot convert URI ["+requestUri+"] to a URL: "+e.getMessage());
return;
}
//suck out any pseudo url parameters from the url
Set<HtmlParameter> pseudoUrlParams = getPseudoUrlParameters (requestUrl);
htmlParams.addAll(pseudoUrlParams);
if ( this.debugEnabled ) log.debug("Pseudo url params of URL ["+ requestUrl+ "] : ["+pseudoUrlParams+"]");
////for each parameter in turn,
//int counter = 0;
for (Iterator<HtmlParameter> iter = htmlParams.iterator(); iter.hasNext(); ) {
HttpMessage msg1Final;
HttpMessage msg1Initial = getNewMsg();
////debug logic only.. to do first field only
//counter ++;
//if ( counter > 1 )
// return;
HtmlParameter currentHtmlParameter = iter.next();
//Useful for debugging, but I can't find a way to view this data in the GUI, so leave it out for now.
//msg1Initial.setNote("Message 1 for parameter "+ currentHtmlParameter);
if ( this.debugEnabled ) log.debug("Scanning URL ["+ msg1Initial.getRequestHeader().getMethod()+ "] ["+ msg1Initial.getRequestHeader().getURI() + "], ["+ currentHtmlParameter.getType()+"] field ["+ currentHtmlParameter.getName() + "] with value ["+currentHtmlParameter.getValue()+"] for Session Fixation");
if ( currentHtmlParameter.getType().equals (HtmlParameter.Type.cookie)) {
//careful to pick up the cookies from the Request, and not to include cookies set in any earlier response
TreeSet <HtmlParameter> cookieRequestParams = msg1Initial.getRequestHeader().getCookieParams();
//delete the original cookie from the parameters
cookieRequestParams.remove(currentHtmlParameter);
msg1Initial.setCookieParams(cookieRequestParams);
//send the message, minus the cookie parameter, and see how it comes back.
//Note: do NOT automatically follow redirects.. handle those here instead.
sendAndReceive(msg1Initial, false, false);
/////////////////////////////
//create a copy of msg1Initial to play with to handle redirects (if any).
//we use a copy because if we change msg1Initial itself, it messes the URL and params displayed on the GUI.
msg1Final=msg1Initial;
HtmlParameter cookieBack1 = getResponseCookie (msg1Initial, currentHtmlParameter.getName());
long cookieBack1TimeReceived = System.currentTimeMillis(); //in ms. when was the cookie received? Important if it has a Max-Age directive
Date cookieBack1ExpiryDate=null;
HttpMessage temp = msg1Initial;
int redirectsFollowed1 = 0;
while ( HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode())) {
//Note that we need to clone the Request and the Response..
//we seem to need to track the secure flag now to make sure its set later
boolean secure1 = temp.getRequestHeader().getSecure();
temp = temp.cloneAll(); //clone the previous message
redirectsFollowed1++;
if ( redirectsFollowed1 > 10 ) {
throw new Exception ("Too many redirects were specified in the first message");
}
//create a new URI from the absolute location returned, and interpret it as escaped
//note that the standard says that the Location returned should be absolute, but it ain't always so...
URI newLocation = new URI (temp.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//and follow the forward url
//need to clear the params (which would come from the initial POST, otherwise)
temp.getRequestHeader().setGetParams(new TreeSet<HtmlParameter>());
temp.setRequestBody("");
temp.setResponseBody(""); //make sure no values accidentally carry from one iteration to the next
try {
temp.getRequestHeader().setURI(newLocation);
} catch (Exception e) {
//the Location field contents may not be standards compliant. Lets generate a uri to use as a workaround where a relative path was
//given instead of an absolute one
URI newLocationWorkaround = new URI(temp.getRequestHeader().getURI(), temp.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//try again, except this time, if it fails, don't try to handle it
if (this.debugEnabled) log.debug("The Location ["+ newLocation + "] specified in a redirect was not valid. Trying workaround url ["+ newLocationWorkaround + "]");
temp.getRequestHeader().setURI(newLocationWorkaround);
}
temp.getRequestHeader().setSecure(secure1);
temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp.getRequestHeader().setContentLength(0); //since we send a GET, the body will be 0 long
if ( cookieBack1 != null) {
//if the previous request sent back a cookie, we need to set that cookie when following redirects, as a browser would
if ( this.debugEnabled ) log.debug("Adding in cookie ["+ cookieBack1+ "] for a redirect");
TreeSet <HtmlParameter> forwardCookieParams = temp.getRequestHeader().getCookieParams();
forwardCookieParams.add(cookieBack1);
temp.getRequestHeader().setCookieParams(forwardCookieParams);
}
if ( this.debugEnabled ) log.debug("DEBUG: Cookie Message 1 causes us to follow redirect to ["+ newLocation +"]");
sendAndReceive(temp, false, false); //do NOT redirect.. handle it here
//handle any cookies set from following redirects that override the cookie set in the redirect itself (if any)
//note that this will handle the case where a latter cookie unsets one set earlier.
HtmlParameter cookieBack1Temp = getResponseCookie (temp, currentHtmlParameter.getName());
if ( cookieBack1Temp != null ) {
cookieBack1 = cookieBack1Temp;
cookieBack1TimeReceived=System.currentTimeMillis(); //in ms. record when we got the cookie.. in case it has a Max-Age directive
}
//reset the "final" version of message1 to use the final response in the chain
msg1Final=temp;
}
///////////////////////////
//if non-200 on the final response for message 1, no point in continuing. Bale out.
if (msg1Final.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg1Final.getResponseHeader().getStatusCode()+"] when sending ["+msg1Initial.getRequestHeader().getURI()+ "] with param ["+ currentHtmlParameter.getName() +"] = NULL (possibly somewhere in the redirects)");
continue;
}
//now check that the response set a cookie. if it didn't, then either..
//1) we are messing with the wrong field
//2) the app doesn't do sessions
//either way, there is not much point in continuing to look at this field..
if ( cookieBack1 == null || cookieBack1.getValue() == null ) {
//no cookie was set, or the cookie param was set to a null value
if ( this.debugEnabled ) log.debug("The Cookie parameter was NOT set in the response, when cookie param ["+ currentHtmlParameter.getName() + "] was set to NULL: "+cookieBack1);
continue;
}
//////////////////////////////////////////////////////////////////////
//at this point, before continuing to check for Session Fixation, do some other checks on the session cookie we got back
//that might cause us to raise additional alerts (in addition to doing the main check for Session Fixation)
//////////////////////////////////////////////////////////////////////
//Check 1: was the session cookie sent and received securely by the server?
//If not, alert this fact
if ( (! msg1Final.getRequestHeader().getSecure()) ||
(! cookieBack1.getFlags().contains("secure")) ) {
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
if (! cookieBack1.getFlags().contains("secure")) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo.secureflagnotset"));
}
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
String attack = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.soln");
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id sent insecurely", or words to that effect.
bingo(risk, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
//////////////////////////////////////////////////////////////////////
//Check 2: is the session cookie that was set accessible to Javascript?
//If so, alert this fact too
if ( ! cookieBack1.getFlags().contains("httponly")) {
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
String attack = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.soln");
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id accessible in Javascript", or words to that effect.
bingo(risk, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
//////////////////////////////////////////////////////////////////////
//Check 3: is the session cookie set to expire soon? when the browser session closes? never?
//the longer the session cookie is valid, the greater the risk. alert it accordingly
String cookieBack1Expiry=null;
int sessionExpiryRiskLevel;
String sessionExpiryDescription = null;
//check for the Expires header
for ( Iterator <String> i = cookieBack1.getFlags().iterator(); i.hasNext(); ) {
String cookieBack1Flag = i.next();
//if ( this.debugEnabled ) log.debug("Cookie back 1 flag (checking for Expires): "+ cookieBack1Flag);
//match in a case insensitive manner. never know what case various web servers are going to send back.
//if (cookieBack1Flag.matches("(?i)expires=.*")) {
if ( cookieBack1Flag.toLowerCase(Locale.ENGLISH).startsWith("expires=")) {
String [] cookieBack1FlagValues = cookieBack1Flag.split("=");
if (cookieBack1FlagValues.length > 1) {
if ( this.debugEnabled ) log.debug("Cookie Expiry: "+ cookieBack1FlagValues[1]);
cookieBack1Expiry=cookieBack1FlagValues[1]; //the Date String
sessionExpiryDescription = cookieBack1FlagValues[1]; //the Date String
cookieBack1ExpiryDate = DateUtil.parseDate(cookieBack1Expiry); //the actual Date
}
}
}
//also check for the Max-Age header, which overrides the Expires header.
//WARNING: this Directive is reported to be ignored by IE, so if both Expires and Max-Age are present
//and we report based on the Max-Age value, but the user is using IE, then the results reported
//by us here may be different from those actually experienced by the user! (we use Max-Age, IE uses Expires)
for ( Iterator <String> i = cookieBack1.getFlags().iterator(); i.hasNext(); ) {
String cookieBack1Flag = i.next();
//if ( this.debugEnabled ) log.debug("Cookie back 1 flag (checking for Max-Age): "+ cookieBack1Flag);
//match in a case insensitive manner. never know what case various web servers are going to send back.
if ( cookieBack1Flag.toLowerCase(Locale.ENGLISH).startsWith("max-age=")) {
String [] cookieBack1FlagValues = cookieBack1Flag.split("=");
if (cookieBack1FlagValues.length > 1) {
//now the Max-Age value is the number of seconds relative to the time the browser received the cookie
//(as stored in cookieBack1TimeReceived)
if ( this.debugEnabled ) log.debug("Cookie Max Age: "+ cookieBack1FlagValues[1]);
long cookie1DropDeadMS = cookieBack1TimeReceived + (Long.parseLong(cookieBack1FlagValues[1])*1000);
cookieBack1ExpiryDate = new Date (cookie1DropDeadMS); //the actual Date the cookie expires (by Max-Age)
cookieBack1Expiry = DateUtil.formatDate(cookieBack1ExpiryDate, DateUtil.PATTERN_RFC1123);
sessionExpiryDescription = cookieBack1Expiry; //needs to the Date String
}
}
}
String sessionExpiryRiskDescription = null;
//check the Expiry/Max-Age details garnered (if any)
//and figure out the risk, depending on whether it is a login page
//and how long the session will live before expiring
if ( cookieBack1ExpiryDate == null ) {
//session expires when the browser closes.. rate this as medium risk?
sessionExpiryRiskLevel = Alert.RISK_MEDIUM;
sessionExpiryRiskDescription="sessionidexpiry.browserclose";
sessionExpiryDescription = Constant.messages.getString(sessionExpiryRiskDescription);
} else {
long datediffSeconds = ( cookieBack1ExpiryDate.getTime() - cookieBack1TimeReceived) / 1000;
long anHourSeconds = 3600;
long aDaySeconds = anHourSeconds * 24;
long aWeekSeconds = aDaySeconds * 7;
if ( datediffSeconds < 0 ) {
if ( this.debugEnabled ) log.debug("The session cookie has expired already");
sessionExpiryRiskDescription = "sessionidexpiry.timeexpired";
sessionExpiryRiskLevel = Alert.RISK_INFO; // no risk.. the cookie has expired already
}
else if (datediffSeconds > aWeekSeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than a week!");
sessionExpiryRiskDescription="sessionidexpiry.timemorethanoneweek";
sessionExpiryRiskLevel = Alert.RISK_HIGH;
}
else if (datediffSeconds > aDaySeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than a day");
sessionExpiryRiskDescription="sessionidexpiry.timemorethanoneday";
sessionExpiryRiskLevel = Alert.RISK_MEDIUM;
}
else if (datediffSeconds > anHourSeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than an hour");
sessionExpiryRiskDescription="sessionidexpiry.timemorethanonehour";
sessionExpiryRiskLevel = Alert.RISK_LOW;
}
else {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for less than an hour!");
sessionExpiryRiskDescription="sessionidexpiry.timelessthanonehour";
sessionExpiryRiskLevel = Alert.RISK_INFO;
}
}
if (! loginUrl) {
//decrement the risk if it's not a login page
sessionExpiryRiskLevel--;
}
//alert it if the default session expiry risk level is more than informational
if (sessionExpiryRiskLevel > Alert.RISK_INFO) {
//pass the original param value here, not the new value
String cookieReceivedTime = cookieBack1Expiry = DateUtil.formatDate( new Date (cookieBack1TimeReceived), DateUtil.PATTERN_RFC1123);
String extraInfo = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue(), sessionExpiryDescription, cookieReceivedTime);
String attack = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidexpiry.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidexpiry.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidexpiry.soln");
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidexpiry.alert.extrainfo.loginpage"));
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session Id Expiry Time is excessive", or words to that effect.
bingo(sessionExpiryRiskLevel, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName(),
sessionExpiryDescription);
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
////////////////////////////////////////////////////////////////////////////////////////////
/// Message 2 - processing starts here
////////////////////////////////////////////////////////////////////////////////////////////
//so now that we know the URL responds with 200 (OK), and that it sets a cookie, lets re-issue the original request,
//but lets add in the new (valid) session cookie that was just issued.
//we will re-send it. the aim is then to see if it accepts the cookie (BAD, in some circumstances),
//or if it issues a new session cookie (GOOD, in most circumstances)
if ( this.debugEnabled ) log.debug("A Cookie was set by the URL for the correct param, when param ["+ currentHtmlParameter.getName() + "] was set to NULL: "+cookieBack1);
//use a copy of msg2Initial, since it has already had the correct cookie removed in the request..
//do NOT use msg2Initial itself, as this will cause both requests in the GUI to show the modified data..
//finally send the second message, and see how it comes back.
HttpMessage msg2Initial= msg1Initial.cloneRequest();
TreeSet<HtmlParameter> cookieParams2Set = msg2Initial.getRequestHeader().getCookieParams();
cookieParams2Set.add(cookieBack1);
msg2Initial.setCookieParams(cookieParams2Set);
//resend the copy of the initial message, but with the valid session cookie added in, to see if it is accepted
//do not automatically follow redirects, as we need to check these for cookies being set.
sendAndReceive(msg2Initial, false, false);
//create a copy of msg2Initial to play with to handle redirects (if any).
//we use a copy because if we change msg2Initial itself, it messes the URL and params displayed on the GUI.
HttpMessage temp2 = msg2Initial;
HttpMessage msg2Final=msg2Initial;
HtmlParameter cookieBack2Previous=cookieBack1;
HtmlParameter cookieBack2 = getResponseCookie (msg2Initial, currentHtmlParameter.getName());
int redirectsFollowed2 = 0;
while ( HttpStatusCode.isRedirection(temp2.getResponseHeader().getStatusCode())) {
//clone the previous message
boolean secure2 = temp2.getRequestHeader().getSecure();
temp2 = temp2.cloneAll();
redirectsFollowed2++;
if ( redirectsFollowed2 > 10 ) {
throw new Exception ("Too many redirects were specified in the second message");
}
//create a new URI from the absolute location returned, and interpret it as escaped
//note that the standard says that the Location returned should be absolute, but it ain't always so...
URI newLocation = new URI (temp2.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//and follow the forward url
//need to clear the params (which would come from the initial POST, otherwise)
temp2.getRequestHeader().setGetParams(new TreeSet<HtmlParameter>());
temp2.setRequestBody("");
temp2.setResponseBody(""); //make sure no values accidentally carry from one iteration to the next
try {
temp2.getRequestHeader().setURI(newLocation);
} catch (Exception e) {
//the Location field contents may not be standards compliant. Lets generate a uri to use as a workaround where a relative path was
//given instead of an absolute one
URI newLocationWorkaround = new URI(temp2.getRequestHeader().getURI(), temp2.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//try again, except this time, if it fails, don't try to handle it
if (this.debugEnabled) log.debug("The Location ["+ newLocation + "] specified in a redirect was not valid. Trying workaround url ["+ newLocationWorkaround + "]");
temp2.getRequestHeader().setURI(newLocationWorkaround);
}
temp2.getRequestHeader().setSecure(secure2);
temp2.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp2.getRequestHeader().setContentLength(0); //since we send a GET, the body will be 0 long
if ( cookieBack2 != null) {
//if the previous request sent back a cookie, we need to set that cookie when following redirects, as a browser would
//also make sure to delete the previous value set for the cookie value
if ( this.debugEnabled ) {
log.debug("Deleting old cookie ["+ cookieBack2Previous + "], and adding in cookie ["+ cookieBack2+ "] for a redirect");
}
TreeSet <HtmlParameter> forwardCookieParams = temp2.getRequestHeader().getCookieParams();
forwardCookieParams.remove(cookieBack2Previous);
forwardCookieParams.add(cookieBack2);
temp2.getRequestHeader().setCookieParams(forwardCookieParams);
}
sendAndReceive(temp2, false, false); //do NOT automatically redirect.. handle redirects here
//handle any cookies set from following redirects that override the cookie set in the redirect itself (if any)
//note that this will handle the case where a latter cookie unsets one set earlier.
HtmlParameter cookieBack2Temp = getResponseCookie (temp2, currentHtmlParameter.getName());
if ( cookieBack2Temp != null ) {
cookieBack2Previous=cookieBack2;
cookieBack2 = cookieBack2Temp;
}
//reset the "final" version of message2 to use the final response in the chain
msg2Final=temp2;
}
if ( this.debugEnabled ) log.debug("Done following redirects");
//final result was non-200, no point in continuing. Bale out.
if (msg2Final.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg2Final.getResponseHeader().getStatusCode()+"] when sending ["+msg2Initial.getRequestHeader().getURI()+ "] with a borrowed cookie (or by following a redirect) for param ["+currentHtmlParameter.getName()+"]");
continue; //to next parameter
}
//and what we've been waiting for.. do we get a *different* cookie being set in the response of message 2??
//or do we get a new cookie back at all?
//No cookie back => the borrowed cookie was accepted. Not ideal
//Cookie back, but same as the one we sent in => the borrowed cookie was accepted. Not ideal
if ( (cookieBack2== null) || cookieBack2.getValue().equals(cookieBack1.getValue())) {
//no cookie back, when a borrowed cookie is in use.. suspicious!
//use the cookie extrainfo message, which is specific to the case of cookies
//pretty much everything else is generic to all types of Session Fixation vulnerabilities
String extraInfo = Constant.messages.getString("ascanbeta.sessionfixation.alert.cookie.extrainfo", currentHtmlParameter.getName(), cookieBack1.getValue(), (cookieBack2== null?"NULL": cookieBack2.getValue()));
String attack = Constant.messages.getString("ascanbeta.sessionfixation.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionfixation.alert.cookie.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
bingo(risk, Alert.WARNING, msg2Initial.getRequestHeader().getURI().getURI(), currentHtmlParameter.getName(), attack, extraInfo, msg2Initial);
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionfixation.alert.logmessage", msg2Initial.getRequestHeader().getMethod(), msg2Initial.getRequestHeader().getURI().getURI(), currentHtmlParameter.getType(), currentHtmlParameter.getName());
log.info(logMessage);
//}
}
continue; //jump to the next iteration of the loop (ie, the next parameter)
} //end of the cookie code.
//start of the url parameter code
//note that this actually caters for
//- actual URL parameters
//- pseudo URL parameters, where the sessionid was in the path portion of the URL, in conjunction with URL re-writing
if ( currentHtmlParameter.getType().equals (HtmlParameter.Type.url)) {
boolean isPseudoUrlParameter=false; //is this "url parameter" actually a url parameter, or was it path of the path (+url re-writing)?
String possibleSessionIdIssuedForUrlParam=null;
//remove the named url parameter from the request..
TreeSet <HtmlParameter> urlRequestParams = msg1Initial.getUrlParams(); //get parameters?
if ( ! urlRequestParams.remove(currentHtmlParameter)) {
isPseudoUrlParameter=true;
//was not removed because it was a pseudo Url parameter, not a real url parameter.. (so it would not be in the url params)
//in this case, we will need to "rewrite" (ie hack) the URL path to remove the pseudo url parameter portion
//ie, we need to remove the ";jsessionid=<sessionid>" bit from the path (assuming the current field is named 'jsessionid')
//and replace it with ";jsessionid=" (ie, we nullify the possible "session" parameter in the hope that a new session will be issued)
//then we continue as usual to see if the URL is vulnerable to a Session Fixation issue
//Side note: quote the string to search for, and the replacement, so that regex special characters are treated as literals
String hackedUrl = requestUrl.replaceAll(
Pattern.quote(";"+ currentHtmlParameter.getName()+"=" + currentHtmlParameter.getValue()),
Matcher.quoteReplacement(";"+currentHtmlParameter.getName()+"="));
if (this.debugEnabled) log.debug("Removing the pseudo URL parameter from ["+requestUrl+"]: ["+hackedUrl+"]");
//Note: the URL is not escaped. Handle it.
msg1Initial.getRequestHeader().setURI(new URI(hackedUrl, false));
}
msg1Initial.setGetParams(urlRequestParams); //url parameters
//send the message, minus the value for the current parameter, and see how it comes back.
//Note: automatically follow redirects.. no need to look at any intermediate responses.
//this was only necessary for cookie-based session implementations
sendAndReceive(msg1Initial);
//if non-200 on the response for message 1, no point in continuing. Bale out.
if (msg1Initial.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg1Initial.getResponseHeader().getStatusCode()+"] when sending ["+msg1Initial.getRequestHeader().getURI()+ "] with param ["+ currentHtmlParameter.getName() +"] = NULL (possibly somewhere in the redirects)");
continue;
}
//now parse the HTML response for urls that contain the same parameter name, and look at the values for that parameter
//if no values are found for the parameter, then
//1) we are messing with the wrong field, or
//2) the app doesn't do sessions
//either way, there is not much point in continuing to look at this field..
//parse out links in HTML (assume for a moment that all the URLs are in links)
//this gives us a map of parameter value for the current parameter, to the number of times it was encountered in links in the HTML
SortedMap <String, Integer> parametersInHTMLURls = getParameterValueCountInHtml (msg1Initial.getResponseBody().toString(), currentHtmlParameter.getName(), isPseudoUrlParameter);
if (this.debugEnabled) log.debug("The count of the various values of the ["+ currentHtmlParameter.getName() + "] parameters in urls in the result of retrieving the url with a null value for parameter ["+ currentHtmlParameter.getName() + "]: "+ parametersInHTMLURls);
if (parametersInHTMLURls.isEmpty()) {
//setting the param to NULL did not cause any new values to be generated for it in the output..
//so either..
//it is not a session field, or
//it is a session field, but a session is only issued on authentication, and this is not an authentication url
//the app doesn't do sessions (etc)
//either way, the parameter/url combo is not vulnerable, so continue with the next parameter
if ( this.debugEnabled) log.debug("The URL parameter ["+ currentHtmlParameter.getName() + "] was NOT set in any links in the response, when "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "] was set to NULL in the request, so it is likely not a session id field");
continue; //to the next parameter
} else if (parametersInHTMLURls.size() == 1) {
//the parameter was set to just one value in the output
//so it's quite possible it is the session id field that we have been looking for
//caveat 1: check it is longer than 3 chars long, to remove false positives..
//we assume here that a real session id will always be greater than 3 characters long
//caveat 2: the value we got back for the param must be different from the value we
//over-wrote with NULL (empty) in the first place, otherwise it is very unlikely to
//be a session id field
possibleSessionIdIssuedForUrlParam=parametersInHTMLURls.firstKey();
//did we get back the same value we just nulled out in the original request?
//if so, use this to eliminate false positives, and to optimise.
if ( possibleSessionIdIssuedForUrlParam.equals (currentHtmlParameter.getValue())) {
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes 1 distinct values to be set for it in URLs in the output, but the possible session id value ["+ possibleSessionIdIssuedForUrlParam + "] is the same as the value we over-wrote with NULL. 'Sorry, kid. You got the gift, but it looks like you're waiting for something'");
continue; //to the next parameter
}
if (possibleSessionIdIssuedForUrlParam.length() > 3) {
//raise an alert here on an exposed session id, even if it is not subject to a session fixation vulnerability
//log.info("The URL parameter ["+ currentHtmlParameter.getName() + "] was set ["+ parametersInHTMLURls.get(possibleSessionIdIssuedForUrlParam)+ "] times to ["+ possibleSessionIdIssuedForUrlParam + "] in links in the response, when "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "] was set to NULL in the request. This likely indicates it is a session id field.");
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
String attack = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.attack", (isPseudoUrlParameter?"pseudo/URL rewritten ":"") + currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidexposedinurl.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidexposedinurl.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidexposedinurl.soln");
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.extrainfo.loginpage"));
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id exposed in url", or words to that effect.
bingo(Alert.RISK_MEDIUM, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
(isPseudoUrlParameter?"pseudo ":"") +currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
else {
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes 1 distinct values to be set for it in URLs in the output, but the possible session id value ["+ possibleSessionIdIssuedForUrlParam + "] is too short to be a real session id.");
continue; //to the next parameter
}
} else {
//strange scenario: setting the param to null causes multiple different values to be set for it in the output
//it could still be a session parameter, but we assume it is *not* a session id field
//log it, but assume it is not a session id
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes ["+ parametersInHTMLURls.size() + "] distinct values to be set for it in URLs in the output. Assuming it is NOT a session id as a consequence. This could be a false negative");
continue; //to the next parameter
}
////////////////////////////////////////////////////////////////////////////////////////////
/// Message 2 - processing starts here
////////////////////////////////////////////////////////////////////////////////////////////
//we now have a plausible session id field to play with, so set it to a borrowed value.
//ie: lets re-send the request, but add in the new (valid) session value that was just issued.
//the aim is then to see if it accepts the session without re-issuing the session id (BAD, in some circumstances),
//or if it issues a new session value (GOOD, in most circumstances)
//and set the (modified) session for the second message
//use a copy of msg2Initial, since it has already had the correct session removed in the request..
//do NOT use msg2Initial itself, as this will cause both requests in the GUI to show the modified data..
//finally send the second message, and see how it comes back.
HttpMessage msg2Initial= msg1Initial.cloneRequest();
//set the parameter to the new session id value (in different manners, depending on whether it is a real url param, or a pseudo url param)
if ( isPseudoUrlParameter ) {
//we need to "rewrite" (hack) the URL path to remove the pseudo url parameter portion
//id, we need to remove the ";jsessionid=<sessionid>" bit from the path
//and replace it with ";jsessionid=" (ie, we nullify the possible "session" parameter in the hope that a new session will be issued)
//then we continue as usual to see if the URL is vulnerable to a Session Fixation issue
//Side note: quote the string to search for, and the replacement, so that regex special characters are treated as literals
String hackedUrl = requestUrl.replaceAll(
Pattern.quote(";"+ currentHtmlParameter.getName()+"=" + currentHtmlParameter.getValue()),
Matcher.quoteReplacement(";" +currentHtmlParameter.getName()+"="+ possibleSessionIdIssuedForUrlParam));
if (this.debugEnabled) log.debug("Changing the pseudo URL parameter from ["+requestUrl+"]: ["+hackedUrl+"]");
//Note: the URL is not escaped
msg2Initial.getRequestHeader().setURI(new URI(hackedUrl, false));
msg2Initial.setGetParams(msg1Initial.getUrlParams()); //restore the GET params
} else {
//do it via the normal url parameters
TreeSet <HtmlParameter> urlRequestParams2 = msg2Initial.getUrlParams();
urlRequestParams2.add(new HtmlParameter(Type.url, currentHtmlParameter.getName(), possibleSessionIdIssuedForUrlParam));
msg2Initial.setGetParams(urlRequestParams2); //restore the GET params
}
//resend a copy of the initial message, but with the new valid session parameter added in, to see if it is accepted
//automatically follow redirects, which are irrelevant for the purposes of testing URL parameters
sendAndReceive(msg2Initial);
//final result was non-200, no point in continuing. Bale out.
if (msg2Initial.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg2Initial.getResponseHeader().getStatusCode()+"] when sending ["+msg2Initial.getRequestHeader().getURI()+ "] with a borrowed session (or by following a redirect) for param ["+currentHtmlParameter.getName()+"]");
continue; //next field!
}
//do the analysis on the parameters in link urls in the HTML output again to see if the session id was regenerated
SortedMap <String, Integer> parametersInHTMLURls2 = getParameterValueCountInHtml (msg2Initial.getResponseBody().toString(), currentHtmlParameter.getName(), isPseudoUrlParameter);
if ( this.debugEnabled ) log.debug("The count of the various values of the ["+ currentHtmlParameter.getName() + "] parameters in urls in the result of retrieving the url with a borrowed session value for parameter ["+ currentHtmlParameter.getName() + "]: "+ parametersInHTMLURls2);
if ( parametersInHTMLURls2.size() != 1) {
//either no values, or multiple values, but not 1 value. For a session that was regenerated, we would have expected to see
//just 1 new value
if (this.debugEnabled) log.debug("The HTML has spoken. ["+currentHtmlParameter.getName()+"] doesn't look like a session id field, because there are "+parametersInHTMLURls2.size()+" distinct values for this parameter in urls in the HTML output");
continue;
}
//there is but one value for this param in links in the HTML output. But is it vulnerable to Session Fixation? Ie, is it the same parameter?
String possibleSessionIdIssuedForUrlParam2=parametersInHTMLURls2.firstKey();
if ( possibleSessionIdIssuedForUrlParam2.equals (possibleSessionIdIssuedForUrlParam)) {
//same sessionid used in the output.. so it is likely that we have a SessionFixation issue..
//use the url param extrainfo message, which is specific to the case of url parameters and url re-writing Session Fixation issue
//pretty much everything else is generic to all types of Session Fixation vulnerabilities
String extraInfo = Constant.messages.getString("ascanbeta.sessionfixation.alert.url.extrainfo", currentHtmlParameter.getName(), possibleSessionIdIssuedForUrlParam, possibleSessionIdIssuedForUrlParam2);
String attack = Constant.messages.getString("ascanbeta.sessionfixation.alert.attack", (isPseudoUrlParameter?"pseudo/URL rewritten ":"") + currentHtmlParameter.getType(), currentHtmlParameter.getName());
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionfixation.alert.url.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
bingo(risk, Alert.WARNING, getBaseMsg().getRequestHeader().getURI().getURI(), currentHtmlParameter.getName(), attack, extraInfo, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionfixation.alert.logmessage", getBaseMsg().getRequestHeader().getMethod(), getBaseMsg().getRequestHeader().getURI().getURI(), (isPseudoUrlParameter?"pseudo ":"") +currentHtmlParameter.getType(), currentHtmlParameter.getName());
log.info(logMessage);
//}
continue; //jump to the next iteration of the loop (ie, the next parameter)
}
else {
//different sessionid used in the output.. so it is unlikely that we have a SessionFixation issue..
//more likely that the Session is being re-issued for every single request, or we have issues a login request, which
//normally causes a session to be reissued
if (this.debugEnabled) log.debug("The "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"") + " parameter ["+currentHtmlParameter.getName() + "] in url ["+ getBaseMsg().getRequestHeader().getMethod()+ "] ["+ getBaseMsg().getRequestHeader().getURI() + "] changes with requests, and so it likely not vulnerable to Session Fixation");
}
continue; //onto the next parameter
} //end of the url parameter code.
} //end of the for loop around the parameter list
} catch (Exception e) {
//Do not try to internationalise this.. we need an error message in any event..
//if it's in English, it's still better than not having it at all.
log.error("An error occurred checking a url for Session Fixation issues", e);
}
}
| public void scan() {
//TODO: scan the POST (form) params for session id fields.
try {
boolean loginUrl = false;
//are we dealing with the login url? Will be important later
try {
ExtensionAuth extAuth = (ExtensionAuth) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAuth.NAME);
URI loginUri = extAuth.getApi().getLoginRequest(1).getRequestHeader().getURI();
URI requestUri = getBaseMsg().getRequestHeader().getURI();
if ( requestUri.getScheme().equals(loginUri.getScheme()) &&
requestUri.getHost().equals(loginUri.getHost()) &&
requestUri.getPort() == loginUri.getPort() &&
requestUri.getPath().equals(loginUri.getPath()) ) {
//we got this far.. only the method (GET/POST), user details, query params, fragment, and POST params
//are possibly different from the login page.
loginUrl = true;
}
}
catch (Exception e) {
log.debug("For the Session Fixation scanner to actually do anything, a Login Page *must* be set!");
}
//For now (from Zap 2.0), the Session Fixation scanner will only run for logon pages
if (loginUrl == false) return;
//find all params set in the request (GET/POST/Cookie)
//Note: this will be the full set, before we delete anything.
TreeSet<HtmlParameter> htmlParams = new TreeSet<> ();
htmlParams.addAll(getBaseMsg().getRequestHeader().getCookieParams()); //request cookies only. no response cookies
htmlParams.addAll(getBaseMsg().getFormParams()); //add in the POST params
htmlParams.addAll(getBaseMsg().getUrlParams()); //add in the GET params
//Now add in the pseudo parameters set in the URL itself, such as in the following:
//http://www.example.com/someurl;JSESSIONID=abcdefg?x=123&y=456
//as opposed to the url parameters in the following example, which are already picked up by getUrlParams()
//http://www.example.com/someurl?JSESSIONID=abcdefg&x=123&y=456
//get the URL
URI requestUri = getBaseMsg().getRequestHeader().getURI();
//convert from org.apache.commons.httpclient.URI to a String
String requestUrl= "Unknown URL";
try {
requestUrl = new URL (requestUri.getScheme(), requestUri.getHost(), requestUri.getPort(), requestUri.getPath()).toString();
}
catch (Exception e) {
// no point in continuing. The URL is invalid. This is a peculiarity in the Zap core,
// and can happen when
// - the user browsed to http://www.example.com/bodgeit and
// - the user did not browse to http://www.example.com or to http://www.example.com/
// so the Zap GUI displays "http://www.example.com" as a node under "Sites",
// and under that, it displays the actual urls to which the user browsed
// (http://www.example.com/bodgeit, for instance)
// When the user selects the node "http://www.example.com", and tries to scan it with
// the session fixation scanner, the URI that is passed is "http://www.example.com",
// which is *not* a valid url.
// If the user actually browses to "http://www.example.com" (even without the trailing slash)
// the web browser appends the trailing slash, and so Zap records the URI as
// "http://www.example.com/", which IS a valid url, and which can (and should) be scanned.
//
// In short.. if this happens, we do not want to scan the URL anyway
// (because the user never browsed to it), so just do nothing instead.
log.error("Cannot convert URI ["+requestUri+"] to a URL: "+e.getMessage());
return;
}
//suck out any pseudo url parameters from the url
Set<HtmlParameter> pseudoUrlParams = getPseudoUrlParameters (requestUrl);
htmlParams.addAll(pseudoUrlParams);
if ( this.debugEnabled ) log.debug("Pseudo url params of URL ["+ requestUrl+ "] : ["+pseudoUrlParams+"]");
////for each parameter in turn,
//int counter = 0;
for (Iterator<HtmlParameter> iter = htmlParams.iterator(); iter.hasNext(); ) {
HttpMessage msg1Final;
HttpMessage msg1Initial = getNewMsg();
////debug logic only.. to do first field only
//counter ++;
//if ( counter > 1 )
// return;
HtmlParameter currentHtmlParameter = iter.next();
//Useful for debugging, but I can't find a way to view this data in the GUI, so leave it out for now.
//msg1Initial.setNote("Message 1 for parameter "+ currentHtmlParameter);
if ( this.debugEnabled ) log.debug("Scanning URL ["+ msg1Initial.getRequestHeader().getMethod()+ "] ["+ msg1Initial.getRequestHeader().getURI() + "], ["+ currentHtmlParameter.getType()+"] field ["+ currentHtmlParameter.getName() + "] with value ["+currentHtmlParameter.getValue()+"] for Session Fixation");
if ( currentHtmlParameter.getType().equals (HtmlParameter.Type.cookie)) {
//careful to pick up the cookies from the Request, and not to include cookies set in any earlier response
TreeSet <HtmlParameter> cookieRequestParams = msg1Initial.getRequestHeader().getCookieParams();
//delete the original cookie from the parameters
cookieRequestParams.remove(currentHtmlParameter);
msg1Initial.setCookieParams(cookieRequestParams);
//send the message, minus the cookie parameter, and see how it comes back.
//Note: do NOT automatically follow redirects.. handle those here instead.
sendAndReceive(msg1Initial, false, false);
/////////////////////////////
//create a copy of msg1Initial to play with to handle redirects (if any).
//we use a copy because if we change msg1Initial itself, it messes the URL and params displayed on the GUI.
msg1Final=msg1Initial;
HtmlParameter cookieBack1 = getResponseCookie (msg1Initial, currentHtmlParameter.getName());
long cookieBack1TimeReceived = System.currentTimeMillis(); //in ms. when was the cookie received? Important if it has a Max-Age directive
Date cookieBack1ExpiryDate=null;
HttpMessage temp = msg1Initial;
int redirectsFollowed1 = 0;
while ( HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode())) {
//Note that we need to clone the Request and the Response..
//we seem to need to track the secure flag now to make sure its set later
boolean secure1 = temp.getRequestHeader().getSecure();
temp = temp.cloneAll(); //clone the previous message
redirectsFollowed1++;
if ( redirectsFollowed1 > 10 ) {
throw new Exception ("Too many redirects were specified in the first message");
}
//create a new URI from the absolute location returned, and interpret it as escaped
//note that the standard says that the Location returned should be absolute, but it ain't always so...
URI newLocation = new URI (temp.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//and follow the forward url
//need to clear the params (which would come from the initial POST, otherwise)
temp.getRequestHeader().setGetParams(new TreeSet<HtmlParameter>());
temp.setRequestBody("");
temp.setResponseBody(""); //make sure no values accidentally carry from one iteration to the next
try {
temp.getRequestHeader().setURI(newLocation);
} catch (Exception e) {
//the Location field contents may not be standards compliant. Lets generate a uri to use as a workaround where a relative path was
//given instead of an absolute one
URI newLocationWorkaround = new URI(temp.getRequestHeader().getURI(), temp.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//try again, except this time, if it fails, don't try to handle it
if (this.debugEnabled) log.debug("The Location ["+ newLocation + "] specified in a redirect was not valid. Trying workaround url ["+ newLocationWorkaround + "]");
temp.getRequestHeader().setURI(newLocationWorkaround);
}
temp.getRequestHeader().setSecure(secure1);
temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp.getRequestHeader().setContentLength(0); //since we send a GET, the body will be 0 long
if ( cookieBack1 != null) {
//if the previous request sent back a cookie, we need to set that cookie when following redirects, as a browser would
if ( this.debugEnabled ) log.debug("Adding in cookie ["+ cookieBack1+ "] for a redirect");
TreeSet <HtmlParameter> forwardCookieParams = temp.getRequestHeader().getCookieParams();
forwardCookieParams.add(cookieBack1);
temp.getRequestHeader().setCookieParams(forwardCookieParams);
}
if ( this.debugEnabled ) log.debug("DEBUG: Cookie Message 1 causes us to follow redirect to ["+ newLocation +"]");
sendAndReceive(temp, false, false); //do NOT redirect.. handle it here
//handle any cookies set from following redirects that override the cookie set in the redirect itself (if any)
//note that this will handle the case where a latter cookie unsets one set earlier.
HtmlParameter cookieBack1Temp = getResponseCookie (temp, currentHtmlParameter.getName());
if ( cookieBack1Temp != null ) {
cookieBack1 = cookieBack1Temp;
cookieBack1TimeReceived=System.currentTimeMillis(); //in ms. record when we got the cookie.. in case it has a Max-Age directive
}
//reset the "final" version of message1 to use the final response in the chain
msg1Final=temp;
}
///////////////////////////
//if non-200 on the final response for message 1, no point in continuing. Bale out.
if (msg1Final.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg1Final.getResponseHeader().getStatusCode()+"] when sending ["+msg1Initial.getRequestHeader().getURI()+ "] with param ["+ currentHtmlParameter.getName() +"] = NULL (possibly somewhere in the redirects)");
continue;
}
//now check that the response set a cookie. if it didn't, then either..
//1) we are messing with the wrong field
//2) the app doesn't do sessions
//either way, there is not much point in continuing to look at this field..
if ( cookieBack1 == null || cookieBack1.getValue() == null ) {
//no cookie was set, or the cookie param was set to a null value
if ( this.debugEnabled ) log.debug("The Cookie parameter was NOT set in the response, when cookie param ["+ currentHtmlParameter.getName() + "] was set to NULL: "+cookieBack1);
continue;
}
//////////////////////////////////////////////////////////////////////
//at this point, before continuing to check for Session Fixation, do some other checks on the session cookie we got back
//that might cause us to raise additional alerts (in addition to doing the main check for Session Fixation)
//////////////////////////////////////////////////////////////////////
//Check 1: was the session cookie sent and received securely by the server?
//If not, alert this fact
if ( (! msg1Final.getRequestHeader().getSecure()) ||
(! cookieBack1.getFlags().contains("secure")) ) {
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
if (! cookieBack1.getFlags().contains("secure")) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo.secureflagnotset"));
}
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
String attack = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidsentinsecurely.soln");
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id sent insecurely", or words to that effect.
bingo(risk, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidsentinsecurely.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
//////////////////////////////////////////////////////////////////////
//Check 2: is the session cookie that was set accessible to Javascript?
//If so, alert this fact too
if ( ! cookieBack1.getFlags().contains("httponly")) {
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
String attack = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.soln");
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id accessible in Javascript", or words to that effect.
bingo(risk, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidaccessiblebyjavascript.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
//////////////////////////////////////////////////////////////////////
//Check 3: is the session cookie set to expire soon? when the browser session closes? never?
//the longer the session cookie is valid, the greater the risk. alert it accordingly
String cookieBack1Expiry=null;
int sessionExpiryRiskLevel;
String sessionExpiryDescription = null;
//check for the Expires header
for ( Iterator <String> i = cookieBack1.getFlags().iterator(); i.hasNext(); ) {
String cookieBack1Flag = i.next();
//if ( this.debugEnabled ) log.debug("Cookie back 1 flag (checking for Expires): "+ cookieBack1Flag);
//match in a case insensitive manner. never know what case various web servers are going to send back.
//if (cookieBack1Flag.matches("(?i)expires=.*")) {
if ( cookieBack1Flag.toLowerCase(Locale.ENGLISH).startsWith("expires=")) {
String [] cookieBack1FlagValues = cookieBack1Flag.split("=");
if (cookieBack1FlagValues.length > 1) {
if ( this.debugEnabled ) log.debug("Cookie Expiry: "+ cookieBack1FlagValues[1]);
cookieBack1Expiry=cookieBack1FlagValues[1]; //the Date String
sessionExpiryDescription = cookieBack1FlagValues[1]; //the Date String
cookieBack1ExpiryDate = DateUtil.parseDate(cookieBack1Expiry); //the actual Date
}
}
}
//also check for the Max-Age header, which overrides the Expires header.
//WARNING: this Directive is reported to be ignored by IE, so if both Expires and Max-Age are present
//and we report based on the Max-Age value, but the user is using IE, then the results reported
//by us here may be different from those actually experienced by the user! (we use Max-Age, IE uses Expires)
for ( Iterator <String> i = cookieBack1.getFlags().iterator(); i.hasNext(); ) {
String cookieBack1Flag = i.next();
//if ( this.debugEnabled ) log.debug("Cookie back 1 flag (checking for Max-Age): "+ cookieBack1Flag);
//match in a case insensitive manner. never know what case various web servers are going to send back.
if ( cookieBack1Flag.toLowerCase(Locale.ENGLISH).startsWith("max-age=")) {
String [] cookieBack1FlagValues = cookieBack1Flag.split("=");
if (cookieBack1FlagValues.length > 1) {
//now the Max-Age value is the number of seconds relative to the time the browser received the cookie
//(as stored in cookieBack1TimeReceived)
if ( this.debugEnabled ) log.debug("Cookie Max Age: "+ cookieBack1FlagValues[1]);
long cookie1DropDeadMS = cookieBack1TimeReceived + (Long.parseLong(cookieBack1FlagValues[1])*1000);
cookieBack1ExpiryDate = new Date (cookie1DropDeadMS); //the actual Date the cookie expires (by Max-Age)
cookieBack1Expiry = DateUtil.formatDate(cookieBack1ExpiryDate, DateUtil.PATTERN_RFC1123);
sessionExpiryDescription = cookieBack1Expiry; //needs to the Date String
}
}
}
String sessionExpiryRiskDescription = null;
//check the Expiry/Max-Age details garnered (if any)
//and figure out the risk, depending on whether it is a login page
//and how long the session will live before expiring
if ( cookieBack1ExpiryDate == null ) {
//session expires when the browser closes.. rate this as medium risk?
sessionExpiryRiskLevel = Alert.RISK_MEDIUM;
sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.browserclose";
sessionExpiryDescription = Constant.messages.getString(sessionExpiryRiskDescription);
} else {
long datediffSeconds = ( cookieBack1ExpiryDate.getTime() - cookieBack1TimeReceived) / 1000;
long anHourSeconds = 3600;
long aDaySeconds = anHourSeconds * 24;
long aWeekSeconds = aDaySeconds * 7;
if ( datediffSeconds < 0 ) {
if ( this.debugEnabled ) log.debug("The session cookie has expired already");
sessionExpiryRiskDescription = "ascanbeta.sessionidexpiry.timeexpired";
sessionExpiryRiskLevel = Alert.RISK_INFO; // no risk.. the cookie has expired already
}
else if (datediffSeconds > aWeekSeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than a week!");
sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timemorethanoneweek";
sessionExpiryRiskLevel = Alert.RISK_HIGH;
}
else if (datediffSeconds > aDaySeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than a day");
sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timemorethanoneday";
sessionExpiryRiskLevel = Alert.RISK_MEDIUM;
}
else if (datediffSeconds > anHourSeconds ) {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for more than an hour");
sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timemorethanonehour";
sessionExpiryRiskLevel = Alert.RISK_LOW;
}
else {
if ( this.debugEnabled ) log.debug("The session cookie is set to last for less than an hour!");
sessionExpiryRiskDescription="ascanbeta.sessionidexpiry.timelessthanonehour";
sessionExpiryRiskLevel = Alert.RISK_INFO;
}
}
if (! loginUrl) {
//decrement the risk if it's not a login page
sessionExpiryRiskLevel--;
}
//alert it if the default session expiry risk level is more than informational
if (sessionExpiryRiskLevel > Alert.RISK_INFO) {
//pass the original param value here, not the new value
String cookieReceivedTime = cookieBack1Expiry = DateUtil.formatDate( new Date (cookieBack1TimeReceived), DateUtil.PATTERN_RFC1123);
String extraInfo = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue(), sessionExpiryDescription, cookieReceivedTime);
String attack = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidexpiry.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidexpiry.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidexpiry.soln");
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidexpiry.alert.extrainfo.loginpage"));
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session Id Expiry Time is excessive", or words to that effect.
bingo(sessionExpiryRiskLevel, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidexpiry.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getType(),
currentHtmlParameter.getName(),
sessionExpiryDescription);
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
////////////////////////////////////////////////////////////////////////////////////////////
/// Message 2 - processing starts here
////////////////////////////////////////////////////////////////////////////////////////////
//so now that we know the URL responds with 200 (OK), and that it sets a cookie, lets re-issue the original request,
//but lets add in the new (valid) session cookie that was just issued.
//we will re-send it. the aim is then to see if it accepts the cookie (BAD, in some circumstances),
//or if it issues a new session cookie (GOOD, in most circumstances)
if ( this.debugEnabled ) log.debug("A Cookie was set by the URL for the correct param, when param ["+ currentHtmlParameter.getName() + "] was set to NULL: "+cookieBack1);
//use a copy of msg2Initial, since it has already had the correct cookie removed in the request..
//do NOT use msg2Initial itself, as this will cause both requests in the GUI to show the modified data..
//finally send the second message, and see how it comes back.
HttpMessage msg2Initial= msg1Initial.cloneRequest();
TreeSet<HtmlParameter> cookieParams2Set = msg2Initial.getRequestHeader().getCookieParams();
cookieParams2Set.add(cookieBack1);
msg2Initial.setCookieParams(cookieParams2Set);
//resend the copy of the initial message, but with the valid session cookie added in, to see if it is accepted
//do not automatically follow redirects, as we need to check these for cookies being set.
sendAndReceive(msg2Initial, false, false);
//create a copy of msg2Initial to play with to handle redirects (if any).
//we use a copy because if we change msg2Initial itself, it messes the URL and params displayed on the GUI.
HttpMessage temp2 = msg2Initial;
HttpMessage msg2Final=msg2Initial;
HtmlParameter cookieBack2Previous=cookieBack1;
HtmlParameter cookieBack2 = getResponseCookie (msg2Initial, currentHtmlParameter.getName());
int redirectsFollowed2 = 0;
while ( HttpStatusCode.isRedirection(temp2.getResponseHeader().getStatusCode())) {
//clone the previous message
boolean secure2 = temp2.getRequestHeader().getSecure();
temp2 = temp2.cloneAll();
redirectsFollowed2++;
if ( redirectsFollowed2 > 10 ) {
throw new Exception ("Too many redirects were specified in the second message");
}
//create a new URI from the absolute location returned, and interpret it as escaped
//note that the standard says that the Location returned should be absolute, but it ain't always so...
URI newLocation = new URI (temp2.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//and follow the forward url
//need to clear the params (which would come from the initial POST, otherwise)
temp2.getRequestHeader().setGetParams(new TreeSet<HtmlParameter>());
temp2.setRequestBody("");
temp2.setResponseBody(""); //make sure no values accidentally carry from one iteration to the next
try {
temp2.getRequestHeader().setURI(newLocation);
} catch (Exception e) {
//the Location field contents may not be standards compliant. Lets generate a uri to use as a workaround where a relative path was
//given instead of an absolute one
URI newLocationWorkaround = new URI(temp2.getRequestHeader().getURI(), temp2.getResponseHeader().getHeader(HttpHeader.LOCATION), true);
//try again, except this time, if it fails, don't try to handle it
if (this.debugEnabled) log.debug("The Location ["+ newLocation + "] specified in a redirect was not valid. Trying workaround url ["+ newLocationWorkaround + "]");
temp2.getRequestHeader().setURI(newLocationWorkaround);
}
temp2.getRequestHeader().setSecure(secure2);
temp2.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp2.getRequestHeader().setContentLength(0); //since we send a GET, the body will be 0 long
if ( cookieBack2 != null) {
//if the previous request sent back a cookie, we need to set that cookie when following redirects, as a browser would
//also make sure to delete the previous value set for the cookie value
if ( this.debugEnabled ) {
log.debug("Deleting old cookie ["+ cookieBack2Previous + "], and adding in cookie ["+ cookieBack2+ "] for a redirect");
}
TreeSet <HtmlParameter> forwardCookieParams = temp2.getRequestHeader().getCookieParams();
forwardCookieParams.remove(cookieBack2Previous);
forwardCookieParams.add(cookieBack2);
temp2.getRequestHeader().setCookieParams(forwardCookieParams);
}
sendAndReceive(temp2, false, false); //do NOT automatically redirect.. handle redirects here
//handle any cookies set from following redirects that override the cookie set in the redirect itself (if any)
//note that this will handle the case where a latter cookie unsets one set earlier.
HtmlParameter cookieBack2Temp = getResponseCookie (temp2, currentHtmlParameter.getName());
if ( cookieBack2Temp != null ) {
cookieBack2Previous=cookieBack2;
cookieBack2 = cookieBack2Temp;
}
//reset the "final" version of message2 to use the final response in the chain
msg2Final=temp2;
}
if ( this.debugEnabled ) log.debug("Done following redirects");
//final result was non-200, no point in continuing. Bale out.
if (msg2Final.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg2Final.getResponseHeader().getStatusCode()+"] when sending ["+msg2Initial.getRequestHeader().getURI()+ "] with a borrowed cookie (or by following a redirect) for param ["+currentHtmlParameter.getName()+"]");
continue; //to next parameter
}
//and what we've been waiting for.. do we get a *different* cookie being set in the response of message 2??
//or do we get a new cookie back at all?
//No cookie back => the borrowed cookie was accepted. Not ideal
//Cookie back, but same as the one we sent in => the borrowed cookie was accepted. Not ideal
if ( (cookieBack2== null) || cookieBack2.getValue().equals(cookieBack1.getValue())) {
//no cookie back, when a borrowed cookie is in use.. suspicious!
//use the cookie extrainfo message, which is specific to the case of cookies
//pretty much everything else is generic to all types of Session Fixation vulnerabilities
String extraInfo = Constant.messages.getString("ascanbeta.sessionfixation.alert.cookie.extrainfo", currentHtmlParameter.getName(), cookieBack1.getValue(), (cookieBack2== null?"NULL": cookieBack2.getValue()));
String attack = Constant.messages.getString("ascanbeta.sessionfixation.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName());
//and figure out the risk, depending on whether it is a login page
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionfixation.alert.cookie.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
bingo(risk, Alert.WARNING, msg2Initial.getRequestHeader().getURI().getURI(), currentHtmlParameter.getName(), attack, extraInfo, msg2Initial);
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionfixation.alert.logmessage", msg2Initial.getRequestHeader().getMethod(), msg2Initial.getRequestHeader().getURI().getURI(), currentHtmlParameter.getType(), currentHtmlParameter.getName());
log.info(logMessage);
//}
}
continue; //jump to the next iteration of the loop (ie, the next parameter)
} //end of the cookie code.
//start of the url parameter code
//note that this actually caters for
//- actual URL parameters
//- pseudo URL parameters, where the sessionid was in the path portion of the URL, in conjunction with URL re-writing
if ( currentHtmlParameter.getType().equals (HtmlParameter.Type.url)) {
boolean isPseudoUrlParameter=false; //is this "url parameter" actually a url parameter, or was it path of the path (+url re-writing)?
String possibleSessionIdIssuedForUrlParam=null;
//remove the named url parameter from the request..
TreeSet <HtmlParameter> urlRequestParams = msg1Initial.getUrlParams(); //get parameters?
if ( ! urlRequestParams.remove(currentHtmlParameter)) {
isPseudoUrlParameter=true;
//was not removed because it was a pseudo Url parameter, not a real url parameter.. (so it would not be in the url params)
//in this case, we will need to "rewrite" (ie hack) the URL path to remove the pseudo url parameter portion
//ie, we need to remove the ";jsessionid=<sessionid>" bit from the path (assuming the current field is named 'jsessionid')
//and replace it with ";jsessionid=" (ie, we nullify the possible "session" parameter in the hope that a new session will be issued)
//then we continue as usual to see if the URL is vulnerable to a Session Fixation issue
//Side note: quote the string to search for, and the replacement, so that regex special characters are treated as literals
String hackedUrl = requestUrl.replaceAll(
Pattern.quote(";"+ currentHtmlParameter.getName()+"=" + currentHtmlParameter.getValue()),
Matcher.quoteReplacement(";"+currentHtmlParameter.getName()+"="));
if (this.debugEnabled) log.debug("Removing the pseudo URL parameter from ["+requestUrl+"]: ["+hackedUrl+"]");
//Note: the URL is not escaped. Handle it.
msg1Initial.getRequestHeader().setURI(new URI(hackedUrl, false));
}
msg1Initial.setGetParams(urlRequestParams); //url parameters
//send the message, minus the value for the current parameter, and see how it comes back.
//Note: automatically follow redirects.. no need to look at any intermediate responses.
//this was only necessary for cookie-based session implementations
sendAndReceive(msg1Initial);
//if non-200 on the response for message 1, no point in continuing. Bale out.
if (msg1Initial.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg1Initial.getResponseHeader().getStatusCode()+"] when sending ["+msg1Initial.getRequestHeader().getURI()+ "] with param ["+ currentHtmlParameter.getName() +"] = NULL (possibly somewhere in the redirects)");
continue;
}
//now parse the HTML response for urls that contain the same parameter name, and look at the values for that parameter
//if no values are found for the parameter, then
//1) we are messing with the wrong field, or
//2) the app doesn't do sessions
//either way, there is not much point in continuing to look at this field..
//parse out links in HTML (assume for a moment that all the URLs are in links)
//this gives us a map of parameter value for the current parameter, to the number of times it was encountered in links in the HTML
SortedMap <String, Integer> parametersInHTMLURls = getParameterValueCountInHtml (msg1Initial.getResponseBody().toString(), currentHtmlParameter.getName(), isPseudoUrlParameter);
if (this.debugEnabled) log.debug("The count of the various values of the ["+ currentHtmlParameter.getName() + "] parameters in urls in the result of retrieving the url with a null value for parameter ["+ currentHtmlParameter.getName() + "]: "+ parametersInHTMLURls);
if (parametersInHTMLURls.isEmpty()) {
//setting the param to NULL did not cause any new values to be generated for it in the output..
//so either..
//it is not a session field, or
//it is a session field, but a session is only issued on authentication, and this is not an authentication url
//the app doesn't do sessions (etc)
//either way, the parameter/url combo is not vulnerable, so continue with the next parameter
if ( this.debugEnabled) log.debug("The URL parameter ["+ currentHtmlParameter.getName() + "] was NOT set in any links in the response, when "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "] was set to NULL in the request, so it is likely not a session id field");
continue; //to the next parameter
} else if (parametersInHTMLURls.size() == 1) {
//the parameter was set to just one value in the output
//so it's quite possible it is the session id field that we have been looking for
//caveat 1: check it is longer than 3 chars long, to remove false positives..
//we assume here that a real session id will always be greater than 3 characters long
//caveat 2: the value we got back for the param must be different from the value we
//over-wrote with NULL (empty) in the first place, otherwise it is very unlikely to
//be a session id field
possibleSessionIdIssuedForUrlParam=parametersInHTMLURls.firstKey();
//did we get back the same value we just nulled out in the original request?
//if so, use this to eliminate false positives, and to optimise.
if ( possibleSessionIdIssuedForUrlParam.equals (currentHtmlParameter.getValue())) {
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes 1 distinct values to be set for it in URLs in the output, but the possible session id value ["+ possibleSessionIdIssuedForUrlParam + "] is the same as the value we over-wrote with NULL. 'Sorry, kid. You got the gift, but it looks like you're waiting for something'");
continue; //to the next parameter
}
if (possibleSessionIdIssuedForUrlParam.length() > 3) {
//raise an alert here on an exposed session id, even if it is not subject to a session fixation vulnerability
//log.info("The URL parameter ["+ currentHtmlParameter.getName() + "] was set ["+ parametersInHTMLURls.get(possibleSessionIdIssuedForUrlParam)+ "] times to ["+ possibleSessionIdIssuedForUrlParam + "] in links in the response, when "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "] was set to NULL in the request. This likely indicates it is a session id field.");
//pass the original param value here, not the new value, since we're displaying the session id exposed in the original message
String extraInfo = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue());
String attack = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.attack", (isPseudoUrlParameter?"pseudo/URL rewritten ":"") + currentHtmlParameter.getType(), currentHtmlParameter.getName());
String vulnname=Constant.messages.getString("ascanbeta.sessionidexposedinurl.name");
String vulndesc=Constant.messages.getString("ascanbeta.sessionidexposedinurl.desc");
String vulnsoln=Constant.messages.getString("ascanbeta.sessionidexposedinurl.soln");
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.extrainfo.loginpage"));
}
//call bingo with some extra info, indicating that the alert is
//not specific to Session Fixation, but has its own title and description (etc)
//the alert here is "Session id exposed in url", or words to that effect.
bingo(Alert.RISK_MEDIUM, Alert.WARNING, vulnname, vulndesc,
getBaseMsg().getRequestHeader().getURI().getURI(),
currentHtmlParameter.getName(), attack,
extraInfo, vulnsoln, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionidexposedinurl.alert.logmessage",
getBaseMsg().getRequestHeader().getMethod(),
getBaseMsg().getRequestHeader().getURI().getURI(),
(isPseudoUrlParameter?"pseudo ":"") +currentHtmlParameter.getType(),
currentHtmlParameter.getName());
log.info(logMessage);
//}
//Note: do NOT continue to the next field at this point..
//since we still need to check for Session Fixation.
}
else {
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes 1 distinct values to be set for it in URLs in the output, but the possible session id value ["+ possibleSessionIdIssuedForUrlParam + "] is too short to be a real session id.");
continue; //to the next parameter
}
} else {
//strange scenario: setting the param to null causes multiple different values to be set for it in the output
//it could still be a session parameter, but we assume it is *not* a session id field
//log it, but assume it is not a session id
if ( this.debugEnabled ) log.debug((isPseudoUrlParameter?"pseudo/URL rewritten":"")+ " URL param ["+ currentHtmlParameter.getName() + "], when set to NULL, causes ["+ parametersInHTMLURls.size() + "] distinct values to be set for it in URLs in the output. Assuming it is NOT a session id as a consequence. This could be a false negative");
continue; //to the next parameter
}
////////////////////////////////////////////////////////////////////////////////////////////
/// Message 2 - processing starts here
////////////////////////////////////////////////////////////////////////////////////////////
//we now have a plausible session id field to play with, so set it to a borrowed value.
//ie: lets re-send the request, but add in the new (valid) session value that was just issued.
//the aim is then to see if it accepts the session without re-issuing the session id (BAD, in some circumstances),
//or if it issues a new session value (GOOD, in most circumstances)
//and set the (modified) session for the second message
//use a copy of msg2Initial, since it has already had the correct session removed in the request..
//do NOT use msg2Initial itself, as this will cause both requests in the GUI to show the modified data..
//finally send the second message, and see how it comes back.
HttpMessage msg2Initial= msg1Initial.cloneRequest();
//set the parameter to the new session id value (in different manners, depending on whether it is a real url param, or a pseudo url param)
if ( isPseudoUrlParameter ) {
//we need to "rewrite" (hack) the URL path to remove the pseudo url parameter portion
//id, we need to remove the ";jsessionid=<sessionid>" bit from the path
//and replace it with ";jsessionid=" (ie, we nullify the possible "session" parameter in the hope that a new session will be issued)
//then we continue as usual to see if the URL is vulnerable to a Session Fixation issue
//Side note: quote the string to search for, and the replacement, so that regex special characters are treated as literals
String hackedUrl = requestUrl.replaceAll(
Pattern.quote(";"+ currentHtmlParameter.getName()+"=" + currentHtmlParameter.getValue()),
Matcher.quoteReplacement(";" +currentHtmlParameter.getName()+"="+ possibleSessionIdIssuedForUrlParam));
if (this.debugEnabled) log.debug("Changing the pseudo URL parameter from ["+requestUrl+"]: ["+hackedUrl+"]");
//Note: the URL is not escaped
msg2Initial.getRequestHeader().setURI(new URI(hackedUrl, false));
msg2Initial.setGetParams(msg1Initial.getUrlParams()); //restore the GET params
} else {
//do it via the normal url parameters
TreeSet <HtmlParameter> urlRequestParams2 = msg2Initial.getUrlParams();
urlRequestParams2.add(new HtmlParameter(Type.url, currentHtmlParameter.getName(), possibleSessionIdIssuedForUrlParam));
msg2Initial.setGetParams(urlRequestParams2); //restore the GET params
}
//resend a copy of the initial message, but with the new valid session parameter added in, to see if it is accepted
//automatically follow redirects, which are irrelevant for the purposes of testing URL parameters
sendAndReceive(msg2Initial);
//final result was non-200, no point in continuing. Bale out.
if (msg2Initial.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
if ( this.debugEnabled ) log.debug("Got a non-200 response code ["+ msg2Initial.getResponseHeader().getStatusCode()+"] when sending ["+msg2Initial.getRequestHeader().getURI()+ "] with a borrowed session (or by following a redirect) for param ["+currentHtmlParameter.getName()+"]");
continue; //next field!
}
//do the analysis on the parameters in link urls in the HTML output again to see if the session id was regenerated
SortedMap <String, Integer> parametersInHTMLURls2 = getParameterValueCountInHtml (msg2Initial.getResponseBody().toString(), currentHtmlParameter.getName(), isPseudoUrlParameter);
if ( this.debugEnabled ) log.debug("The count of the various values of the ["+ currentHtmlParameter.getName() + "] parameters in urls in the result of retrieving the url with a borrowed session value for parameter ["+ currentHtmlParameter.getName() + "]: "+ parametersInHTMLURls2);
if ( parametersInHTMLURls2.size() != 1) {
//either no values, or multiple values, but not 1 value. For a session that was regenerated, we would have expected to see
//just 1 new value
if (this.debugEnabled) log.debug("The HTML has spoken. ["+currentHtmlParameter.getName()+"] doesn't look like a session id field, because there are "+parametersInHTMLURls2.size()+" distinct values for this parameter in urls in the HTML output");
continue;
}
//there is but one value for this param in links in the HTML output. But is it vulnerable to Session Fixation? Ie, is it the same parameter?
String possibleSessionIdIssuedForUrlParam2=parametersInHTMLURls2.firstKey();
if ( possibleSessionIdIssuedForUrlParam2.equals (possibleSessionIdIssuedForUrlParam)) {
//same sessionid used in the output.. so it is likely that we have a SessionFixation issue..
//use the url param extrainfo message, which is specific to the case of url parameters and url re-writing Session Fixation issue
//pretty much everything else is generic to all types of Session Fixation vulnerabilities
String extraInfo = Constant.messages.getString("ascanbeta.sessionfixation.alert.url.extrainfo", currentHtmlParameter.getName(), possibleSessionIdIssuedForUrlParam, possibleSessionIdIssuedForUrlParam2);
String attack = Constant.messages.getString("ascanbeta.sessionfixation.alert.attack", (isPseudoUrlParameter?"pseudo/URL rewritten ":"") + currentHtmlParameter.getType(), currentHtmlParameter.getName());
int risk = Alert.RISK_LOW;
if (loginUrl) {
extraInfo += ("\n" + Constant.messages.getString("ascanbeta.sessionfixation.alert.url.extrainfo.loginpage"));
//login page, so higher risk
risk = Alert.RISK_MEDIUM;
} else {
//not a login page.. lower risk
risk = Alert.RISK_LOW;
}
bingo(risk, Alert.WARNING, getBaseMsg().getRequestHeader().getURI().getURI(), currentHtmlParameter.getName(), attack, extraInfo, getBaseMsg());
//if ( log.isInfoEnabled()) {
String logMessage = Constant.messages.getString("ascanbeta.sessionfixation.alert.logmessage", getBaseMsg().getRequestHeader().getMethod(), getBaseMsg().getRequestHeader().getURI().getURI(), (isPseudoUrlParameter?"pseudo ":"") +currentHtmlParameter.getType(), currentHtmlParameter.getName());
log.info(logMessage);
//}
continue; //jump to the next iteration of the loop (ie, the next parameter)
}
else {
//different sessionid used in the output.. so it is unlikely that we have a SessionFixation issue..
//more likely that the Session is being re-issued for every single request, or we have issues a login request, which
//normally causes a session to be reissued
if (this.debugEnabled) log.debug("The "+ (isPseudoUrlParameter?"pseudo/URL rewritten":"") + " parameter ["+currentHtmlParameter.getName() + "] in url ["+ getBaseMsg().getRequestHeader().getMethod()+ "] ["+ getBaseMsg().getRequestHeader().getURI() + "] changes with requests, and so it likely not vulnerable to Session Fixation");
}
continue; //onto the next parameter
} //end of the url parameter code.
} //end of the for loop around the parameter list
} catch (Exception e) {
//Do not try to internationalise this.. we need an error message in any event..
//if it's in English, it's still better than not having it at all.
log.error("An error occurred checking a url for Session Fixation issues", e);
}
}
|
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/transport/ReceivePack.java b/org.eclipse.jgit/src/org/eclipse/jgit/transport/ReceivePack.java
index 26b66db..6aa64cc 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/transport/ReceivePack.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/transport/ReceivePack.java
@@ -1,913 +1,913 @@
/*
* Copyright (C) 2008-2009, Google Inc.
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* 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 Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.transport;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.PackProtocolException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.NullProgressMonitor;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PackLock;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.Config.SectionParser;
import org.eclipse.jgit.revwalk.ObjectWalk;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevFlag;
import org.eclipse.jgit.revwalk.RevObject;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand.Result;
import org.eclipse.jgit.util.io.InterruptTimer;
import org.eclipse.jgit.util.io.TimeoutInputStream;
import org.eclipse.jgit.util.io.TimeoutOutputStream;
/**
* Implements the server side of a push connection, receiving objects.
*/
public class ReceivePack {
static final String CAPABILITY_REPORT_STATUS = BasePackPushConnection.CAPABILITY_REPORT_STATUS;
static final String CAPABILITY_DELETE_REFS = BasePackPushConnection.CAPABILITY_DELETE_REFS;
static final String CAPABILITY_OFS_DELTA = BasePackPushConnection.CAPABILITY_OFS_DELTA;
/** Database we write the stored objects into. */
private final Repository db;
/** Revision traversal support over {@link #db}. */
private final RevWalk walk;
/** Should an incoming transfer validate objects? */
private boolean checkReceivedObjects;
/** Should an incoming transfer permit create requests? */
private boolean allowCreates;
/** Should an incoming transfer permit delete requests? */
private boolean allowDeletes;
/** Should an incoming transfer permit non-fast-forward requests? */
private boolean allowNonFastForwards;
private boolean allowOfsDelta;
/** Identity to record action as within the reflog. */
private PersonIdent refLogIdent;
/** Hook to validate the update commands before execution. */
private PreReceiveHook preReceive;
/** Hook to report on the commands after execution. */
private PostReceiveHook postReceive;
/** Timeout in seconds to wait for client interaction. */
private int timeout;
/** Timer to manage {@link #timeout}. */
private InterruptTimer timer;
private TimeoutInputStream timeoutIn;
private InputStream rawIn;
private OutputStream rawOut;
private PacketLineIn pckIn;
private PacketLineOut pckOut;
private PrintWriter msgs;
/** The refs we advertised as existing at the start of the connection. */
private Map<String, Ref> refs;
/** Capabilities requested by the client. */
private Set<String> enabledCapablities;
/** Commands to execute, as received by the client. */
private List<ReceiveCommand> commands;
/** An exception caught while unpacking and fsck'ing the objects. */
private Throwable unpackError;
/** if {@link #enabledCapablities} has {@link #CAPABILITY_REPORT_STATUS} */
private boolean reportStatus;
/** Lock around the received pack file, while updating refs. */
private PackLock packLock;
/**
* Create a new pack receive for an open repository.
*
* @param into
* the destination repository.
*/
public ReceivePack(final Repository into) {
db = into;
walk = new RevWalk(db);
final ReceiveConfig cfg = db.getConfig().get(ReceiveConfig.KEY);
checkReceivedObjects = cfg.checkReceivedObjects;
allowCreates = cfg.allowCreates;
allowDeletes = cfg.allowDeletes;
allowNonFastForwards = cfg.allowNonFastForwards;
allowOfsDelta = cfg.allowOfsDelta;
preReceive = PreReceiveHook.NULL;
postReceive = PostReceiveHook.NULL;
}
private static class ReceiveConfig {
static final SectionParser<ReceiveConfig> KEY = new SectionParser<ReceiveConfig>() {
public ReceiveConfig parse(final Config cfg) {
return new ReceiveConfig(cfg);
}
};
final boolean checkReceivedObjects;
final boolean allowCreates;
final boolean allowDeletes;
final boolean allowNonFastForwards;
final boolean allowOfsDelta;
ReceiveConfig(final Config config) {
checkReceivedObjects = config.getBoolean("receive", "fsckobjects",
false);
allowCreates = true;
allowDeletes = !config.getBoolean("receive", "denydeletes", false);
allowNonFastForwards = !config.getBoolean("receive",
"denynonfastforwards", false);
allowOfsDelta = config.getBoolean("repack", "usedeltabaseoffset",
true);
}
}
/** @return the repository this receive completes into. */
public final Repository getRepository() {
return db;
}
/** @return the RevWalk instance used by this connection. */
public final RevWalk getRevWalk() {
return walk;
}
/** @return all refs which were advertised to the client. */
public final Map<String, Ref> getAdvertisedRefs() {
return refs;
}
/**
* @return true if this instance will verify received objects are formatted
* correctly. Validating objects requires more CPU time on this side
* of the connection.
*/
public boolean isCheckReceivedObjects() {
return checkReceivedObjects;
}
/**
* @param check
* true to enable checking received objects; false to assume all
* received objects are valid.
*/
public void setCheckReceivedObjects(final boolean check) {
checkReceivedObjects = check;
}
/** @return true if the client can request refs to be created. */
public boolean isAllowCreates() {
return allowCreates;
}
/**
* @param canCreate
* true to permit create ref commands to be processed.
*/
public void setAllowCreates(final boolean canCreate) {
allowCreates = canCreate;
}
/** @return true if the client can request refs to be deleted. */
public boolean isAllowDeletes() {
return allowDeletes;
}
/**
* @param canDelete
* true to permit delete ref commands to be processed.
*/
public void setAllowDeletes(final boolean canDelete) {
allowDeletes = canDelete;
}
/**
* @return true if the client can request non-fast-forward updates of a ref,
* possibly making objects unreachable.
*/
public boolean isAllowNonFastForwards() {
return allowNonFastForwards;
}
/**
* @param canRewind
* true to permit the client to ask for non-fast-forward updates
* of an existing ref.
*/
public void setAllowNonFastForwards(final boolean canRewind) {
allowNonFastForwards = canRewind;
}
/** @return identity of the user making the changes in the reflog. */
public PersonIdent getRefLogIdent() {
return refLogIdent;
}
/**
* Set the identity of the user appearing in the affected reflogs.
* <p>
* The timestamp portion of the identity is ignored. A new identity with the
* current timestamp will be created automatically when the updates occur
* and the log records are written.
*
* @param pi
* identity of the user. If null the identity will be
* automatically determined based on the repository
* configuration.
*/
public void setRefLogIdent(final PersonIdent pi) {
refLogIdent = pi;
}
/** @return get the hook invoked before updates occur. */
public PreReceiveHook getPreReceiveHook() {
return preReceive;
}
/**
* Set the hook which is invoked prior to commands being executed.
* <p>
* Only valid commands (those which have no obvious errors according to the
* received input and this instance's configuration) are passed into the
* hook. The hook may mark a command with a result of any value other than
* {@link Result#NOT_ATTEMPTED} to block its execution.
* <p>
* The hook may be called with an empty command collection if the current
* set is completely invalid.
*
* @param h
* the hook instance; may be null to disable the hook.
*/
public void setPreReceiveHook(final PreReceiveHook h) {
preReceive = h != null ? h : PreReceiveHook.NULL;
}
/** @return get the hook invoked after updates occur. */
public PostReceiveHook getPostReceiveHook() {
return postReceive;
}
/**
* Set the hook which is invoked after commands are executed.
* <p>
* Only successful commands (type is {@link Result#OK}) are passed into the
* hook. The hook may be called with an empty command collection if the
* current set all resulted in an error.
*
* @param h
* the hook instance; may be null to disable the hook.
*/
public void setPostReceiveHook(final PostReceiveHook h) {
postReceive = h != null ? h : PostReceiveHook.NULL;
}
/** @return timeout (in seconds) before aborting an IO operation. */
public int getTimeout() {
return timeout;
}
/**
* Set the timeout before willing to abort an IO call.
*
* @param seconds
* number of seconds to wait (with no data transfer occurring)
* before aborting an IO read or write operation with the
* connected client.
*/
public void setTimeout(final int seconds) {
timeout = seconds;
}
/** @return all of the command received by the current request. */
public List<ReceiveCommand> getAllCommands() {
return Collections.unmodifiableList(commands);
}
/**
* Send an error message to the client, if it supports receiving them.
* <p>
* If the client doesn't support receiving messages, the message will be
* discarded, with no other indication to the caller or to the client.
* <p>
* {@link PreReceiveHook}s should always try to use
* {@link ReceiveCommand#setResult(Result, String)} with a result status of
* {@link Result#REJECTED_OTHER_REASON} to indicate any reasons for
* rejecting an update. Messages attached to a command are much more likely
* to be returned to the client.
*
* @param what
* string describing the problem identified by the hook. The
* string must not end with an LF, and must not contain an LF.
*/
public void sendError(final String what) {
sendMessage("error", what);
}
/**
* Send a message to the client, if it supports receiving them.
* <p>
* If the client doesn't support receiving messages, the message will be
* discarded, with no other indication to the caller or to the client.
*
* @param what
* string describing the problem identified by the hook. The
* string must not end with an LF, and must not contain an LF.
*/
public void sendMessage(final String what) {
sendMessage("remote", what);
}
private void sendMessage(final String type, final String what) {
if (msgs != null)
msgs.println(type + ": " + what);
}
/**
* Execute the receive task on the socket.
*
* @param input
* raw input to read client commands and pack data from. Caller
* must ensure the input is buffered, otherwise read performance
* may suffer.
* @param output
* response back to the Git network client. Caller must ensure
* the output is buffered, otherwise write performance may
* suffer.
* @param messages
* secondary "notice" channel to send additional messages out
* through. When run over SSH this should be tied back to the
* standard error channel of the command execution. For most
* other network connections this should be null.
* @throws IOException
*/
public void receive(final InputStream input, final OutputStream output,
final OutputStream messages) throws IOException {
try {
rawIn = input;
rawOut = output;
if (timeout > 0) {
final Thread caller = Thread.currentThread();
timer = new InterruptTimer(caller.getName() + "-Timer");
timeoutIn = new TimeoutInputStream(rawIn, timer);
TimeoutOutputStream o = new TimeoutOutputStream(rawOut, timer);
timeoutIn.setTimeout(timeout * 1000);
o.setTimeout(timeout * 1000);
rawIn = timeoutIn;
rawOut = o;
}
pckIn = new PacketLineIn(rawIn);
pckOut = new PacketLineOut(rawOut);
if (messages != null) {
msgs = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(messages, Constants.CHARSET),
8192)) {
@Override
public void println() {
print('\n');
}
};
}
enabledCapablities = new HashSet<String>();
commands = new ArrayList<ReceiveCommand>();
service();
} finally {
try {
if (msgs != null) {
msgs.flush();
}
} finally {
unlockPack();
timeoutIn = null;
rawIn = null;
rawOut = null;
pckIn = null;
pckOut = null;
msgs = null;
refs = null;
enabledCapablities = null;
commands = null;
if (timer != null) {
try {
timer.terminate();
} finally {
timer = null;
}
}
}
}
}
private void service() throws IOException {
sendAdvertisedRefs();
recvCommands();
if (!commands.isEmpty()) {
enableCapabilities();
if (needPack()) {
try {
receivePack();
if (isCheckReceivedObjects())
checkConnectivity();
unpackError = null;
} catch (IOException err) {
unpackError = err;
} catch (RuntimeException err) {
unpackError = err;
} catch (Error err) {
unpackError = err;
}
}
if (unpackError == null) {
validateCommands();
executeCommands();
}
unlockPack();
if (reportStatus) {
sendStatusReport(true, new Reporter() {
void sendString(final String s) throws IOException {
pckOut.writeString(s + "\n");
}
});
pckOut.end();
} else if (msgs != null) {
sendStatusReport(false, new Reporter() {
void sendString(final String s) throws IOException {
msgs.println(s);
}
});
msgs.flush();
}
postReceive.onPostReceive(this, filterCommands(Result.OK));
}
}
private void unlockPack() {
if (packLock != null) {
packLock.unlock();
packLock = null;
}
}
private void sendAdvertisedRefs() throws IOException {
final RevFlag advertised = walk.newFlag("ADVERTISED");
final RefAdvertiser adv = new RefAdvertiser(pckOut, walk, advertised);
adv.advertiseCapability(CAPABILITY_DELETE_REFS);
adv.advertiseCapability(CAPABILITY_REPORT_STATUS);
if (allowOfsDelta)
adv.advertiseCapability(CAPABILITY_OFS_DELTA);
refs = new HashMap<String, Ref>(db.getAllRefs());
final Ref head = refs.remove(Constants.HEAD);
adv.send(refs.values());
if (head != null && head.getName().equals(head.getOrigName()))
adv.advertiseHave(head.getObjectId());
adv.includeAdditionalHaves();
if (adv.isEmpty())
adv.advertiseId(ObjectId.zeroId(), "capabilities^{}");
pckOut.end();
}
private void recvCommands() throws IOException {
for (;;) {
String line;
try {
line = pckIn.readStringRaw();
} catch (EOFException eof) {
if (commands.isEmpty())
return;
throw eof;
}
if (line == PacketLineIn.END)
break;
if (commands.isEmpty()) {
final int nul = line.indexOf('\0');
if (nul >= 0) {
for (String c : line.substring(nul + 1).split(" "))
enabledCapablities.add(c);
line = line.substring(0, nul);
}
}
if (line.length() < 83) {
final String m = "error: invalid protocol: wanted 'old new ref'";
sendError(m);
throw new PackProtocolException(m);
}
final ObjectId oldId = ObjectId.fromString(line.substring(0, 40));
final ObjectId newId = ObjectId.fromString(line.substring(41, 81));
final String name = line.substring(82);
final ReceiveCommand cmd = new ReceiveCommand(oldId, newId, name);
cmd.setRef(refs.get(cmd.getRefName()));
commands.add(cmd);
}
}
private void enableCapabilities() {
reportStatus = enabledCapablities.contains(CAPABILITY_REPORT_STATUS);
}
private boolean needPack() {
for (final ReceiveCommand cmd : commands) {
if (cmd.getType() != ReceiveCommand.Type.DELETE)
return true;
}
return false;
}
private void receivePack() throws IOException {
// It might take the client a while to pack the objects it needs
// to send to us. We should increase our timeout so we don't
// abort while the client is computing.
//
if (timeoutIn != null)
timeoutIn.setTimeout(10 * timeout * 1000);
final IndexPack ip = IndexPack.create(db, rawIn);
ip.setFixThin(true);
ip.setObjectChecking(isCheckReceivedObjects());
ip.index(NullProgressMonitor.INSTANCE);
String lockMsg = "jgit receive-pack";
if (getRefLogIdent() != null)
lockMsg += " from " + getRefLogIdent().toExternalString();
packLock = ip.renameAndOpenPack(lockMsg);
if (timeoutIn != null)
timeoutIn.setTimeout(timeout * 1000);
}
private void checkConnectivity() throws IOException {
final ObjectWalk ow = new ObjectWalk(db);
for (final ReceiveCommand cmd : commands) {
if (cmd.getResult() != Result.NOT_ATTEMPTED)
continue;
if (cmd.getType() == ReceiveCommand.Type.DELETE)
continue;
ow.markStart(ow.parseAny(cmd.getNewId()));
}
for (final Ref ref : refs.values())
ow.markUninteresting(ow.parseAny(ref.getObjectId()));
ow.checkConnectivity();
}
private void validateCommands() {
for (final ReceiveCommand cmd : commands) {
final Ref ref = cmd.getRef();
if (cmd.getResult() != Result.NOT_ATTEMPTED)
continue;
if (cmd.getType() == ReceiveCommand.Type.DELETE
&& !isAllowDeletes()) {
// Deletes are not supported on this repository.
//
cmd.setResult(Result.REJECTED_NODELETE);
continue;
}
if (cmd.getType() == ReceiveCommand.Type.CREATE) {
if (!isAllowCreates()) {
cmd.setResult(Result.REJECTED_NOCREATE);
continue;
}
if (ref != null && !isAllowNonFastForwards()) {
// Creation over an existing ref is certainly not going
// to be a fast-forward update. We can reject it early.
//
cmd.setResult(Result.REJECTED_NONFASTFORWARD);
continue;
}
if (ref != null) {
- // A well behaved client shouldn't have sent us an
- // update command for a ref we advertised to it.
+ // A well behaved client shouldn't have sent us a
+ // create command for a ref we advertised to it.
//
cmd.setResult(Result.REJECTED_OTHER_REASON, "ref exists");
continue;
}
}
if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null
&& !ObjectId.zeroId().equals(cmd.getOldId())
&& !ref.getObjectId().equals(cmd.getOldId())) {
// Delete commands can be sent with the old id matching our
// advertised value, *OR* with the old id being 0{40}. Any
// other requested old id is invalid.
//
cmd.setResult(Result.REJECTED_OTHER_REASON,
"invalid old id sent");
continue;
}
if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
if (ref == null) {
// The ref must have been advertised in order to be updated.
//
cmd.setResult(Result.REJECTED_OTHER_REASON, "no such ref");
continue;
}
if (!ref.getObjectId().equals(cmd.getOldId())) {
// A properly functioning client will send the same
// object id we advertised.
//
cmd.setResult(Result.REJECTED_OTHER_REASON,
"invalid old id sent");
continue;
}
// Is this possibly a non-fast-forward style update?
//
RevObject oldObj, newObj;
try {
oldObj = walk.parseAny(cmd.getOldId());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
.getOldId().name());
continue;
}
try {
newObj = walk.parseAny(cmd.getNewId());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
.getNewId().name());
continue;
}
if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
try {
if (!walk.isMergedInto((RevCommit) oldObj,
(RevCommit) newObj)) {
cmd
.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
}
} catch (MissingObjectException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
.getMessage());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_OTHER_REASON);
}
} else {
cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
}
}
if (!cmd.getRefName().startsWith(Constants.R_REFS)
|| !Repository.isValidRefName(cmd.getRefName())) {
cmd.setResult(Result.REJECTED_OTHER_REASON, "funny refname");
}
}
}
private void executeCommands() {
preReceive.onPreReceive(this, filterCommands(Result.NOT_ATTEMPTED));
for (final ReceiveCommand cmd : filterCommands(Result.NOT_ATTEMPTED))
execute(cmd);
}
private void execute(final ReceiveCommand cmd) {
try {
final RefUpdate ru = db.updateRef(cmd.getRefName());
ru.setRefLogIdent(getRefLogIdent());
switch (cmd.getType()) {
case DELETE:
if (!ObjectId.zeroId().equals(cmd.getOldId())) {
// We can only do a CAS style delete if the client
// didn't bork its delete request by sending the
// wrong zero id rather than the advertised one.
//
ru.setExpectedOldObjectId(cmd.getOldId());
}
ru.setForceUpdate(true);
status(cmd, ru.delete(walk));
break;
case CREATE:
case UPDATE:
case UPDATE_NONFASTFORWARD:
ru.setForceUpdate(isAllowNonFastForwards());
ru.setExpectedOldObjectId(cmd.getOldId());
ru.setNewObjectId(cmd.getNewId());
ru.setRefLogMessage("push", true);
status(cmd, ru.update(walk));
break;
}
} catch (IOException err) {
cmd.setResult(Result.REJECTED_OTHER_REASON, "lock error: "
+ err.getMessage());
}
}
private void status(final ReceiveCommand cmd, final RefUpdate.Result result) {
switch (result) {
case NOT_ATTEMPTED:
cmd.setResult(Result.NOT_ATTEMPTED);
break;
case LOCK_FAILURE:
case IO_FAILURE:
cmd.setResult(Result.LOCK_FAILURE);
break;
case NO_CHANGE:
case NEW:
case FORCED:
case FAST_FORWARD:
cmd.setResult(Result.OK);
break;
case REJECTED:
cmd.setResult(Result.REJECTED_NONFASTFORWARD);
break;
case REJECTED_CURRENT_BRANCH:
cmd.setResult(Result.REJECTED_CURRENT_BRANCH);
break;
default:
cmd.setResult(Result.REJECTED_OTHER_REASON, result.name());
break;
}
}
private List<ReceiveCommand> filterCommands(final Result want) {
final List<ReceiveCommand> r = new ArrayList<ReceiveCommand>(commands
.size());
for (final ReceiveCommand cmd : commands) {
if (cmd.getResult() == want)
r.add(cmd);
}
return r;
}
private void sendStatusReport(final boolean forClient, final Reporter out)
throws IOException {
if (unpackError != null) {
out.sendString("unpack error " + unpackError.getMessage());
if (forClient) {
for (final ReceiveCommand cmd : commands) {
out.sendString("ng " + cmd.getRefName()
+ " n/a (unpacker error)");
}
}
return;
}
if (forClient)
out.sendString("unpack ok");
for (final ReceiveCommand cmd : commands) {
if (cmd.getResult() == Result.OK) {
if (forClient)
out.sendString("ok " + cmd.getRefName());
continue;
}
final StringBuilder r = new StringBuilder();
r.append("ng ");
r.append(cmd.getRefName());
r.append(" ");
switch (cmd.getResult()) {
case NOT_ATTEMPTED:
r.append("server bug; ref not processed");
break;
case REJECTED_NOCREATE:
r.append("creation prohibited");
break;
case REJECTED_NODELETE:
r.append("deletion prohibited");
break;
case REJECTED_NONFASTFORWARD:
r.append("non-fast forward");
break;
case REJECTED_CURRENT_BRANCH:
r.append("branch is currently checked out");
break;
case REJECTED_MISSING_OBJECT:
if (cmd.getMessage() == null)
r.append("missing object(s)");
else if (cmd.getMessage().length() == 2 * Constants.OBJECT_ID_LENGTH)
r.append("object " + cmd.getMessage() + " missing");
else
r.append(cmd.getMessage());
break;
case REJECTED_OTHER_REASON:
if (cmd.getMessage() == null)
r.append("unspecified reason");
else
r.append(cmd.getMessage());
break;
case LOCK_FAILURE:
r.append("failed to lock");
break;
case OK:
// We shouldn't have reached this case (see 'ok' case above).
continue;
}
out.sendString(r.toString());
}
}
static abstract class Reporter {
abstract void sendString(String s) throws IOException;
}
}
| true | true | private void validateCommands() {
for (final ReceiveCommand cmd : commands) {
final Ref ref = cmd.getRef();
if (cmd.getResult() != Result.NOT_ATTEMPTED)
continue;
if (cmd.getType() == ReceiveCommand.Type.DELETE
&& !isAllowDeletes()) {
// Deletes are not supported on this repository.
//
cmd.setResult(Result.REJECTED_NODELETE);
continue;
}
if (cmd.getType() == ReceiveCommand.Type.CREATE) {
if (!isAllowCreates()) {
cmd.setResult(Result.REJECTED_NOCREATE);
continue;
}
if (ref != null && !isAllowNonFastForwards()) {
// Creation over an existing ref is certainly not going
// to be a fast-forward update. We can reject it early.
//
cmd.setResult(Result.REJECTED_NONFASTFORWARD);
continue;
}
if (ref != null) {
// A well behaved client shouldn't have sent us an
// update command for a ref we advertised to it.
//
cmd.setResult(Result.REJECTED_OTHER_REASON, "ref exists");
continue;
}
}
if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null
&& !ObjectId.zeroId().equals(cmd.getOldId())
&& !ref.getObjectId().equals(cmd.getOldId())) {
// Delete commands can be sent with the old id matching our
// advertised value, *OR* with the old id being 0{40}. Any
// other requested old id is invalid.
//
cmd.setResult(Result.REJECTED_OTHER_REASON,
"invalid old id sent");
continue;
}
if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
if (ref == null) {
// The ref must have been advertised in order to be updated.
//
cmd.setResult(Result.REJECTED_OTHER_REASON, "no such ref");
continue;
}
if (!ref.getObjectId().equals(cmd.getOldId())) {
// A properly functioning client will send the same
// object id we advertised.
//
cmd.setResult(Result.REJECTED_OTHER_REASON,
"invalid old id sent");
continue;
}
// Is this possibly a non-fast-forward style update?
//
RevObject oldObj, newObj;
try {
oldObj = walk.parseAny(cmd.getOldId());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
.getOldId().name());
continue;
}
try {
newObj = walk.parseAny(cmd.getNewId());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
.getNewId().name());
continue;
}
if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
try {
if (!walk.isMergedInto((RevCommit) oldObj,
(RevCommit) newObj)) {
cmd
.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
}
} catch (MissingObjectException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
.getMessage());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_OTHER_REASON);
}
} else {
cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
}
}
if (!cmd.getRefName().startsWith(Constants.R_REFS)
|| !Repository.isValidRefName(cmd.getRefName())) {
cmd.setResult(Result.REJECTED_OTHER_REASON, "funny refname");
}
}
}
| private void validateCommands() {
for (final ReceiveCommand cmd : commands) {
final Ref ref = cmd.getRef();
if (cmd.getResult() != Result.NOT_ATTEMPTED)
continue;
if (cmd.getType() == ReceiveCommand.Type.DELETE
&& !isAllowDeletes()) {
// Deletes are not supported on this repository.
//
cmd.setResult(Result.REJECTED_NODELETE);
continue;
}
if (cmd.getType() == ReceiveCommand.Type.CREATE) {
if (!isAllowCreates()) {
cmd.setResult(Result.REJECTED_NOCREATE);
continue;
}
if (ref != null && !isAllowNonFastForwards()) {
// Creation over an existing ref is certainly not going
// to be a fast-forward update. We can reject it early.
//
cmd.setResult(Result.REJECTED_NONFASTFORWARD);
continue;
}
if (ref != null) {
// A well behaved client shouldn't have sent us a
// create command for a ref we advertised to it.
//
cmd.setResult(Result.REJECTED_OTHER_REASON, "ref exists");
continue;
}
}
if (cmd.getType() == ReceiveCommand.Type.DELETE && ref != null
&& !ObjectId.zeroId().equals(cmd.getOldId())
&& !ref.getObjectId().equals(cmd.getOldId())) {
// Delete commands can be sent with the old id matching our
// advertised value, *OR* with the old id being 0{40}. Any
// other requested old id is invalid.
//
cmd.setResult(Result.REJECTED_OTHER_REASON,
"invalid old id sent");
continue;
}
if (cmd.getType() == ReceiveCommand.Type.UPDATE) {
if (ref == null) {
// The ref must have been advertised in order to be updated.
//
cmd.setResult(Result.REJECTED_OTHER_REASON, "no such ref");
continue;
}
if (!ref.getObjectId().equals(cmd.getOldId())) {
// A properly functioning client will send the same
// object id we advertised.
//
cmd.setResult(Result.REJECTED_OTHER_REASON,
"invalid old id sent");
continue;
}
// Is this possibly a non-fast-forward style update?
//
RevObject oldObj, newObj;
try {
oldObj = walk.parseAny(cmd.getOldId());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
.getOldId().name());
continue;
}
try {
newObj = walk.parseAny(cmd.getNewId());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, cmd
.getNewId().name());
continue;
}
if (oldObj instanceof RevCommit && newObj instanceof RevCommit) {
try {
if (!walk.isMergedInto((RevCommit) oldObj,
(RevCommit) newObj)) {
cmd
.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
}
} catch (MissingObjectException e) {
cmd.setResult(Result.REJECTED_MISSING_OBJECT, e
.getMessage());
} catch (IOException e) {
cmd.setResult(Result.REJECTED_OTHER_REASON);
}
} else {
cmd.setType(ReceiveCommand.Type.UPDATE_NONFASTFORWARD);
}
}
if (!cmd.getRefName().startsWith(Constants.R_REFS)
|| !Repository.isValidRefName(cmd.getRefName())) {
cmd.setResult(Result.REJECTED_OTHER_REASON, "funny refname");
}
}
}
|
diff --git a/src/org/mozilla/javascript/TokenStream.java b/src/org/mozilla/javascript/TokenStream.java
index c2cdf2ac..7ea027dd 100644
--- a/src/org/mozilla/javascript/TokenStream.java
+++ b/src/org/mozilla/javascript/TokenStream.java
@@ -1,1462 +1,1463 @@
/* -*- 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):
* Roger Lawrence
* Mike McCabe
* Igor Bukanov
* Ethan Hugg
* Bob Jervis
* Terry Lucas
* Milen Nankov
*
* 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.*;
/**
* This class implements the JavaScript scanner.
*
* It is based on the C source files jsscan.c and jsscan.h
* in the jsref package.
*
* @see org.mozilla.javascript.Parser
*
* @author Mike McCabe
* @author Brendan Eich
*/
class TokenStream
{
/*
* For chars - because we need something out-of-range
* to check. (And checking EOF by exception is annoying.)
* Note distinction from EOF token type!
*/
private final static int
EOF_CHAR = -1;
TokenStream(Parser parser, Reader sourceReader, String sourceString,
int lineno)
{
this.parser = parser;
this.lineno = lineno;
if (sourceReader != null) {
if (sourceString != null) Kit.codeBug();
this.sourceReader = sourceReader;
this.sourceBuffer = new char[512];
this.sourceEnd = 0;
} else {
if (sourceString == null) Kit.codeBug();
this.sourceString = sourceString;
this.sourceEnd = sourceString.length();
}
this.sourceCursor = 0;
}
/* This function uses the cached op, string and number fields in
* TokenStream; if getToken has been called since the passed token
* was scanned, the op or string printed may be incorrect.
*/
String tokenToString(int token)
{
if (Token.printTrees) {
String name = Token.name(token);
switch (token) {
case Token.STRING:
case Token.REGEXP:
case Token.NAME:
return name + " `" + this.string + "'";
case Token.NUMBER:
return "NUMBER " + this.number;
}
return name;
}
return "";
}
static boolean isKeyword(String s)
{
return Token.EOF != stringToKeyword(s);
}
private static int stringToKeyword(String name)
{
// #string_id_map#
// The following assumes that Token.EOF == 0
final int
Id_break = Token.BREAK,
Id_case = Token.CASE,
Id_continue = Token.CONTINUE,
Id_default = Token.DEFAULT,
Id_delete = Token.DELPROP,
Id_do = Token.DO,
Id_else = Token.ELSE,
Id_export = Token.EXPORT,
Id_false = Token.FALSE,
Id_for = Token.FOR,
Id_function = Token.FUNCTION,
Id_if = Token.IF,
Id_in = Token.IN,
Id_let = Token.LET,
Id_new = Token.NEW,
Id_null = Token.NULL,
Id_return = Token.RETURN,
Id_switch = Token.SWITCH,
Id_this = Token.THIS,
Id_true = Token.TRUE,
Id_typeof = Token.TYPEOF,
Id_var = Token.VAR,
Id_void = Token.VOID,
Id_while = Token.WHILE,
Id_with = Token.WITH,
Id_yield = Token.YIELD,
// the following are #ifdef RESERVE_JAVA_KEYWORDS in jsscan.c
Id_abstract = Token.RESERVED,
Id_boolean = Token.RESERVED,
Id_byte = Token.RESERVED,
Id_catch = Token.CATCH,
Id_char = Token.RESERVED,
Id_class = Token.RESERVED,
Id_const = Token.CONST,
Id_debugger = Token.DEBUGGER,
Id_double = Token.RESERVED,
Id_enum = Token.RESERVED,
Id_extends = Token.RESERVED,
Id_final = Token.RESERVED,
Id_finally = Token.FINALLY,
Id_float = Token.RESERVED,
Id_goto = Token.RESERVED,
Id_implements = Token.RESERVED,
Id_import = Token.IMPORT,
Id_instanceof = Token.INSTANCEOF,
Id_int = Token.RESERVED,
Id_interface = Token.RESERVED,
Id_long = Token.RESERVED,
Id_native = Token.RESERVED,
Id_package = Token.RESERVED,
Id_private = Token.RESERVED,
Id_protected = Token.RESERVED,
Id_public = Token.RESERVED,
Id_short = Token.RESERVED,
Id_static = Token.RESERVED,
Id_super = Token.RESERVED,
Id_synchronized = Token.RESERVED,
Id_throw = Token.THROW,
Id_throws = Token.RESERVED,
Id_transient = Token.RESERVED,
Id_try = Token.TRY,
Id_volatile = Token.RESERVED;
int id;
String s = name;
// #generated# Last update: 2007-04-18 13:53:30 PDT
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 2: c=s.charAt(1);
if (c=='f') { if (s.charAt(0)=='i') {id=Id_if; break L0;} }
else if (c=='n') { if (s.charAt(0)=='i') {id=Id_in; break L0;} }
else if (c=='o') { if (s.charAt(0)=='d') {id=Id_do; break L0;} }
break L;
case 3: switch (s.charAt(0)) {
case 'f': if (s.charAt(2)=='r' && s.charAt(1)=='o') {id=Id_for; break L0;} break L;
case 'i': if (s.charAt(2)=='t' && s.charAt(1)=='n') {id=Id_int; break L0;} break L;
case 'l': if (s.charAt(2)=='t' && s.charAt(1)=='e') {id=Id_let; break L0;} break L;
case 'n': if (s.charAt(2)=='w' && s.charAt(1)=='e') {id=Id_new; break L0;} break L;
case 't': if (s.charAt(2)=='y' && s.charAt(1)=='r') {id=Id_try; break L0;} break L;
case 'v': if (s.charAt(2)=='r' && s.charAt(1)=='a') {id=Id_var; break L0;} break L;
} break L;
case 4: switch (s.charAt(0)) {
case 'b': X="byte";id=Id_byte; break L;
case 'c': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='a') {id=Id_case; break L0;} }
else if (c=='r') { if (s.charAt(2)=='a' && s.charAt(1)=='h') {id=Id_char; break L0;} }
break L;
case 'e': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='l') {id=Id_else; break L0;} }
else if (c=='m') { if (s.charAt(2)=='u' && s.charAt(1)=='n') {id=Id_enum; break L0;} }
break L;
case 'g': X="goto";id=Id_goto; break L;
case 'l': X="long";id=Id_long; break L;
case 'n': X="null";id=Id_null; break L;
case 't': c=s.charAt(3);
if (c=='e') { if (s.charAt(2)=='u' && s.charAt(1)=='r') {id=Id_true; break L0;} }
else if (c=='s') { if (s.charAt(2)=='i' && s.charAt(1)=='h') {id=Id_this; break L0;} }
break L;
case 'v': X="void";id=Id_void; break L;
case 'w': X="with";id=Id_with; break L;
} break L;
case 5: switch (s.charAt(2)) {
case 'a': X="class";id=Id_class; break L;
case 'e': c=s.charAt(0);
if (c=='b') { X="break";id=Id_break; }
else if (c=='y') { X="yield";id=Id_yield; }
break L;
case 'i': X="while";id=Id_while; break L;
case 'l': X="false";id=Id_false; break L;
case 'n': c=s.charAt(0);
if (c=='c') { X="const";id=Id_const; }
else if (c=='f') { X="final";id=Id_final; }
break L;
case 'o': c=s.charAt(0);
if (c=='f') { X="float";id=Id_float; }
else if (c=='s') { X="short";id=Id_short; }
break L;
case 'p': X="super";id=Id_super; break L;
case 'r': X="throw";id=Id_throw; break L;
case 't': X="catch";id=Id_catch; break L;
} break L;
case 6: switch (s.charAt(1)) {
case 'a': X="native";id=Id_native; break L;
case 'e': c=s.charAt(0);
if (c=='d') { X="delete";id=Id_delete; }
else if (c=='r') { X="return";id=Id_return; }
break L;
case 'h': X="throws";id=Id_throws; break L;
case 'm': X="import";id=Id_import; break L;
case 'o': X="double";id=Id_double; break L;
case 't': X="static";id=Id_static; break L;
case 'u': X="public";id=Id_public; break L;
case 'w': X="switch";id=Id_switch; break L;
case 'x': X="export";id=Id_export; break L;
case 'y': X="typeof";id=Id_typeof; break L;
} break L;
case 7: switch (s.charAt(1)) {
case 'a': X="package";id=Id_package; break L;
case 'e': X="default";id=Id_default; break L;
case 'i': X="finally";id=Id_finally; break L;
case 'o': X="boolean";id=Id_boolean; break L;
case 'r': X="private";id=Id_private; break L;
case 'x': X="extends";id=Id_extends; break L;
} break L;
case 8: switch (s.charAt(0)) {
case 'a': X="abstract";id=Id_abstract; break L;
case 'c': X="continue";id=Id_continue; break L;
case 'd': X="debugger";id=Id_debugger; break L;
case 'f': X="function";id=Id_function; break L;
case 'v': X="volatile";id=Id_volatile; break L;
} break L;
case 9: c=s.charAt(0);
if (c=='i') { X="interface";id=Id_interface; }
else if (c=='p') { X="protected";id=Id_protected; }
else if (c=='t') { X="transient";id=Id_transient; }
break L;
case 10: c=s.charAt(1);
if (c=='m') { X="implements";id=Id_implements; }
else if (c=='n') { X="instanceof";id=Id_instanceof; }
break L;
case 12: X="synchronized";id=Id_synchronized; break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
// #/string_id_map#
if (id == 0) { return Token.EOF; }
return id & 0xff;
}
final int getLineno() { return lineno; }
final String getString() { return string; }
final double getNumber() { return number; }
final boolean eof() { return hitEOF; }
final int getToken() throws IOException
{
int c;
retry:
for (;;) {
// Eat whitespace, possibly sensitive to newlines.
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
return Token.EOF;
} else if (c == '\n') {
dirtyLine = false;
return Token.EOL;
} else if (!isJSSpace(c)) {
if (c != '-') {
dirtyLine = true;
}
break;
}
}
if (c == '@') return Token.XMLATTR;
// identifier/keyword/instanceof?
// watch out for starting with a <backslash>
boolean identifierStart;
boolean isUnicodeEscapeStart = false;
if (c == '\\') {
c = getChar();
if (c == 'u') {
identifierStart = true;
isUnicodeEscapeStart = true;
stringBufferTop = 0;
} else {
identifierStart = false;
ungetChar(c);
c = '\\';
}
} else {
identifierStart = Character.isJavaIdentifierStart((char)c);
if (identifierStart) {
stringBufferTop = 0;
addToString(c);
}
}
if (identifierStart) {
boolean containsEscape = isUnicodeEscapeStart;
for (;;) {
if (isUnicodeEscapeStart) {
// strictly speaking we should probably push-back
// all the bad characters if the <backslash>uXXXX
// sequence is malformed. But since there isn't a
// correct context(is there?) for a bad Unicode
// escape sequence in an identifier, we can report
// an error here.
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
// Next check takes care about c < 0 and bad escape
if (escapeVal < 0) { break; }
}
if (escapeVal < 0) {
parser.addError("msg.invalid.escape");
return Token.ERROR;
}
addToString(escapeVal);
isUnicodeEscapeStart = false;
} else {
c = getChar();
if (c == '\\') {
c = getChar();
if (c == 'u') {
isUnicodeEscapeStart = true;
containsEscape = true;
} else {
parser.addError("msg.illegal.character");
return Token.ERROR;
}
} else {
if (c == EOF_CHAR
|| !Character.isJavaIdentifierPart((char)c))
{
break;
}
addToString(c);
}
}
}
ungetChar(c);
String str = getStringFromBuffer();
if (!containsEscape) {
// OPT we shouldn't have to make a string (object!) to
// check if it's a keyword.
// Return the corresponding token if it's a keyword
int result = stringToKeyword(str);
if (result != Token.EOF) {
if ((result == Token.LET || result == Token.YIELD) &&
parser.compilerEnv.getLanguageVersion()
< Context.VERSION_1_7)
{
// LET and YIELD are tokens only in 1.7 and later
+ string = result == Token.LET ? "let" : "yield";
result = Token.NAME;
}
if (result != Token.RESERVED) {
return result;
} else if (!parser.compilerEnv.
isReservedKeywordAsIdentifier())
{
return result;
} else {
// If implementation permits to use future reserved
// keywords in violation with the EcmaScript,
// treat it as name but issue warning
parser.addWarning("msg.reserved.keyword", str);
}
}
}
this.string = (String)allStrings.intern(str);
return Token.NAME;
}
// is it a number?
if (isDigit(c) || (c == '.' && isDigit(peekChar()))) {
stringBufferTop = 0;
int base = 10;
if (c == '0') {
c = getChar();
if (c == 'x' || c == 'X') {
base = 16;
c = getChar();
} else if (isDigit(c)) {
base = 8;
} else {
addToString('0');
}
}
if (base == 16) {
while (0 <= Kit.xDigitToInt(c, 0)) {
addToString(c);
c = getChar();
}
} else {
while ('0' <= c && c <= '9') {
/*
* We permit 08 and 09 as decimal numbers, which
* makes our behavior a superset of the ECMA
* numeric grammar. We might not always be so
* permissive, so we warn about it.
*/
if (base == 8 && c >= '8') {
parser.addWarning("msg.bad.octal.literal",
c == '8' ? "8" : "9");
base = 10;
}
addToString(c);
c = getChar();
}
}
boolean isInteger = true;
if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
isInteger = false;
if (c == '.') {
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
if (c == 'e' || c == 'E') {
addToString(c);
c = getChar();
if (c == '+' || c == '-') {
addToString(c);
c = getChar();
}
if (!isDigit(c)) {
parser.addError("msg.missing.exponent");
return Token.ERROR;
}
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
}
ungetChar(c);
String numString = getStringFromBuffer();
double dval;
if (base == 10 && !isInteger) {
try {
// Use Java conversion to number from string...
dval = Double.valueOf(numString).doubleValue();
}
catch (NumberFormatException ex) {
parser.addError("msg.caught.nfe");
return Token.ERROR;
}
} else {
dval = ScriptRuntime.stringToNumber(numString, 0, base);
}
this.number = dval;
return Token.NUMBER;
}
// is it a string?
if (c == '"' || c == '\'') {
// We attempt to accumulate a string the fast way, by
// building it directly out of the reader. But if there
// are any escaped characters in the string, we revert to
// building it out of a StringBuffer.
int quoteChar = c;
stringBufferTop = 0;
c = getChar();
strLoop: while (c != quoteChar) {
if (c == '\n' || c == EOF_CHAR) {
ungetChar(c);
parser.addError("msg.unterminated.string.lit");
return Token.ERROR;
}
if (c == '\\') {
// We've hit an escaped character
int escapeVal;
c = getChar();
switch (c) {
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
// \v a late addition to the ECMA spec,
// it is not in Java, so use 0xb
case 'v': c = 0xb; break;
case 'u':
// Get 4 hex digits; if the u escape is not
// followed by 4 hex digits, use 'u' + the
// literal character sequence that follows.
int escapeStart = stringBufferTop;
addToString('u');
escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
if (escapeVal < 0) {
continue strLoop;
}
addToString(c);
}
// prepare for replace of stored 'u' sequence
// by escape value
stringBufferTop = escapeStart;
c = escapeVal;
break;
case 'x':
// Get 2 hex digits, defaulting to 'x'+literal
// sequence, as above.
c = getChar();
escapeVal = Kit.xDigitToInt(c, 0);
if (escapeVal < 0) {
addToString('x');
continue strLoop;
} else {
int c1 = c;
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
if (escapeVal < 0) {
addToString('x');
addToString(c1);
continue strLoop;
} else {
// got 2 hex digits
c = escapeVal;
}
}
break;
case '\n':
// Remove line terminator after escape to follow
// SpiderMonkey and C/C++
c = getChar();
continue strLoop;
default:
if ('0' <= c && c < '8') {
int val = c - '0';
c = getChar();
if ('0' <= c && c < '8') {
val = 8 * val + c - '0';
c = getChar();
if ('0' <= c && c < '8' && val <= 037) {
// c is 3rd char of octal sequence only
// if the resulting val <= 0377
val = 8 * val + c - '0';
c = getChar();
}
}
ungetChar(c);
c = val;
}
}
}
addToString(c);
c = getChar();
}
String str = getStringFromBuffer();
this.string = (String)allStrings.intern(str);
return Token.STRING;
}
switch (c) {
case ';': return Token.SEMI;
case '[': return Token.LB;
case ']': return Token.RB;
case '{': return Token.LC;
case '}': return Token.RC;
case '(': return Token.LP;
case ')': return Token.RP;
case ',': return Token.COMMA;
case '?': return Token.HOOK;
case ':':
if (matchChar(':')) {
return Token.COLONCOLON;
} else {
return Token.COLON;
}
case '.':
if (matchChar('.')) {
return Token.DOTDOT;
} else if (matchChar('(')) {
return Token.DOTQUERY;
} else {
return Token.DOT;
}
case '|':
if (matchChar('|')) {
return Token.OR;
} else if (matchChar('=')) {
return Token.ASSIGN_BITOR;
} else {
return Token.BITOR;
}
case '^':
if (matchChar('=')) {
return Token.ASSIGN_BITXOR;
} else {
return Token.BITXOR;
}
case '&':
if (matchChar('&')) {
return Token.AND;
} else if (matchChar('=')) {
return Token.ASSIGN_BITAND;
} else {
return Token.BITAND;
}
case '=':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHEQ;
else
return Token.EQ;
} else {
return Token.ASSIGN;
}
case '!':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHNE;
else
return Token.NE;
} else {
return Token.NOT;
}
case '<':
/* NB:treat HTML begin-comment as comment-till-eol */
if (matchChar('!')) {
if (matchChar('-')) {
if (matchChar('-')) {
skipLine();
continue retry;
}
ungetCharIgnoreLineEnd('-');
}
ungetCharIgnoreLineEnd('!');
}
if (matchChar('<')) {
if (matchChar('=')) {
return Token.ASSIGN_LSH;
} else {
return Token.LSH;
}
} else {
if (matchChar('=')) {
return Token.LE;
} else {
return Token.LT;
}
}
case '>':
if (matchChar('>')) {
if (matchChar('>')) {
if (matchChar('=')) {
return Token.ASSIGN_URSH;
} else {
return Token.URSH;
}
} else {
if (matchChar('=')) {
return Token.ASSIGN_RSH;
} else {
return Token.RSH;
}
}
} else {
if (matchChar('=')) {
return Token.GE;
} else {
return Token.GT;
}
}
case '*':
if (matchChar('=')) {
return Token.ASSIGN_MUL;
} else {
return Token.MUL;
}
case '/':
// is it a // comment?
if (matchChar('/')) {
skipLine();
continue retry;
}
if (matchChar('*')) {
boolean lookForSlash = false;
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
parser.addError("msg.unterminated.comment");
return Token.ERROR;
} else if (c == '*') {
lookForSlash = true;
} else if (c == '/') {
if (lookForSlash) {
continue retry;
}
} else {
lookForSlash = false;
}
}
}
if (matchChar('=')) {
return Token.ASSIGN_DIV;
} else {
return Token.DIV;
}
case '%':
if (matchChar('=')) {
return Token.ASSIGN_MOD;
} else {
return Token.MOD;
}
case '~':
return Token.BITNOT;
case '+':
if (matchChar('=')) {
return Token.ASSIGN_ADD;
} else if (matchChar('+')) {
return Token.INC;
} else {
return Token.ADD;
}
case '-':
if (matchChar('=')) {
c = Token.ASSIGN_SUB;
} else if (matchChar('-')) {
if (!dirtyLine) {
// treat HTML end-comment after possible whitespace
// after line start as comment-utill-eol
if (matchChar('>')) {
skipLine();
continue retry;
}
}
c = Token.DEC;
} else {
c = Token.SUB;
}
dirtyLine = true;
return c;
default:
parser.addError("msg.illegal.character");
return Token.ERROR;
}
}
}
private static boolean isAlpha(int c)
{
// Use 'Z' < 'a'
if (c <= 'Z') {
return 'A' <= c;
} else {
return 'a' <= c && c <= 'z';
}
}
static boolean isDigit(int c)
{
return '0' <= c && c <= '9';
}
/* As defined in ECMA. jsscan.c uses C isspace() (which allows
* \v, I think.) note that code in getChar() implicitly accepts
* '\r' == \u000D as well.
*/
static boolean isJSSpace(int c)
{
if (c <= 127) {
return c == 0x20 || c == 0x9 || c == 0xC || c == 0xB;
} else {
return c == 0xA0
|| Character.getType((char)c) == Character.SPACE_SEPARATOR;
}
}
private static boolean isJSFormatChar(int c)
{
return c > 127 && Character.getType((char)c) == Character.FORMAT;
}
/**
* Parser calls the method when it gets / or /= in literal context.
*/
void readRegExp(int startToken)
throws IOException
{
stringBufferTop = 0;
if (startToken == Token.ASSIGN_DIV) {
// Miss-scanned /=
addToString('=');
} else {
if (startToken != Token.DIV) Kit.codeBug();
}
boolean inCharSet = false; // true if inside a '['..']' pair
int c;
while ((c = getChar()) != '/' || inCharSet) {
if (c == '\n' || c == EOF_CHAR) {
ungetChar(c);
throw parser.reportError("msg.unterminated.re.lit");
}
if (c == '\\') {
addToString(c);
c = getChar();
} else if (c == '[') {
inCharSet = true;
} else if (c == ']') {
inCharSet = false;
}
addToString(c);
}
int reEnd = stringBufferTop;
while (true) {
if (matchChar('g'))
addToString('g');
else if (matchChar('i'))
addToString('i');
else if (matchChar('m'))
addToString('m');
else
break;
}
if (isAlpha(peekChar())) {
throw parser.reportError("msg.invalid.re.flag");
}
this.string = new String(stringBuffer, 0, reEnd);
this.regExpFlags = new String(stringBuffer, reEnd,
stringBufferTop - reEnd);
}
boolean isXMLAttribute()
{
return xmlIsAttribute;
}
int getFirstXMLToken() throws IOException
{
xmlOpenTagsCount = 0;
xmlIsAttribute = false;
xmlIsTagContent = false;
ungetChar('<');
return getNextXMLToken();
}
int getNextXMLToken() throws IOException
{
stringBufferTop = 0; // remember the XML
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
if (xmlIsTagContent) {
switch (c) {
case '>':
addToString(c);
xmlIsTagContent = false;
xmlIsAttribute = false;
break;
case '/':
addToString(c);
if (peekChar() == '>') {
c = getChar();
addToString(c);
xmlIsTagContent = false;
xmlOpenTagsCount--;
}
break;
case '{':
ungetChar(c);
this.string = getStringFromBuffer();
return Token.XML;
case '\'':
case '"':
addToString(c);
if (!readQuotedString(c)) return Token.ERROR;
break;
case '=':
addToString(c);
xmlIsAttribute = true;
break;
case ' ':
case '\t':
case '\r':
case '\n':
addToString(c);
break;
default:
addToString(c);
xmlIsAttribute = false;
break;
}
if (!xmlIsTagContent && xmlOpenTagsCount == 0) {
this.string = getStringFromBuffer();
return Token.XMLEND;
}
} else {
switch (c) {
case '<':
addToString(c);
c = peekChar();
switch (c) {
case '!':
c = getChar(); // Skip !
addToString(c);
c = peekChar();
switch (c) {
case '-':
c = getChar(); // Skip -
addToString(c);
c = getChar();
if (c == '-') {
addToString(c);
if(!readXmlComment()) return Token.ERROR;
} else {
// throw away the string in progress
stringBufferTop = 0;
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
break;
case '[':
c = getChar(); // Skip [
addToString(c);
if (getChar() == 'C' &&
getChar() == 'D' &&
getChar() == 'A' &&
getChar() == 'T' &&
getChar() == 'A' &&
getChar() == '[')
{
addToString('C');
addToString('D');
addToString('A');
addToString('T');
addToString('A');
addToString('[');
if (!readCDATA()) return Token.ERROR;
} else {
// throw away the string in progress
stringBufferTop = 0;
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
break;
default:
if(!readEntity()) return Token.ERROR;
break;
}
break;
case '?':
c = getChar(); // Skip ?
addToString(c);
if (!readPI()) return Token.ERROR;
break;
case '/':
// End tag
c = getChar(); // Skip /
addToString(c);
if (xmlOpenTagsCount == 0) {
// throw away the string in progress
stringBufferTop = 0;
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
xmlIsTagContent = true;
xmlOpenTagsCount--;
break;
default:
// Start tag
xmlIsTagContent = true;
xmlOpenTagsCount++;
break;
}
break;
case '{':
ungetChar(c);
this.string = getStringFromBuffer();
return Token.XML;
default:
addToString(c);
break;
}
}
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return Token.ERROR;
}
/**
*
*/
private boolean readQuotedString(int quote) throws IOException
{
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
addToString(c);
if (c == quote) return true;
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readXmlComment() throws IOException
{
for (int c = getChar(); c != EOF_CHAR;) {
addToString(c);
if (c == '-' && peekChar() == '-') {
c = getChar();
addToString(c);
if (peekChar() == '>') {
c = getChar(); // Skip >
addToString(c);
return true;
} else {
continue;
}
}
c = getChar();
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readCDATA() throws IOException
{
for (int c = getChar(); c != EOF_CHAR;) {
addToString(c);
if (c == ']' && peekChar() == ']') {
c = getChar();
addToString(c);
if (peekChar() == '>') {
c = getChar(); // Skip >
addToString(c);
return true;
} else {
continue;
}
}
c = getChar();
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readEntity() throws IOException
{
int declTags = 1;
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
addToString(c);
switch (c) {
case '<':
declTags++;
break;
case '>':
declTags--;
if (declTags == 0) return true;
break;
}
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
/**
*
*/
private boolean readPI() throws IOException
{
for (int c = getChar(); c != EOF_CHAR; c = getChar()) {
addToString(c);
if (c == '?' && peekChar() == '>') {
c = getChar(); // Skip >
addToString(c);
return true;
}
}
stringBufferTop = 0; // throw away the string in progress
this.string = null;
parser.addError("msg.XML.bad.form");
return false;
}
private String getStringFromBuffer()
{
return new String(stringBuffer, 0, stringBufferTop);
}
private void addToString(int c)
{
int N = stringBufferTop;
if (N == stringBuffer.length) {
char[] tmp = new char[stringBuffer.length * 2];
System.arraycopy(stringBuffer, 0, tmp, 0, N);
stringBuffer = tmp;
}
stringBuffer[N] = (char)c;
stringBufferTop = N + 1;
}
private void ungetChar(int c)
{
// can not unread past across line boundary
if (ungetCursor != 0 && ungetBuffer[ungetCursor - 1] == '\n')
Kit.codeBug();
ungetBuffer[ungetCursor++] = c;
}
private boolean matchChar(int test) throws IOException
{
int c = getCharIgnoreLineEnd();
if (c == test) {
return true;
} else {
ungetCharIgnoreLineEnd(c);
return false;
}
}
private int peekChar() throws IOException
{
int c = getChar();
ungetChar(c);
return c;
}
private int getChar() throws IOException
{
if (ungetCursor != 0) {
return ungetBuffer[--ungetCursor];
}
for(;;) {
int c;
if (sourceString != null) {
if (sourceCursor == sourceEnd) {
hitEOF = true;
return EOF_CHAR;
}
c = sourceString.charAt(sourceCursor++);
} else {
if (sourceCursor == sourceEnd) {
if (!fillSourceBuffer()) {
hitEOF = true;
return EOF_CHAR;
}
}
c = sourceBuffer[sourceCursor++];
}
if (lineEndChar >= 0) {
if (lineEndChar == '\r' && c == '\n') {
lineEndChar = '\n';
continue;
}
lineEndChar = -1;
lineStart = sourceCursor - 1;
lineno++;
}
if (c <= 127) {
if (c == '\n' || c == '\r') {
lineEndChar = c;
c = '\n';
}
} else {
if (isJSFormatChar(c)) {
continue;
}
if (ScriptRuntime.isJSLineTerminator(c)) {
lineEndChar = c;
c = '\n';
}
}
return c;
}
}
private int getCharIgnoreLineEnd() throws IOException
{
if (ungetCursor != 0) {
return ungetBuffer[--ungetCursor];
}
for(;;) {
int c;
if (sourceString != null) {
if (sourceCursor == sourceEnd) {
hitEOF = true;
return EOF_CHAR;
}
c = sourceString.charAt(sourceCursor++);
} else {
if (sourceCursor == sourceEnd) {
if (!fillSourceBuffer()) {
hitEOF = true;
return EOF_CHAR;
}
}
c = sourceBuffer[sourceCursor++];
}
if (c <= 127) {
if (c == '\n' || c == '\r') {
lineEndChar = c;
c = '\n';
}
} else {
if (isJSFormatChar(c)) {
continue;
}
if (ScriptRuntime.isJSLineTerminator(c)) {
lineEndChar = c;
c = '\n';
}
}
return c;
}
}
private void ungetCharIgnoreLineEnd(int c)
{
ungetBuffer[ungetCursor++] = c;
}
private void skipLine() throws IOException
{
// skip to end of line
int c;
while ((c = getChar()) != EOF_CHAR && c != '\n') { }
ungetChar(c);
}
final int getOffset()
{
int n = sourceCursor - lineStart;
if (lineEndChar >= 0) { --n; }
return n;
}
final String getLine()
{
if (sourceString != null) {
// String case
int lineEnd = sourceCursor;
if (lineEndChar >= 0) {
--lineEnd;
} else {
for (; lineEnd != sourceEnd; ++lineEnd) {
int c = sourceString.charAt(lineEnd);
if (ScriptRuntime.isJSLineTerminator(c)) {
break;
}
}
}
return sourceString.substring(lineStart, lineEnd);
} else {
// Reader case
int lineLength = sourceCursor - lineStart;
if (lineEndChar >= 0) {
--lineLength;
} else {
// Read until the end of line
for (;; ++lineLength) {
int i = lineStart + lineLength;
if (i == sourceEnd) {
try {
if (!fillSourceBuffer()) { break; }
} catch (IOException ioe) {
// ignore it, we're already displaying an error...
break;
}
// i recalculuation as fillSourceBuffer can move saved
// line buffer and change lineStart
i = lineStart + lineLength;
}
int c = sourceBuffer[i];
if (ScriptRuntime.isJSLineTerminator(c)) {
break;
}
}
}
return new String(sourceBuffer, lineStart, lineLength);
}
}
private boolean fillSourceBuffer() throws IOException
{
if (sourceString != null) Kit.codeBug();
if (sourceEnd == sourceBuffer.length) {
if (lineStart != 0) {
System.arraycopy(sourceBuffer, lineStart, sourceBuffer, 0,
sourceEnd - lineStart);
sourceEnd -= lineStart;
sourceCursor -= lineStart;
lineStart = 0;
} else {
char[] tmp = new char[sourceBuffer.length * 2];
System.arraycopy(sourceBuffer, 0, tmp, 0, sourceEnd);
sourceBuffer = tmp;
}
}
int n = sourceReader.read(sourceBuffer, sourceEnd,
sourceBuffer.length - sourceEnd);
if (n < 0) {
return false;
}
sourceEnd += n;
return true;
}
// stuff other than whitespace since start of line
private boolean dirtyLine;
String regExpFlags;
// Set this to an initial non-null value so that the Parser has
// something to retrieve even if an error has occurred and no
// string is found. Fosters one class of error, but saves lots of
// code.
private String string = "";
private double number;
private char[] stringBuffer = new char[128];
private int stringBufferTop;
private ObjToIntMap allStrings = new ObjToIntMap(50);
// Room to backtrace from to < on failed match of the last - in <!--
private final int[] ungetBuffer = new int[3];
private int ungetCursor;
private boolean hitEOF = false;
private int lineStart = 0;
private int lineno;
private int lineEndChar = -1;
private String sourceString;
private Reader sourceReader;
private char[] sourceBuffer;
private int sourceEnd;
private int sourceCursor;
// for xml tokenizer
private boolean xmlIsAttribute;
private boolean xmlIsTagContent;
private int xmlOpenTagsCount;
private Parser parser;
}
| true | true | final int getToken() throws IOException
{
int c;
retry:
for (;;) {
// Eat whitespace, possibly sensitive to newlines.
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
return Token.EOF;
} else if (c == '\n') {
dirtyLine = false;
return Token.EOL;
} else if (!isJSSpace(c)) {
if (c != '-') {
dirtyLine = true;
}
break;
}
}
if (c == '@') return Token.XMLATTR;
// identifier/keyword/instanceof?
// watch out for starting with a <backslash>
boolean identifierStart;
boolean isUnicodeEscapeStart = false;
if (c == '\\') {
c = getChar();
if (c == 'u') {
identifierStart = true;
isUnicodeEscapeStart = true;
stringBufferTop = 0;
} else {
identifierStart = false;
ungetChar(c);
c = '\\';
}
} else {
identifierStart = Character.isJavaIdentifierStart((char)c);
if (identifierStart) {
stringBufferTop = 0;
addToString(c);
}
}
if (identifierStart) {
boolean containsEscape = isUnicodeEscapeStart;
for (;;) {
if (isUnicodeEscapeStart) {
// strictly speaking we should probably push-back
// all the bad characters if the <backslash>uXXXX
// sequence is malformed. But since there isn't a
// correct context(is there?) for a bad Unicode
// escape sequence in an identifier, we can report
// an error here.
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
// Next check takes care about c < 0 and bad escape
if (escapeVal < 0) { break; }
}
if (escapeVal < 0) {
parser.addError("msg.invalid.escape");
return Token.ERROR;
}
addToString(escapeVal);
isUnicodeEscapeStart = false;
} else {
c = getChar();
if (c == '\\') {
c = getChar();
if (c == 'u') {
isUnicodeEscapeStart = true;
containsEscape = true;
} else {
parser.addError("msg.illegal.character");
return Token.ERROR;
}
} else {
if (c == EOF_CHAR
|| !Character.isJavaIdentifierPart((char)c))
{
break;
}
addToString(c);
}
}
}
ungetChar(c);
String str = getStringFromBuffer();
if (!containsEscape) {
// OPT we shouldn't have to make a string (object!) to
// check if it's a keyword.
// Return the corresponding token if it's a keyword
int result = stringToKeyword(str);
if (result != Token.EOF) {
if ((result == Token.LET || result == Token.YIELD) &&
parser.compilerEnv.getLanguageVersion()
< Context.VERSION_1_7)
{
// LET and YIELD are tokens only in 1.7 and later
result = Token.NAME;
}
if (result != Token.RESERVED) {
return result;
} else if (!parser.compilerEnv.
isReservedKeywordAsIdentifier())
{
return result;
} else {
// If implementation permits to use future reserved
// keywords in violation with the EcmaScript,
// treat it as name but issue warning
parser.addWarning("msg.reserved.keyword", str);
}
}
}
this.string = (String)allStrings.intern(str);
return Token.NAME;
}
// is it a number?
if (isDigit(c) || (c == '.' && isDigit(peekChar()))) {
stringBufferTop = 0;
int base = 10;
if (c == '0') {
c = getChar();
if (c == 'x' || c == 'X') {
base = 16;
c = getChar();
} else if (isDigit(c)) {
base = 8;
} else {
addToString('0');
}
}
if (base == 16) {
while (0 <= Kit.xDigitToInt(c, 0)) {
addToString(c);
c = getChar();
}
} else {
while ('0' <= c && c <= '9') {
/*
* We permit 08 and 09 as decimal numbers, which
* makes our behavior a superset of the ECMA
* numeric grammar. We might not always be so
* permissive, so we warn about it.
*/
if (base == 8 && c >= '8') {
parser.addWarning("msg.bad.octal.literal",
c == '8' ? "8" : "9");
base = 10;
}
addToString(c);
c = getChar();
}
}
boolean isInteger = true;
if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
isInteger = false;
if (c == '.') {
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
if (c == 'e' || c == 'E') {
addToString(c);
c = getChar();
if (c == '+' || c == '-') {
addToString(c);
c = getChar();
}
if (!isDigit(c)) {
parser.addError("msg.missing.exponent");
return Token.ERROR;
}
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
}
ungetChar(c);
String numString = getStringFromBuffer();
double dval;
if (base == 10 && !isInteger) {
try {
// Use Java conversion to number from string...
dval = Double.valueOf(numString).doubleValue();
}
catch (NumberFormatException ex) {
parser.addError("msg.caught.nfe");
return Token.ERROR;
}
} else {
dval = ScriptRuntime.stringToNumber(numString, 0, base);
}
this.number = dval;
return Token.NUMBER;
}
// is it a string?
if (c == '"' || c == '\'') {
// We attempt to accumulate a string the fast way, by
// building it directly out of the reader. But if there
// are any escaped characters in the string, we revert to
// building it out of a StringBuffer.
int quoteChar = c;
stringBufferTop = 0;
c = getChar();
strLoop: while (c != quoteChar) {
if (c == '\n' || c == EOF_CHAR) {
ungetChar(c);
parser.addError("msg.unterminated.string.lit");
return Token.ERROR;
}
if (c == '\\') {
// We've hit an escaped character
int escapeVal;
c = getChar();
switch (c) {
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
// \v a late addition to the ECMA spec,
// it is not in Java, so use 0xb
case 'v': c = 0xb; break;
case 'u':
// Get 4 hex digits; if the u escape is not
// followed by 4 hex digits, use 'u' + the
// literal character sequence that follows.
int escapeStart = stringBufferTop;
addToString('u');
escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
if (escapeVal < 0) {
continue strLoop;
}
addToString(c);
}
// prepare for replace of stored 'u' sequence
// by escape value
stringBufferTop = escapeStart;
c = escapeVal;
break;
case 'x':
// Get 2 hex digits, defaulting to 'x'+literal
// sequence, as above.
c = getChar();
escapeVal = Kit.xDigitToInt(c, 0);
if (escapeVal < 0) {
addToString('x');
continue strLoop;
} else {
int c1 = c;
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
if (escapeVal < 0) {
addToString('x');
addToString(c1);
continue strLoop;
} else {
// got 2 hex digits
c = escapeVal;
}
}
break;
case '\n':
// Remove line terminator after escape to follow
// SpiderMonkey and C/C++
c = getChar();
continue strLoop;
default:
if ('0' <= c && c < '8') {
int val = c - '0';
c = getChar();
if ('0' <= c && c < '8') {
val = 8 * val + c - '0';
c = getChar();
if ('0' <= c && c < '8' && val <= 037) {
// c is 3rd char of octal sequence only
// if the resulting val <= 0377
val = 8 * val + c - '0';
c = getChar();
}
}
ungetChar(c);
c = val;
}
}
}
addToString(c);
c = getChar();
}
String str = getStringFromBuffer();
this.string = (String)allStrings.intern(str);
return Token.STRING;
}
switch (c) {
case ';': return Token.SEMI;
case '[': return Token.LB;
case ']': return Token.RB;
case '{': return Token.LC;
case '}': return Token.RC;
case '(': return Token.LP;
case ')': return Token.RP;
case ',': return Token.COMMA;
case '?': return Token.HOOK;
case ':':
if (matchChar(':')) {
return Token.COLONCOLON;
} else {
return Token.COLON;
}
case '.':
if (matchChar('.')) {
return Token.DOTDOT;
} else if (matchChar('(')) {
return Token.DOTQUERY;
} else {
return Token.DOT;
}
case '|':
if (matchChar('|')) {
return Token.OR;
} else if (matchChar('=')) {
return Token.ASSIGN_BITOR;
} else {
return Token.BITOR;
}
case '^':
if (matchChar('=')) {
return Token.ASSIGN_BITXOR;
} else {
return Token.BITXOR;
}
case '&':
if (matchChar('&')) {
return Token.AND;
} else if (matchChar('=')) {
return Token.ASSIGN_BITAND;
} else {
return Token.BITAND;
}
case '=':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHEQ;
else
return Token.EQ;
} else {
return Token.ASSIGN;
}
case '!':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHNE;
else
return Token.NE;
} else {
return Token.NOT;
}
case '<':
/* NB:treat HTML begin-comment as comment-till-eol */
if (matchChar('!')) {
if (matchChar('-')) {
if (matchChar('-')) {
skipLine();
continue retry;
}
ungetCharIgnoreLineEnd('-');
}
ungetCharIgnoreLineEnd('!');
}
if (matchChar('<')) {
if (matchChar('=')) {
return Token.ASSIGN_LSH;
} else {
return Token.LSH;
}
} else {
if (matchChar('=')) {
return Token.LE;
} else {
return Token.LT;
}
}
case '>':
if (matchChar('>')) {
if (matchChar('>')) {
if (matchChar('=')) {
return Token.ASSIGN_URSH;
} else {
return Token.URSH;
}
} else {
if (matchChar('=')) {
return Token.ASSIGN_RSH;
} else {
return Token.RSH;
}
}
} else {
if (matchChar('=')) {
return Token.GE;
} else {
return Token.GT;
}
}
case '*':
if (matchChar('=')) {
return Token.ASSIGN_MUL;
} else {
return Token.MUL;
}
case '/':
// is it a // comment?
if (matchChar('/')) {
skipLine();
continue retry;
}
if (matchChar('*')) {
boolean lookForSlash = false;
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
parser.addError("msg.unterminated.comment");
return Token.ERROR;
} else if (c == '*') {
lookForSlash = true;
} else if (c == '/') {
if (lookForSlash) {
continue retry;
}
} else {
lookForSlash = false;
}
}
}
if (matchChar('=')) {
return Token.ASSIGN_DIV;
} else {
return Token.DIV;
}
case '%':
if (matchChar('=')) {
return Token.ASSIGN_MOD;
} else {
return Token.MOD;
}
case '~':
return Token.BITNOT;
case '+':
if (matchChar('=')) {
return Token.ASSIGN_ADD;
} else if (matchChar('+')) {
return Token.INC;
} else {
return Token.ADD;
}
case '-':
if (matchChar('=')) {
c = Token.ASSIGN_SUB;
} else if (matchChar('-')) {
if (!dirtyLine) {
// treat HTML end-comment after possible whitespace
// after line start as comment-utill-eol
if (matchChar('>')) {
skipLine();
continue retry;
}
}
c = Token.DEC;
} else {
c = Token.SUB;
}
dirtyLine = true;
return c;
default:
parser.addError("msg.illegal.character");
return Token.ERROR;
}
}
}
| final int getToken() throws IOException
{
int c;
retry:
for (;;) {
// Eat whitespace, possibly sensitive to newlines.
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
return Token.EOF;
} else if (c == '\n') {
dirtyLine = false;
return Token.EOL;
} else if (!isJSSpace(c)) {
if (c != '-') {
dirtyLine = true;
}
break;
}
}
if (c == '@') return Token.XMLATTR;
// identifier/keyword/instanceof?
// watch out for starting with a <backslash>
boolean identifierStart;
boolean isUnicodeEscapeStart = false;
if (c == '\\') {
c = getChar();
if (c == 'u') {
identifierStart = true;
isUnicodeEscapeStart = true;
stringBufferTop = 0;
} else {
identifierStart = false;
ungetChar(c);
c = '\\';
}
} else {
identifierStart = Character.isJavaIdentifierStart((char)c);
if (identifierStart) {
stringBufferTop = 0;
addToString(c);
}
}
if (identifierStart) {
boolean containsEscape = isUnicodeEscapeStart;
for (;;) {
if (isUnicodeEscapeStart) {
// strictly speaking we should probably push-back
// all the bad characters if the <backslash>uXXXX
// sequence is malformed. But since there isn't a
// correct context(is there?) for a bad Unicode
// escape sequence in an identifier, we can report
// an error here.
int escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
// Next check takes care about c < 0 and bad escape
if (escapeVal < 0) { break; }
}
if (escapeVal < 0) {
parser.addError("msg.invalid.escape");
return Token.ERROR;
}
addToString(escapeVal);
isUnicodeEscapeStart = false;
} else {
c = getChar();
if (c == '\\') {
c = getChar();
if (c == 'u') {
isUnicodeEscapeStart = true;
containsEscape = true;
} else {
parser.addError("msg.illegal.character");
return Token.ERROR;
}
} else {
if (c == EOF_CHAR
|| !Character.isJavaIdentifierPart((char)c))
{
break;
}
addToString(c);
}
}
}
ungetChar(c);
String str = getStringFromBuffer();
if (!containsEscape) {
// OPT we shouldn't have to make a string (object!) to
// check if it's a keyword.
// Return the corresponding token if it's a keyword
int result = stringToKeyword(str);
if (result != Token.EOF) {
if ((result == Token.LET || result == Token.YIELD) &&
parser.compilerEnv.getLanguageVersion()
< Context.VERSION_1_7)
{
// LET and YIELD are tokens only in 1.7 and later
string = result == Token.LET ? "let" : "yield";
result = Token.NAME;
}
if (result != Token.RESERVED) {
return result;
} else if (!parser.compilerEnv.
isReservedKeywordAsIdentifier())
{
return result;
} else {
// If implementation permits to use future reserved
// keywords in violation with the EcmaScript,
// treat it as name but issue warning
parser.addWarning("msg.reserved.keyword", str);
}
}
}
this.string = (String)allStrings.intern(str);
return Token.NAME;
}
// is it a number?
if (isDigit(c) || (c == '.' && isDigit(peekChar()))) {
stringBufferTop = 0;
int base = 10;
if (c == '0') {
c = getChar();
if (c == 'x' || c == 'X') {
base = 16;
c = getChar();
} else if (isDigit(c)) {
base = 8;
} else {
addToString('0');
}
}
if (base == 16) {
while (0 <= Kit.xDigitToInt(c, 0)) {
addToString(c);
c = getChar();
}
} else {
while ('0' <= c && c <= '9') {
/*
* We permit 08 and 09 as decimal numbers, which
* makes our behavior a superset of the ECMA
* numeric grammar. We might not always be so
* permissive, so we warn about it.
*/
if (base == 8 && c >= '8') {
parser.addWarning("msg.bad.octal.literal",
c == '8' ? "8" : "9");
base = 10;
}
addToString(c);
c = getChar();
}
}
boolean isInteger = true;
if (base == 10 && (c == '.' || c == 'e' || c == 'E')) {
isInteger = false;
if (c == '.') {
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
if (c == 'e' || c == 'E') {
addToString(c);
c = getChar();
if (c == '+' || c == '-') {
addToString(c);
c = getChar();
}
if (!isDigit(c)) {
parser.addError("msg.missing.exponent");
return Token.ERROR;
}
do {
addToString(c);
c = getChar();
} while (isDigit(c));
}
}
ungetChar(c);
String numString = getStringFromBuffer();
double dval;
if (base == 10 && !isInteger) {
try {
// Use Java conversion to number from string...
dval = Double.valueOf(numString).doubleValue();
}
catch (NumberFormatException ex) {
parser.addError("msg.caught.nfe");
return Token.ERROR;
}
} else {
dval = ScriptRuntime.stringToNumber(numString, 0, base);
}
this.number = dval;
return Token.NUMBER;
}
// is it a string?
if (c == '"' || c == '\'') {
// We attempt to accumulate a string the fast way, by
// building it directly out of the reader. But if there
// are any escaped characters in the string, we revert to
// building it out of a StringBuffer.
int quoteChar = c;
stringBufferTop = 0;
c = getChar();
strLoop: while (c != quoteChar) {
if (c == '\n' || c == EOF_CHAR) {
ungetChar(c);
parser.addError("msg.unterminated.string.lit");
return Token.ERROR;
}
if (c == '\\') {
// We've hit an escaped character
int escapeVal;
c = getChar();
switch (c) {
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
// \v a late addition to the ECMA spec,
// it is not in Java, so use 0xb
case 'v': c = 0xb; break;
case 'u':
// Get 4 hex digits; if the u escape is not
// followed by 4 hex digits, use 'u' + the
// literal character sequence that follows.
int escapeStart = stringBufferTop;
addToString('u');
escapeVal = 0;
for (int i = 0; i != 4; ++i) {
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
if (escapeVal < 0) {
continue strLoop;
}
addToString(c);
}
// prepare for replace of stored 'u' sequence
// by escape value
stringBufferTop = escapeStart;
c = escapeVal;
break;
case 'x':
// Get 2 hex digits, defaulting to 'x'+literal
// sequence, as above.
c = getChar();
escapeVal = Kit.xDigitToInt(c, 0);
if (escapeVal < 0) {
addToString('x');
continue strLoop;
} else {
int c1 = c;
c = getChar();
escapeVal = Kit.xDigitToInt(c, escapeVal);
if (escapeVal < 0) {
addToString('x');
addToString(c1);
continue strLoop;
} else {
// got 2 hex digits
c = escapeVal;
}
}
break;
case '\n':
// Remove line terminator after escape to follow
// SpiderMonkey and C/C++
c = getChar();
continue strLoop;
default:
if ('0' <= c && c < '8') {
int val = c - '0';
c = getChar();
if ('0' <= c && c < '8') {
val = 8 * val + c - '0';
c = getChar();
if ('0' <= c && c < '8' && val <= 037) {
// c is 3rd char of octal sequence only
// if the resulting val <= 0377
val = 8 * val + c - '0';
c = getChar();
}
}
ungetChar(c);
c = val;
}
}
}
addToString(c);
c = getChar();
}
String str = getStringFromBuffer();
this.string = (String)allStrings.intern(str);
return Token.STRING;
}
switch (c) {
case ';': return Token.SEMI;
case '[': return Token.LB;
case ']': return Token.RB;
case '{': return Token.LC;
case '}': return Token.RC;
case '(': return Token.LP;
case ')': return Token.RP;
case ',': return Token.COMMA;
case '?': return Token.HOOK;
case ':':
if (matchChar(':')) {
return Token.COLONCOLON;
} else {
return Token.COLON;
}
case '.':
if (matchChar('.')) {
return Token.DOTDOT;
} else if (matchChar('(')) {
return Token.DOTQUERY;
} else {
return Token.DOT;
}
case '|':
if (matchChar('|')) {
return Token.OR;
} else if (matchChar('=')) {
return Token.ASSIGN_BITOR;
} else {
return Token.BITOR;
}
case '^':
if (matchChar('=')) {
return Token.ASSIGN_BITXOR;
} else {
return Token.BITXOR;
}
case '&':
if (matchChar('&')) {
return Token.AND;
} else if (matchChar('=')) {
return Token.ASSIGN_BITAND;
} else {
return Token.BITAND;
}
case '=':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHEQ;
else
return Token.EQ;
} else {
return Token.ASSIGN;
}
case '!':
if (matchChar('=')) {
if (matchChar('='))
return Token.SHNE;
else
return Token.NE;
} else {
return Token.NOT;
}
case '<':
/* NB:treat HTML begin-comment as comment-till-eol */
if (matchChar('!')) {
if (matchChar('-')) {
if (matchChar('-')) {
skipLine();
continue retry;
}
ungetCharIgnoreLineEnd('-');
}
ungetCharIgnoreLineEnd('!');
}
if (matchChar('<')) {
if (matchChar('=')) {
return Token.ASSIGN_LSH;
} else {
return Token.LSH;
}
} else {
if (matchChar('=')) {
return Token.LE;
} else {
return Token.LT;
}
}
case '>':
if (matchChar('>')) {
if (matchChar('>')) {
if (matchChar('=')) {
return Token.ASSIGN_URSH;
} else {
return Token.URSH;
}
} else {
if (matchChar('=')) {
return Token.ASSIGN_RSH;
} else {
return Token.RSH;
}
}
} else {
if (matchChar('=')) {
return Token.GE;
} else {
return Token.GT;
}
}
case '*':
if (matchChar('=')) {
return Token.ASSIGN_MUL;
} else {
return Token.MUL;
}
case '/':
// is it a // comment?
if (matchChar('/')) {
skipLine();
continue retry;
}
if (matchChar('*')) {
boolean lookForSlash = false;
for (;;) {
c = getChar();
if (c == EOF_CHAR) {
parser.addError("msg.unterminated.comment");
return Token.ERROR;
} else if (c == '*') {
lookForSlash = true;
} else if (c == '/') {
if (lookForSlash) {
continue retry;
}
} else {
lookForSlash = false;
}
}
}
if (matchChar('=')) {
return Token.ASSIGN_DIV;
} else {
return Token.DIV;
}
case '%':
if (matchChar('=')) {
return Token.ASSIGN_MOD;
} else {
return Token.MOD;
}
case '~':
return Token.BITNOT;
case '+':
if (matchChar('=')) {
return Token.ASSIGN_ADD;
} else if (matchChar('+')) {
return Token.INC;
} else {
return Token.ADD;
}
case '-':
if (matchChar('=')) {
c = Token.ASSIGN_SUB;
} else if (matchChar('-')) {
if (!dirtyLine) {
// treat HTML end-comment after possible whitespace
// after line start as comment-utill-eol
if (matchChar('>')) {
skipLine();
continue retry;
}
}
c = Token.DEC;
} else {
c = Token.SUB;
}
dirtyLine = true;
return c;
default:
parser.addError("msg.illegal.character");
return Token.ERROR;
}
}
}
|
diff --git a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindAllPersistentMethod.java b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindAllPersistentMethod.java
index 5dd5ec6d4..4db387e9d 100644
--- a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindAllPersistentMethod.java
+++ b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/FindAllPersistentMethod.java
@@ -1,260 +1,260 @@
/*
* 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.orm.hibernate.metaclass;
import groovy.lang.GString;
import groovy.lang.MissingMethodException;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.orm.hibernate.exceptions.GrailsQueryException;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil;
import org.hibernate.*;
import org.hibernate.criterion.Example;
import org.springframework.orm.hibernate3.HibernateCallback;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* <p>
* The "findAll" persistent static method allows searching for instances using
* either an example instance or an HQL query. Max results and offset parameters could
* be specified. A GrailsQueryException is thrown if the query is not a valid query
* for the domain class.
* <p>
* Syntax:
* DomainClass.findAll( query, params?)
* DomainClass.findAll( query, params?, max)
* DomainClass.findAll( query, params?, max, offset)
* DomainClass.findAll( query, params?, [max:10, offset:5])
*
* <p>
* Examples in Groovy: <code>
* // retrieves all accounts
* def a = Account.findAll()
*
* // retrieve all accounts ordered by account number
* def a = Account.findAll("from Account as a order by a.number asc" )
*
* // retrieve first 10 accounts ordered by account number
* def a = Account.findAll("from Account as a order by a.number asc",10 )
*
* // retrieve first 10 accounts ordered by account number started from 5th account
* def a = Account.findAll("from Account as a order by a.number asc",10,5 )
*
* // retrieve first 10 accounts ordered by account number started from 5th account
* def a = Account.findAll("from Account as a order by a.number asc",[max:10,offset:5] )
*
* // with query parameters
* def a = Account.find("from Account as a where a.number = ? and a.branch = ?", [38479, "London"])
*
* // with query named parameters
* def a = Account.find("from Account as a where a.number = :number and a.branch = :branch", [number:38479, branch:"London"])
*
* // with query named parameters and max results and offset
* def a = Account.find("from Account as a where a.number = :number and a.branch = :branch", [number:38479, branch:"London"], 10, 5 )
*
* // with query named parameters and max results and offset map
* def a = Account.find("from Account as a where a.number = :number and a.branch = :branch", [number:38479, branch:"London"], [max:10, offset:5] )
*
* // query by example
* def a = new Account()
* a.number = 495749357
* def a = Account.find(a)
*
* </code>
*
* @author Graeme Rocher
* @author Steven Devijver
* @author Sergey Nebolsin
*
* @since 0.1
*
* Created: Aug 8, 2005
*
*/
public class FindAllPersistentMethod
extends AbstractStaticPersistentMethod {
public FindAllPersistentMethod(SessionFactory sessionFactory,
ClassLoader classLoader) {
super(sessionFactory, classLoader, Pattern.compile("^findAll$"));
}
protected Object doInvokeInternal(final Class clazz, String methodName, final Object[] arguments) {
if (arguments.length == 0)
return getHibernateTemplate().loadAll(clazz);
final Object arg = arguments[0] instanceof GString ? arguments[0].toString() : arguments[0];
// if the arg is an instance of the class find by example
if (arg instanceof String) {
final String query = ((String) arg).trim();
final String shortName = GrailsClassUtils.getShortName(clazz);
if (!query.matches("(?i)from(?-i)\\s+[" + clazz.getName() + "|" + shortName
+ "].*")) {
throw new GrailsQueryException("Invalid query [" + query + "] for domain class [" + clazz + "]");
}
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.createQuery(query);
Object[] queryArgs = null;
Map queryNamedArgs = null;
int max = retrieveMaxValue(arguments);
int offset = retrieveOffsetValue(arguments);
if (arguments.length > 1) {
if (arguments[1] instanceof Collection) {
queryArgs = GrailsClassUtils.collectionToObjectArray((Collection) arguments[1]);
} else if (arguments[1].getClass().isArray()) {
queryArgs = (Object[]) arguments[1];
} else if (arguments[1] instanceof Map) {
queryNamedArgs = (Map) arguments[1];
}
}
if (queryArgs != null) {
for (int i = 0; i < queryArgs.length; i++) {
if (queryArgs[i] instanceof GString) {
q.setParameter(i, queryArgs[i].toString());
} else {
q.setParameter(i, queryArgs[i]);
}
}
}
if (queryNamedArgs != null) {
for (Iterator it = queryNamedArgs.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String))
throw new GrailsQueryException("Named parameter's name must be String: "
+ queryNamedArgs.toString());
String stringKey = (String) entry.getKey();
// Won't try to bind these parameters since they are processed separately
if( GrailsHibernateUtil.ARGUMENT_MAX.equals(stringKey) || GrailsHibernateUtil.ARGUMENT_OFFSET.equals(stringKey) ) continue;
Object value = entry.getValue();
if(value == null) {
q.setParameter(stringKey, null);
}
else if (value instanceof GString) {
q.setParameter(stringKey, value.toString());
} else if (List.class.isAssignableFrom(value.getClass())) {
q.setParameterList(stringKey, (List) value);
} else if (value.getClass().isArray()) {
q.setParameterList(stringKey, (Object[]) value);
} else {
q.setParameter(stringKey, value);
}
}
}
if (max > 0) {
q.setMaxResults(max);
}
if (offset > 0) {
q.setFirstResult(offset);
}
return q.list();
}
private int retrieveMaxValue(Object[] arguments) {
int result = -1;
if( arguments.length > 1) {
result = retrieveInt(arguments[1], GrailsHibernateUtil.ARGUMENT_MAX);
if( arguments.length > 2 && result == -1 ) {
result = retrieveInt(arguments[2], GrailsHibernateUtil.ARGUMENT_MAX);
}
}
return result;
}
private int retrieveOffsetValue(Object[] arguments) {
int result = -1;
if( arguments.length > 1) {
if( isMapWithValue(arguments[1], GrailsHibernateUtil.ARGUMENT_OFFSET) ) {
result = ((Number)((Map)arguments[1]).get(GrailsHibernateUtil.ARGUMENT_OFFSET)).intValue();
}
if( arguments.length > 2 && result == -1 ) {
if( isMapWithValue(arguments[2], GrailsHibernateUtil.ARGUMENT_OFFSET) ) {
result = ((Number)((Map)arguments[2]).get(GrailsHibernateUtil.ARGUMENT_OFFSET)).intValue();
} else if( isIntegerOrLong(arguments[1]) && isIntegerOrLong(arguments[2])) {
result = ((Number)arguments[2]).intValue();
}
}
if( arguments.length > 3 && result == -1 ) {
if( isIntegerOrLong(arguments[3]) ) {
result = ((Number)arguments[3]).intValue();
}
}
}
return result;
}
private int retrieveInt( Object param, String key ) {
if( isMapWithValue(param, key) ) {
return ((Number)((Map)param).get(key)).intValue();
} else if( isIntegerOrLong(param) ) {
return ((Number)param).intValue();
}
return -1;
}
private boolean isIntegerOrLong( Object param ) {
return (param instanceof Integer) || (param instanceof Long);
}
private boolean isMapWithValue( Object param, String key ) {
return (param instanceof Map) && ((Map)param).containsKey(key);
}
});
} else if (clazz.isAssignableFrom(arg.getClass())) {
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Example example = Example.create(arg).ignoreCase();
Criteria crit = session.createCriteria(clazz);
crit.add(example);
- if(arguments.length > 1 && arguments[0] instanceof Map) {
+ if(arguments.length > 1 && arguments[1] instanceof Map) {
GrailsHibernateUtil.populateArgumentsForCriteria(crit, (Map)arguments[1] );
}
return crit.list();
}
});
}
else if(arguments[0] instanceof Map) {
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Criteria crit = session.createCriteria(clazz);
GrailsHibernateUtil.populateArgumentsForCriteria(crit, (Map)arguments[0] );
return crit.list();
}
});
}
throw new MissingMethodException(methodName, clazz, arguments);
}
}
| true | true | protected Object doInvokeInternal(final Class clazz, String methodName, final Object[] arguments) {
if (arguments.length == 0)
return getHibernateTemplate().loadAll(clazz);
final Object arg = arguments[0] instanceof GString ? arguments[0].toString() : arguments[0];
// if the arg is an instance of the class find by example
if (arg instanceof String) {
final String query = ((String) arg).trim();
final String shortName = GrailsClassUtils.getShortName(clazz);
if (!query.matches("(?i)from(?-i)\\s+[" + clazz.getName() + "|" + shortName
+ "].*")) {
throw new GrailsQueryException("Invalid query [" + query + "] for domain class [" + clazz + "]");
}
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.createQuery(query);
Object[] queryArgs = null;
Map queryNamedArgs = null;
int max = retrieveMaxValue(arguments);
int offset = retrieveOffsetValue(arguments);
if (arguments.length > 1) {
if (arguments[1] instanceof Collection) {
queryArgs = GrailsClassUtils.collectionToObjectArray((Collection) arguments[1]);
} else if (arguments[1].getClass().isArray()) {
queryArgs = (Object[]) arguments[1];
} else if (arguments[1] instanceof Map) {
queryNamedArgs = (Map) arguments[1];
}
}
if (queryArgs != null) {
for (int i = 0; i < queryArgs.length; i++) {
if (queryArgs[i] instanceof GString) {
q.setParameter(i, queryArgs[i].toString());
} else {
q.setParameter(i, queryArgs[i]);
}
}
}
if (queryNamedArgs != null) {
for (Iterator it = queryNamedArgs.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String))
throw new GrailsQueryException("Named parameter's name must be String: "
+ queryNamedArgs.toString());
String stringKey = (String) entry.getKey();
// Won't try to bind these parameters since they are processed separately
if( GrailsHibernateUtil.ARGUMENT_MAX.equals(stringKey) || GrailsHibernateUtil.ARGUMENT_OFFSET.equals(stringKey) ) continue;
Object value = entry.getValue();
if(value == null) {
q.setParameter(stringKey, null);
}
else if (value instanceof GString) {
q.setParameter(stringKey, value.toString());
} else if (List.class.isAssignableFrom(value.getClass())) {
q.setParameterList(stringKey, (List) value);
} else if (value.getClass().isArray()) {
q.setParameterList(stringKey, (Object[]) value);
} else {
q.setParameter(stringKey, value);
}
}
}
if (max > 0) {
q.setMaxResults(max);
}
if (offset > 0) {
q.setFirstResult(offset);
}
return q.list();
}
private int retrieveMaxValue(Object[] arguments) {
int result = -1;
if( arguments.length > 1) {
result = retrieveInt(arguments[1], GrailsHibernateUtil.ARGUMENT_MAX);
if( arguments.length > 2 && result == -1 ) {
result = retrieveInt(arguments[2], GrailsHibernateUtil.ARGUMENT_MAX);
}
}
return result;
}
private int retrieveOffsetValue(Object[] arguments) {
int result = -1;
if( arguments.length > 1) {
if( isMapWithValue(arguments[1], GrailsHibernateUtil.ARGUMENT_OFFSET) ) {
result = ((Number)((Map)arguments[1]).get(GrailsHibernateUtil.ARGUMENT_OFFSET)).intValue();
}
if( arguments.length > 2 && result == -1 ) {
if( isMapWithValue(arguments[2], GrailsHibernateUtil.ARGUMENT_OFFSET) ) {
result = ((Number)((Map)arguments[2]).get(GrailsHibernateUtil.ARGUMENT_OFFSET)).intValue();
} else if( isIntegerOrLong(arguments[1]) && isIntegerOrLong(arguments[2])) {
result = ((Number)arguments[2]).intValue();
}
}
if( arguments.length > 3 && result == -1 ) {
if( isIntegerOrLong(arguments[3]) ) {
result = ((Number)arguments[3]).intValue();
}
}
}
return result;
}
private int retrieveInt( Object param, String key ) {
if( isMapWithValue(param, key) ) {
return ((Number)((Map)param).get(key)).intValue();
} else if( isIntegerOrLong(param) ) {
return ((Number)param).intValue();
}
return -1;
}
private boolean isIntegerOrLong( Object param ) {
return (param instanceof Integer) || (param instanceof Long);
}
private boolean isMapWithValue( Object param, String key ) {
return (param instanceof Map) && ((Map)param).containsKey(key);
}
});
} else if (clazz.isAssignableFrom(arg.getClass())) {
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Example example = Example.create(arg).ignoreCase();
Criteria crit = session.createCriteria(clazz);
crit.add(example);
if(arguments.length > 1 && arguments[0] instanceof Map) {
GrailsHibernateUtil.populateArgumentsForCriteria(crit, (Map)arguments[1] );
}
return crit.list();
}
});
}
else if(arguments[0] instanceof Map) {
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Criteria crit = session.createCriteria(clazz);
GrailsHibernateUtil.populateArgumentsForCriteria(crit, (Map)arguments[0] );
return crit.list();
}
});
}
throw new MissingMethodException(methodName, clazz, arguments);
}
| protected Object doInvokeInternal(final Class clazz, String methodName, final Object[] arguments) {
if (arguments.length == 0)
return getHibernateTemplate().loadAll(clazz);
final Object arg = arguments[0] instanceof GString ? arguments[0].toString() : arguments[0];
// if the arg is an instance of the class find by example
if (arg instanceof String) {
final String query = ((String) arg).trim();
final String shortName = GrailsClassUtils.getShortName(clazz);
if (!query.matches("(?i)from(?-i)\\s+[" + clazz.getName() + "|" + shortName
+ "].*")) {
throw new GrailsQueryException("Invalid query [" + query + "] for domain class [" + clazz + "]");
}
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query q = session.createQuery(query);
Object[] queryArgs = null;
Map queryNamedArgs = null;
int max = retrieveMaxValue(arguments);
int offset = retrieveOffsetValue(arguments);
if (arguments.length > 1) {
if (arguments[1] instanceof Collection) {
queryArgs = GrailsClassUtils.collectionToObjectArray((Collection) arguments[1]);
} else if (arguments[1].getClass().isArray()) {
queryArgs = (Object[]) arguments[1];
} else if (arguments[1] instanceof Map) {
queryNamedArgs = (Map) arguments[1];
}
}
if (queryArgs != null) {
for (int i = 0; i < queryArgs.length; i++) {
if (queryArgs[i] instanceof GString) {
q.setParameter(i, queryArgs[i].toString());
} else {
q.setParameter(i, queryArgs[i]);
}
}
}
if (queryNamedArgs != null) {
for (Iterator it = queryNamedArgs.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String))
throw new GrailsQueryException("Named parameter's name must be String: "
+ queryNamedArgs.toString());
String stringKey = (String) entry.getKey();
// Won't try to bind these parameters since they are processed separately
if( GrailsHibernateUtil.ARGUMENT_MAX.equals(stringKey) || GrailsHibernateUtil.ARGUMENT_OFFSET.equals(stringKey) ) continue;
Object value = entry.getValue();
if(value == null) {
q.setParameter(stringKey, null);
}
else if (value instanceof GString) {
q.setParameter(stringKey, value.toString());
} else if (List.class.isAssignableFrom(value.getClass())) {
q.setParameterList(stringKey, (List) value);
} else if (value.getClass().isArray()) {
q.setParameterList(stringKey, (Object[]) value);
} else {
q.setParameter(stringKey, value);
}
}
}
if (max > 0) {
q.setMaxResults(max);
}
if (offset > 0) {
q.setFirstResult(offset);
}
return q.list();
}
private int retrieveMaxValue(Object[] arguments) {
int result = -1;
if( arguments.length > 1) {
result = retrieveInt(arguments[1], GrailsHibernateUtil.ARGUMENT_MAX);
if( arguments.length > 2 && result == -1 ) {
result = retrieveInt(arguments[2], GrailsHibernateUtil.ARGUMENT_MAX);
}
}
return result;
}
private int retrieveOffsetValue(Object[] arguments) {
int result = -1;
if( arguments.length > 1) {
if( isMapWithValue(arguments[1], GrailsHibernateUtil.ARGUMENT_OFFSET) ) {
result = ((Number)((Map)arguments[1]).get(GrailsHibernateUtil.ARGUMENT_OFFSET)).intValue();
}
if( arguments.length > 2 && result == -1 ) {
if( isMapWithValue(arguments[2], GrailsHibernateUtil.ARGUMENT_OFFSET) ) {
result = ((Number)((Map)arguments[2]).get(GrailsHibernateUtil.ARGUMENT_OFFSET)).intValue();
} else if( isIntegerOrLong(arguments[1]) && isIntegerOrLong(arguments[2])) {
result = ((Number)arguments[2]).intValue();
}
}
if( arguments.length > 3 && result == -1 ) {
if( isIntegerOrLong(arguments[3]) ) {
result = ((Number)arguments[3]).intValue();
}
}
}
return result;
}
private int retrieveInt( Object param, String key ) {
if( isMapWithValue(param, key) ) {
return ((Number)((Map)param).get(key)).intValue();
} else if( isIntegerOrLong(param) ) {
return ((Number)param).intValue();
}
return -1;
}
private boolean isIntegerOrLong( Object param ) {
return (param instanceof Integer) || (param instanceof Long);
}
private boolean isMapWithValue( Object param, String key ) {
return (param instanceof Map) && ((Map)param).containsKey(key);
}
});
} else if (clazz.isAssignableFrom(arg.getClass())) {
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Example example = Example.create(arg).ignoreCase();
Criteria crit = session.createCriteria(clazz);
crit.add(example);
if(arguments.length > 1 && arguments[1] instanceof Map) {
GrailsHibernateUtil.populateArgumentsForCriteria(crit, (Map)arguments[1] );
}
return crit.list();
}
});
}
else if(arguments[0] instanceof Map) {
return super.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Criteria crit = session.createCriteria(clazz);
GrailsHibernateUtil.populateArgumentsForCriteria(crit, (Map)arguments[0] );
return crit.list();
}
});
}
throw new MissingMethodException(methodName, clazz, arguments);
}
|
diff --git a/src/main/java/org/jboss/dcp/api/rest/SuggestionsRestService.java b/src/main/java/org/jboss/dcp/api/rest/SuggestionsRestService.java
index c9e7534..af1ae81 100644
--- a/src/main/java/org/jboss/dcp/api/rest/SuggestionsRestService.java
+++ b/src/main/java/org/jboss/dcp/api/rest/SuggestionsRestService.java
@@ -1,169 +1,169 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.jboss.dcp.api.rest;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.jboss.dcp.api.annotations.header.AccessControlAllowOrigin;
import org.jboss.dcp.api.annotations.security.GuestAllowed;
import org.jboss.dcp.api.model.QuerySettings;
import org.jboss.dcp.api.service.SearchClientService;
import org.jboss.dcp.api.util.SearchUtils;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import java.util.logging.Logger;
/**
* Suggestions REST API.
*
* @author Lukas Vlcek
*/
@RequestScoped
@Path("/suggestions")
@Produces(MediaType.APPLICATION_JSON)
public class SuggestionsRestService extends RestServiceBase {
public static final String SEARCH_INDEX_NAME = "data_project_info";
public static final String SEARCH_INDEX_TYPE = "jbossorg_project_info";
@Inject
protected Logger log;
@Inject
protected SearchClientService searchClientService;
@GET
@Path("/query_string")
@Produces(MediaType.APPLICATION_JSON)
@GuestAllowed
@AccessControlAllowOrigin
public Object queryString(@Context UriInfo uriInfo) {
try {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
String query = SearchUtils.trimToNull(params.getFirst(QuerySettings.QUERY_KEY));
if (query == null) {
throw new IllegalArgumentException(QuerySettings.QUERY_KEY);
}
throw new Exception("Method not implemented yet!");
} catch (IllegalArgumentException e) {
return createBadFieldDataResponse(e.getMessage());
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
@Path("/project")
@Produces(MediaType.APPLICATION_JSON)
@GuestAllowed
@AccessControlAllowOrigin
public Object project(@Context UriInfo uriInfo) {
try {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
String query = SearchUtils.trimToNull(params.getFirst(QuerySettings.QUERY_KEY));
if (query == null) {
throw new IllegalArgumentException(QuerySettings.QUERY_KEY);
}
int responseSize = 5;
String size = SearchUtils.trimToNull(params.getFirst(QuerySettings.Filters.SIZE_KEY));
if (size != null ) {
try {
responseSize = Integer.parseInt(size);
} catch (NumberFormatException ex) {
log.finer("Error parsing size URL parameter to int");
log.finest(ex.getMessage());
}
}
final Client client = searchClientService.getClient();
final MultiSearchRequestBuilder msrb = getProjectMultiSearchRequestBuilder(
client.prepareMultiSearch(),
- getProjectSearchNGramRequestBuilder(client.prepareSearch(SEARCH_INDEX_NAME, SEARCH_INDEX_TYPE), query, responseSize),
- getProjectSearchFuzzyRequestBuilder(client.prepareSearch(SEARCH_INDEX_NAME, SEARCH_INDEX_TYPE), query, responseSize)
+ getProjectSearchNGramRequestBuilder(client.prepareSearch().setIndices(SEARCH_INDEX_NAME).setTypes(SEARCH_INDEX_TYPE), query, responseSize),
+ getProjectSearchFuzzyRequestBuilder(client.prepareSearch().setIndices(SEARCH_INDEX_NAME).setTypes(SEARCH_INDEX_TYPE), query, responseSize)
);
final MultiSearchResponse searchResponse = msrb.execute().actionGet();
return createResponse(searchResponse, null); // Do we need uuid in this case?
} catch (IllegalArgumentException e) {
return createBadFieldDataResponse(e.getMessage());
} catch (Exception e) {
return createErrorResponse(e);
}
}
/**
*
* @param srb
* @param query
* @return
*/
protected SearchRequestBuilder getProjectSearchNGramRequestBuilder(SearchRequestBuilder srb, String query, int size) {
return srb.addFields("dcp_project", "dcp_project_name")
.setSize(size)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(
QueryBuilders.queryString(query)
.analyzer("whitespace")
.field("dcp_project_name")
.field("dcp_project_name.edgengram")
.field("dcp_project_name.ngram")
)
.addHighlightedField("dcp_project_name", 1, 0)
.addHighlightedField("dcp_project_name.ngram", 1, 0)
.addHighlightedField("dcp_project_name.edgengram", 1, 0)
;
}
/**
*
* @param srb
* @param query
* @return
*/
protected SearchRequestBuilder getProjectSearchFuzzyRequestBuilder(SearchRequestBuilder srb, String query, int size) {
return srb.addFields("dcp_project","dcp_project_name")
.setSize(size)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(
QueryBuilders.fuzzyLikeThisQuery("dcp_project_name", "dcp_project_name.ngram")
.analyzer("whitespace")
.maxQueryTerms(10)
.likeText(query)
)
.addHighlightedField("dcp_project_name", 1, 0)
.addHighlightedField("dcp_project_name.ngram", 1, 0)
.addHighlightedField("dcp_project_name.edgengram", 1, 0)
;
}
/**
* @param msrb
* @param srbNGram
* @param srbFuzzy
* @return
*/
protected MultiSearchRequestBuilder getProjectMultiSearchRequestBuilder(MultiSearchRequestBuilder msrb,
SearchRequestBuilder srbNGram,
SearchRequestBuilder srbFuzzy) {
return msrb.add(srbNGram).add(srbFuzzy);
}
}
| true | true | public Object project(@Context UriInfo uriInfo) {
try {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
String query = SearchUtils.trimToNull(params.getFirst(QuerySettings.QUERY_KEY));
if (query == null) {
throw new IllegalArgumentException(QuerySettings.QUERY_KEY);
}
int responseSize = 5;
String size = SearchUtils.trimToNull(params.getFirst(QuerySettings.Filters.SIZE_KEY));
if (size != null ) {
try {
responseSize = Integer.parseInt(size);
} catch (NumberFormatException ex) {
log.finer("Error parsing size URL parameter to int");
log.finest(ex.getMessage());
}
}
final Client client = searchClientService.getClient();
final MultiSearchRequestBuilder msrb = getProjectMultiSearchRequestBuilder(
client.prepareMultiSearch(),
getProjectSearchNGramRequestBuilder(client.prepareSearch(SEARCH_INDEX_NAME, SEARCH_INDEX_TYPE), query, responseSize),
getProjectSearchFuzzyRequestBuilder(client.prepareSearch(SEARCH_INDEX_NAME, SEARCH_INDEX_TYPE), query, responseSize)
);
final MultiSearchResponse searchResponse = msrb.execute().actionGet();
return createResponse(searchResponse, null); // Do we need uuid in this case?
} catch (IllegalArgumentException e) {
return createBadFieldDataResponse(e.getMessage());
} catch (Exception e) {
return createErrorResponse(e);
}
}
| public Object project(@Context UriInfo uriInfo) {
try {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
String query = SearchUtils.trimToNull(params.getFirst(QuerySettings.QUERY_KEY));
if (query == null) {
throw new IllegalArgumentException(QuerySettings.QUERY_KEY);
}
int responseSize = 5;
String size = SearchUtils.trimToNull(params.getFirst(QuerySettings.Filters.SIZE_KEY));
if (size != null ) {
try {
responseSize = Integer.parseInt(size);
} catch (NumberFormatException ex) {
log.finer("Error parsing size URL parameter to int");
log.finest(ex.getMessage());
}
}
final Client client = searchClientService.getClient();
final MultiSearchRequestBuilder msrb = getProjectMultiSearchRequestBuilder(
client.prepareMultiSearch(),
getProjectSearchNGramRequestBuilder(client.prepareSearch().setIndices(SEARCH_INDEX_NAME).setTypes(SEARCH_INDEX_TYPE), query, responseSize),
getProjectSearchFuzzyRequestBuilder(client.prepareSearch().setIndices(SEARCH_INDEX_NAME).setTypes(SEARCH_INDEX_TYPE), query, responseSize)
);
final MultiSearchResponse searchResponse = msrb.execute().actionGet();
return createResponse(searchResponse, null); // Do we need uuid in this case?
} catch (IllegalArgumentException e) {
return createBadFieldDataResponse(e.getMessage());
} catch (Exception e) {
return createErrorResponse(e);
}
}
|
diff --git a/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/proxy/unix/UnixProxyProvider.java b/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/proxy/unix/UnixProxyProvider.java
index 91a4399f8..414ed3323 100644
--- a/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/proxy/unix/UnixProxyProvider.java
+++ b/bundles/org.eclipse.core.net/src/org/eclipse/core/internal/net/proxy/unix/UnixProxyProvider.java
@@ -1,223 +1,225 @@
/*******************************************************************************
* Copyright (c) 2008 Oakland Software Incorporated 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:
* Oakland Software Incorporated - initial API and implementation
* IBM Corporation - implementation
*******************************************************************************/
package org.eclipse.core.internal.net.proxy.unix;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import org.eclipse.core.internal.net.AbstractProxyProvider;
import org.eclipse.core.internal.net.Activator;
import org.eclipse.core.internal.net.Policy;
import org.eclipse.core.internal.net.ProxyData;
import org.eclipse.core.net.proxy.IProxyData;
public class UnixProxyProvider extends AbstractProxyProvider {
private static final String LIBRARY_GCONF2 = "gconf-2"; //$NON-NLS-1$
private static final String LIBRARY_NAME = "gnomeproxy-1.0.0"; //$NON-NLS-1$
private static boolean isGnomeLibLoaded = false;
static {
// We have to load this here otherwise gconf seems to have problems
// causing hangs and various other bad behavior,
// please don't move this to be initialized on another thread.
loadGnomeLib();
}
public UnixProxyProvider() {
// Nothing to initialize
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.internal.net.AbstractProxyProvider#getProxyData(java.net.URI)
*/
public IProxyData[] getProxyData(URI uri) {
if (uri.getScheme() != null) {
ProxyData pd = getSystemProxyInfo(uri.getScheme());
return pd != null ? new IProxyData[] { pd } : new IProxyData[0];
}
String[] commonTypes = new String[] { IProxyData.HTTP_PROXY_TYPE,
IProxyData.SOCKS_PROXY_TYPE, IProxyData.HTTPS_PROXY_TYPE };
return getProxyForTypes(commonTypes);
}
private IProxyData[] getProxyForTypes(String[] types) {
ArrayList allData = new ArrayList();
for (int i = 0; i < types.length; i++) {
String type = types[i];
ProxyData pd = getSystemProxyInfo(type);
if (pd != null && pd.getHost() != null) {
allData.add(pd);
}
}
return (IProxyData[]) allData.toArray(new IProxyData[0]);
}
public String[] getNonProxiedHosts() {
String[] npHosts;
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Getting no_proxy"); //$NON-NLS-1$
// First try the environment variable which is a URL
String npEnv = getEnv("no_proxy"); //$NON-NLS-1$
if (npEnv != null) {
npHosts = npEnv.split(","); //$NON-NLS-1$
for (int i = 0; i < npHosts.length; i++)
npHosts[i] = npHosts[i].trim();
if (Policy.DEBUG_SYSTEM_PROVIDERS) {
Policy.debug("Got Env no_proxy: " + npEnv); //$NON-NLS-1$
debugPrint(npHosts);
}
return npHosts;
}
if (isGnomeLibLoaded) {
try {
npHosts = getGConfNonProxyHosts();
if (npHosts != null && npHosts.length > 0) {
if (Policy.DEBUG_SYSTEM_PROVIDERS) {
Policy.debug("Got Gnome no_proxy"); //$NON-NLS-1$
debugPrint(npHosts);
}
return npHosts;
}
} catch (UnsatisfiedLinkError e) {
// The library should be loaded, so this is a real exception
Activator.logError(
"Problem during accessing Gnome library", e); //$NON-NLS-1$
}
}
return new String[0];
}
// Returns null if something wrong or there is no proxy for the protocol
protected ProxyData getSystemProxyInfo(String protocol) {
ProxyData pd = null;
String envName = null;
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Getting proxies for: " + protocol); //$NON-NLS-1$
try {
// protocol schemes are ISO 8859 (ASCII)
protocol = protocol.toLowerCase(Locale.ENGLISH);
// First try the environment variable which is a URL
envName = protocol + "_proxy"; //$NON-NLS-1$
String proxyEnv = getEnv(envName);
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got proxyEnv: " + proxyEnv); //$NON-NLS-1$
if (proxyEnv != null) {
URI uri = new URI(proxyEnv);
pd = new ProxyData(protocol);
pd.setHost(uri.getHost());
pd.setPort(uri.getPort());
String userInfo = uri.getUserInfo();
if (userInfo != null) {
String user = null;
String password = null;
int pwInd = userInfo.indexOf(':');
if (pwInd >= 0) {
user = userInfo.substring(0, pwInd);
password = userInfo.substring(pwInd + 1);
} else {
user = userInfo;
}
pd.setUserid(user);
pd.setPassword(password);
}
pd.setSource("LINUX_ENV"); //$NON-NLS-1$
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got Env proxy: " + pd); //$NON-NLS-1$
return pd;
}
} catch (Exception e) {
Activator.logError(
"Problem during accessing system variable: " + envName, e); //$NON-NLS-1$
}
if (isGnomeLibLoaded) {
try {
// Then ask Gnome
pd = getGConfProxyInfo(protocol);
- if (Policy.DEBUG_SYSTEM_PROVIDERS)
- Policy.debug("Got Gnome proxy: " + pd); //$NON-NLS-1$
- pd.setSource("LINUX_GNOME"); //$NON-NLS-1$
- return pd;
+ if (pd != null) {
+ if (Policy.DEBUG_SYSTEM_PROVIDERS)
+ Policy.debug("Got Gnome proxy: " + pd); //$NON-NLS-1$
+ pd.setSource("LINUX_GNOME"); //$NON-NLS-1$
+ return pd;
+ }
} catch (UnsatisfiedLinkError e) {
// The library should be loaded, so this is a real exception
Activator.logError(
"Problem during accessing Gnome library", e); //$NON-NLS-1$
}
}
return null;
}
private String getEnv(String env) {
Properties props = new Properties();
try {
props.load(Runtime.getRuntime().exec("env").getInputStream()); //$NON-NLS-1$
} catch (IOException e) {
Activator.logError(
"Problem during accessing system variable: " + env, e); //$NON-NLS-1$
}
return props.getProperty(env);
}
private static void loadGnomeLib() {
try {
System.loadLibrary(LIBRARY_GCONF2);
} catch (final UnsatisfiedLinkError e) {
// Expected on systems that are missing Gnome
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Could not load library: " //$NON-NLS-1$
+ System.mapLibraryName(LIBRARY_GCONF2));
return;
}
try {
System.loadLibrary(LIBRARY_NAME);
isGnomeLibLoaded = true;
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Loaded " + //$NON-NLS-1$
System.mapLibraryName(LIBRARY_NAME) + " library"); //$NON-NLS-1$
} catch (final UnsatisfiedLinkError e) {
// Expected on systems that are missing Gnome library
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Could not load library: " //$NON-NLS-1$
+ System.mapLibraryName(LIBRARY_NAME));
}
}
private void debugPrint(String[] strs) {
for (int i = 0; i < strs.length; i++)
System.out.println(i + ": " + strs[i]); //$NON-NLS-1$
}
protected static native void gconfInit();
protected static native ProxyData getGConfProxyInfo(String protocol);
protected static native String[] getGConfNonProxyHosts();
}
| true | true | protected ProxyData getSystemProxyInfo(String protocol) {
ProxyData pd = null;
String envName = null;
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Getting proxies for: " + protocol); //$NON-NLS-1$
try {
// protocol schemes are ISO 8859 (ASCII)
protocol = protocol.toLowerCase(Locale.ENGLISH);
// First try the environment variable which is a URL
envName = protocol + "_proxy"; //$NON-NLS-1$
String proxyEnv = getEnv(envName);
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got proxyEnv: " + proxyEnv); //$NON-NLS-1$
if (proxyEnv != null) {
URI uri = new URI(proxyEnv);
pd = new ProxyData(protocol);
pd.setHost(uri.getHost());
pd.setPort(uri.getPort());
String userInfo = uri.getUserInfo();
if (userInfo != null) {
String user = null;
String password = null;
int pwInd = userInfo.indexOf(':');
if (pwInd >= 0) {
user = userInfo.substring(0, pwInd);
password = userInfo.substring(pwInd + 1);
} else {
user = userInfo;
}
pd.setUserid(user);
pd.setPassword(password);
}
pd.setSource("LINUX_ENV"); //$NON-NLS-1$
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got Env proxy: " + pd); //$NON-NLS-1$
return pd;
}
} catch (Exception e) {
Activator.logError(
"Problem during accessing system variable: " + envName, e); //$NON-NLS-1$
}
if (isGnomeLibLoaded) {
try {
// Then ask Gnome
pd = getGConfProxyInfo(protocol);
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got Gnome proxy: " + pd); //$NON-NLS-1$
pd.setSource("LINUX_GNOME"); //$NON-NLS-1$
return pd;
} catch (UnsatisfiedLinkError e) {
// The library should be loaded, so this is a real exception
Activator.logError(
"Problem during accessing Gnome library", e); //$NON-NLS-1$
}
}
return null;
}
| protected ProxyData getSystemProxyInfo(String protocol) {
ProxyData pd = null;
String envName = null;
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Getting proxies for: " + protocol); //$NON-NLS-1$
try {
// protocol schemes are ISO 8859 (ASCII)
protocol = protocol.toLowerCase(Locale.ENGLISH);
// First try the environment variable which is a URL
envName = protocol + "_proxy"; //$NON-NLS-1$
String proxyEnv = getEnv(envName);
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got proxyEnv: " + proxyEnv); //$NON-NLS-1$
if (proxyEnv != null) {
URI uri = new URI(proxyEnv);
pd = new ProxyData(protocol);
pd.setHost(uri.getHost());
pd.setPort(uri.getPort());
String userInfo = uri.getUserInfo();
if (userInfo != null) {
String user = null;
String password = null;
int pwInd = userInfo.indexOf(':');
if (pwInd >= 0) {
user = userInfo.substring(0, pwInd);
password = userInfo.substring(pwInd + 1);
} else {
user = userInfo;
}
pd.setUserid(user);
pd.setPassword(password);
}
pd.setSource("LINUX_ENV"); //$NON-NLS-1$
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got Env proxy: " + pd); //$NON-NLS-1$
return pd;
}
} catch (Exception e) {
Activator.logError(
"Problem during accessing system variable: " + envName, e); //$NON-NLS-1$
}
if (isGnomeLibLoaded) {
try {
// Then ask Gnome
pd = getGConfProxyInfo(protocol);
if (pd != null) {
if (Policy.DEBUG_SYSTEM_PROVIDERS)
Policy.debug("Got Gnome proxy: " + pd); //$NON-NLS-1$
pd.setSource("LINUX_GNOME"); //$NON-NLS-1$
return pd;
}
} catch (UnsatisfiedLinkError e) {
// The library should be loaded, so this is a real exception
Activator.logError(
"Problem during accessing Gnome library", e); //$NON-NLS-1$
}
}
return null;
}
|
diff --git a/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java b/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java
index e8288f359..9e028ce7d 100644
--- a/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java
+++ b/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java
@@ -1,414 +1,415 @@
package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.IndexDocValuesField;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter; // javadoc
import org.apache.lucene.index.codecs.CodecProvider;
import org.apache.lucene.index.values.ValueType;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.Version;
import org.apache.lucene.util._TestUtil;
/** Silly class that randomizes the indexing experience. EG
* it may swap in a different merge policy/scheduler; may
* commit periodically; may or may not optimize in the end,
* may flush by doc count instead of RAM, etc.
*/
public class RandomIndexWriter implements Closeable {
public IndexWriter w;
private final Random r;
int docCount;
int flushAt;
private double flushAtFactor = 1.0;
private boolean getReaderCalled;
private final int fixedBytesLength;
private final long docValuesFieldPrefix;
private volatile boolean doDocValues;
private CodecProvider codecProvider;
// Randomly calls Thread.yield so we mixup thread scheduling
private static final class MockIndexWriter extends IndexWriter {
private final Random r;
public MockIndexWriter(Random r, Directory dir, IndexWriterConfig conf) throws IOException {
super(dir, conf);
// must make a private random since our methods are
// called from different threads; else test failures may
// not be reproducible from the original seed
this.r = new Random(r.nextInt());
}
@Override
boolean testPoint(String name) {
if (r.nextInt(4) == 2)
Thread.yield();
return true;
}
}
/** create a RandomIndexWriter with a random config: Uses TEST_VERSION_CURRENT and MockAnalyzer */
public RandomIndexWriter(Random r, Directory dir) throws IOException {
this(r, dir, LuceneTestCase.newIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, new MockAnalyzer(r)));
}
/** create a RandomIndexWriter with a random config: Uses TEST_VERSION_CURRENT */
public RandomIndexWriter(Random r, Directory dir, Analyzer a) throws IOException {
this(r, dir, LuceneTestCase.newIndexWriterConfig(r, LuceneTestCase.TEST_VERSION_CURRENT, a));
}
/** create a RandomIndexWriter with a random config */
public RandomIndexWriter(Random r, Directory dir, Version v, Analyzer a) throws IOException {
this(r, dir, LuceneTestCase.newIndexWriterConfig(r, v, a));
}
/** create a RandomIndexWriter with the provided config */
public RandomIndexWriter(Random r, Directory dir, IndexWriterConfig c) throws IOException {
this.r = r;
w = new MockIndexWriter(r, dir, c);
flushAt = _TestUtil.nextInt(r, 10, 1000);
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW config=" + w.getConfig());
System.out.println("codec default=" + w.getConfig().getCodecProvider().getDefaultFieldCodec());
w.setInfoStream(System.out);
}
/* TODO: find some what to make that random...
* This must be fixed across all fixed bytes
* fields in one index. so if you open another writer
* this might change if I use r.nextInt(x)
* maybe we can peek at the existing files here?
*/
fixedBytesLength = 37;
docValuesFieldPrefix = r.nextLong();
codecProvider = w.getConfig().getCodecProvider();
switchDoDocValues();
}
private void switchDoDocValues() {
// randomly enable / disable docValues
doDocValues = LuceneTestCase.rarely(r);
}
/**
* Adds a Document.
* @see IndexWriter#addDocument(Iterable)
*/
public <T extends IndexableField> void addDocument(final Iterable<T> doc) throws IOException {
if (doDocValues && doc instanceof Document) {
randomPerDocFieldValues(r, (Document) doc);
}
if (r.nextInt(5) == 3) {
// TODO: maybe, we should simply buffer up added docs
// (but we need to clone them), and only when
// getReader, commit, etc. are called, we do an
// addDocuments? Would be better testing.
w.addDocuments(new Iterable<Iterable<T>>() {
@Override
public Iterator<Iterable<T>> iterator() {
return new Iterator<Iterable<T>>() {
boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterable<T> next() {
if (done) {
throw new IllegalStateException();
}
done = true;
return doc;
}
};
}
});
} else {
w.addDocument(doc);
}
maybeCommit();
}
private void randomPerDocFieldValues(Random random, Document doc) {
ValueType[] values = ValueType.values();
ValueType type = values[random.nextInt(values.length)];
String name = "random_" + type.name() + "" + docValuesFieldPrefix;
if ("PreFlex".equals(codecProvider.getFieldCodec(name)) || doc.getField(name) != null)
return;
IndexDocValuesField docValuesField = new IndexDocValuesField(name);
switch (type) {
case BYTES_FIXED_DEREF:
case BYTES_FIXED_STRAIGHT:
case BYTES_FIXED_SORTED:
- final String randomUnicodeString = _TestUtil.randomUnicodeString(random, fixedBytesLength);
+ //make sure we use a valid unicode string with a fixed size byte length
+ final String randomUnicodeString = _TestUtil.randomFixedByteLengthUnicodeString(random, fixedBytesLength);
BytesRef fixedRef = new BytesRef(randomUnicodeString);
if (fixedRef.length > fixedBytesLength) {
fixedRef = new BytesRef(fixedRef.bytes, 0, fixedBytesLength);
} else {
fixedRef.grow(fixedBytesLength);
fixedRef.length = fixedBytesLength;
}
docValuesField.setBytes(fixedRef, type);
break;
case BYTES_VAR_DEREF:
case BYTES_VAR_STRAIGHT:
case BYTES_VAR_SORTED:
BytesRef ref = new BytesRef(_TestUtil.randomUnicodeString(random, 200));
docValuesField.setBytes(ref, type);
break;
case FLOAT_32:
docValuesField.setFloat(random.nextFloat());
break;
case FLOAT_64:
docValuesField.setFloat(random.nextDouble());
break;
case VAR_INTS:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_16:
docValuesField.setInt(random.nextInt(Short.MAX_VALUE));
break;
case FIXED_INTS_32:
docValuesField.setInt(random.nextInt());
break;
case FIXED_INTS_64:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_8:
docValuesField.setInt(random.nextInt(128));
break;
default:
throw new IllegalArgumentException("no such type: " + type);
}
doc.add(docValuesField);
}
private void maybeCommit() throws IOException {
if (docCount++ == flushAt) {
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW.add/updateDocument: now doing a commit at docCount=" + docCount);
}
w.commit();
flushAt += _TestUtil.nextInt(r, (int) (flushAtFactor * 10), (int) (flushAtFactor * 1000));
if (flushAtFactor < 2e6) {
// gradually but exponentially increase time b/w flushes
flushAtFactor *= 1.05;
}
switchDoDocValues();
}
}
public void addDocuments(Iterable<? extends Iterable<? extends IndexableField>> docs) throws IOException {
w.addDocuments(docs);
maybeCommit();
}
public void updateDocuments(Term delTerm, Iterable<? extends Iterable<? extends IndexableField>> docs) throws IOException {
w.updateDocuments(delTerm, docs);
maybeCommit();
}
/**
* Updates a document.
* @see IndexWriter#updateDocument(Term, Iterable)
*/
public <T extends IndexableField> void updateDocument(Term t, final Iterable<T> doc) throws IOException {
if (doDocValues) {
randomPerDocFieldValues(r, (Document) doc);
}
if (r.nextInt(5) == 3) {
w.updateDocuments(t, new Iterable<Iterable<T>>() {
@Override
public Iterator<Iterable<T>> iterator() {
return new Iterator<Iterable<T>>() {
boolean done;
@Override
public boolean hasNext() {
return !done;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public Iterable<T> next() {
if (done) {
throw new IllegalStateException();
}
done = true;
return doc;
}
};
}
});
} else {
w.updateDocument(t, doc);
}
maybeCommit();
}
public void addIndexes(Directory... dirs) throws CorruptIndexException, IOException {
w.addIndexes(dirs);
}
public void deleteDocuments(Term term) throws CorruptIndexException, IOException {
w.deleteDocuments(term);
}
public void deleteDocuments(Query q) throws CorruptIndexException, IOException {
w.deleteDocuments(q);
}
public void commit() throws CorruptIndexException, IOException {
w.commit();
switchDoDocValues();
}
public int numDocs() throws IOException {
return w.numDocs();
}
public int maxDoc() {
return w.maxDoc();
}
public void deleteAll() throws IOException {
w.deleteAll();
}
public IndexReader getReader() throws IOException {
return getReader(true);
}
private boolean doRandomOptimize = true;
private boolean doRandomOptimizeAssert = true;
public void expungeDeletes(boolean doWait) throws IOException {
w.expungeDeletes(doWait);
}
public void expungeDeletes() throws IOException {
w.expungeDeletes();
}
public void setDoRandomOptimize(boolean v) {
doRandomOptimize = v;
}
public void setDoRandomOptimizeAssert(boolean v) {
doRandomOptimizeAssert = v;
}
private void doRandomOptimize() throws IOException {
if (doRandomOptimize) {
final int segCount = w.getSegmentCount();
if (r.nextBoolean() || segCount == 0) {
// full optimize
w.optimize();
} else {
// partial optimize
final int limit = _TestUtil.nextInt(r, 1, segCount);
w.optimize(limit);
assert !doRandomOptimizeAssert || w.getSegmentCount() <= limit: "limit=" + limit + " actual=" + w.getSegmentCount();
}
}
switchDoDocValues();
}
public IndexReader getReader(boolean applyDeletions) throws IOException {
getReaderCalled = true;
if (r.nextInt(4) == 2) {
doRandomOptimize();
}
// If we are writing with PreFlexRW, force a full
// IndexReader.open so terms are sorted in codepoint
// order during searching:
if (!applyDeletions || !w.codecs.getDefaultFieldCodec().equals("PreFlex") && r.nextBoolean()) {
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW.getReader: use NRT reader");
}
if (r.nextInt(5) == 1) {
w.commit();
}
return w.getReader(applyDeletions);
} else {
if (LuceneTestCase.VERBOSE) {
System.out.println("RIW.getReader: open new reader");
}
w.commit();
switchDoDocValues();
if (r.nextBoolean()) {
return IndexReader.open(w.getDirectory(), new KeepOnlyLastCommitDeletionPolicy(), r.nextBoolean(), _TestUtil.nextInt(r, 1, 10), w.getConfig().getCodecProvider());
} else {
return w.getReader(applyDeletions);
}
}
}
/**
* Close this writer.
* @see IndexWriter#close()
*/
public void close() throws IOException {
// if someone isn't using getReader() API, we want to be sure to
// maybeOptimize since presumably they might open a reader on the dir.
if (getReaderCalled == false && r.nextInt(8) == 2) {
doRandomOptimize();
}
w.close();
}
/**
* Forces an optimize.
* <p>
* NOTE: this should be avoided in tests unless absolutely necessary,
* as it will result in less test coverage.
* @see IndexWriter#optimize()
*/
public void optimize() throws IOException {
w.optimize();
}
}
| true | true | private void randomPerDocFieldValues(Random random, Document doc) {
ValueType[] values = ValueType.values();
ValueType type = values[random.nextInt(values.length)];
String name = "random_" + type.name() + "" + docValuesFieldPrefix;
if ("PreFlex".equals(codecProvider.getFieldCodec(name)) || doc.getField(name) != null)
return;
IndexDocValuesField docValuesField = new IndexDocValuesField(name);
switch (type) {
case BYTES_FIXED_DEREF:
case BYTES_FIXED_STRAIGHT:
case BYTES_FIXED_SORTED:
final String randomUnicodeString = _TestUtil.randomUnicodeString(random, fixedBytesLength);
BytesRef fixedRef = new BytesRef(randomUnicodeString);
if (fixedRef.length > fixedBytesLength) {
fixedRef = new BytesRef(fixedRef.bytes, 0, fixedBytesLength);
} else {
fixedRef.grow(fixedBytesLength);
fixedRef.length = fixedBytesLength;
}
docValuesField.setBytes(fixedRef, type);
break;
case BYTES_VAR_DEREF:
case BYTES_VAR_STRAIGHT:
case BYTES_VAR_SORTED:
BytesRef ref = new BytesRef(_TestUtil.randomUnicodeString(random, 200));
docValuesField.setBytes(ref, type);
break;
case FLOAT_32:
docValuesField.setFloat(random.nextFloat());
break;
case FLOAT_64:
docValuesField.setFloat(random.nextDouble());
break;
case VAR_INTS:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_16:
docValuesField.setInt(random.nextInt(Short.MAX_VALUE));
break;
case FIXED_INTS_32:
docValuesField.setInt(random.nextInt());
break;
case FIXED_INTS_64:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_8:
docValuesField.setInt(random.nextInt(128));
break;
default:
throw new IllegalArgumentException("no such type: " + type);
}
doc.add(docValuesField);
}
| private void randomPerDocFieldValues(Random random, Document doc) {
ValueType[] values = ValueType.values();
ValueType type = values[random.nextInt(values.length)];
String name = "random_" + type.name() + "" + docValuesFieldPrefix;
if ("PreFlex".equals(codecProvider.getFieldCodec(name)) || doc.getField(name) != null)
return;
IndexDocValuesField docValuesField = new IndexDocValuesField(name);
switch (type) {
case BYTES_FIXED_DEREF:
case BYTES_FIXED_STRAIGHT:
case BYTES_FIXED_SORTED:
//make sure we use a valid unicode string with a fixed size byte length
final String randomUnicodeString = _TestUtil.randomFixedByteLengthUnicodeString(random, fixedBytesLength);
BytesRef fixedRef = new BytesRef(randomUnicodeString);
if (fixedRef.length > fixedBytesLength) {
fixedRef = new BytesRef(fixedRef.bytes, 0, fixedBytesLength);
} else {
fixedRef.grow(fixedBytesLength);
fixedRef.length = fixedBytesLength;
}
docValuesField.setBytes(fixedRef, type);
break;
case BYTES_VAR_DEREF:
case BYTES_VAR_STRAIGHT:
case BYTES_VAR_SORTED:
BytesRef ref = new BytesRef(_TestUtil.randomUnicodeString(random, 200));
docValuesField.setBytes(ref, type);
break;
case FLOAT_32:
docValuesField.setFloat(random.nextFloat());
break;
case FLOAT_64:
docValuesField.setFloat(random.nextDouble());
break;
case VAR_INTS:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_16:
docValuesField.setInt(random.nextInt(Short.MAX_VALUE));
break;
case FIXED_INTS_32:
docValuesField.setInt(random.nextInt());
break;
case FIXED_INTS_64:
docValuesField.setInt(random.nextLong());
break;
case FIXED_INTS_8:
docValuesField.setInt(random.nextInt(128));
break;
default:
throw new IllegalArgumentException("no such type: " + type);
}
doc.add(docValuesField);
}
|
diff --git a/src/org/adaptlab/chpir/android/survey/QuestionFragmentFactory.java b/src/org/adaptlab/chpir/android/survey/QuestionFragmentFactory.java
index f1e4b46..4b68c3e 100644
--- a/src/org/adaptlab/chpir/android/survey/QuestionFragmentFactory.java
+++ b/src/org/adaptlab/chpir/android/survey/QuestionFragmentFactory.java
@@ -1,53 +1,53 @@
package org.adaptlab.chpir.android.survey;
import org.adaptlab.chpir.android.survey.Models.Question;
import org.adaptlab.chpir.android.survey.QuestionFragments.FreeResponseQuestionFragment;
import org.adaptlab.chpir.android.survey.QuestionFragments.FrontPictureQuestionFragment;
import org.adaptlab.chpir.android.survey.QuestionFragments.RearPictureQuestionFragment;
import org.adaptlab.chpir.android.survey.QuestionFragments.SelectMultipleQuestionFragment;
import org.adaptlab.chpir.android.survey.QuestionFragments.SelectMultipleWriteOtherQuestionFragment;
import org.adaptlab.chpir.android.survey.QuestionFragments.SelectOneQuestionFragment;
import org.adaptlab.chpir.android.survey.QuestionFragments.SelectOneWriteOtherQuestionFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
public class QuestionFragmentFactory {
private static final String TAG = "QuestionFragmentFactory";
public static final String EXTRA_QUESTION_ID =
"org.adaptlab.chpir.android.survey.question_id";
public static Fragment createQuestionFragment(Question question) {
String type = question.getQuestionType().toString();
Fragment fragment = null;
// TODO: Write automated test to ensure every QuestionType in
// Question.QuestionType is covered in factory
if ("SELECT_ONE".equals(type)) {
fragment = new SelectOneQuestionFragment();
} else if ("SELECT_MULTIPLE".equals(type)) {
fragment = new SelectMultipleQuestionFragment();
} else if ("SELECT_ONE_WRITE_OTHER".equals(type)) {
fragment = new SelectOneWriteOtherQuestionFragment();
} else if ("SELECT_MULTIPLE_WRITE_OTHER".equals(type)) {
fragment = new SelectMultipleWriteOtherQuestionFragment();
} else if ("FREE_RESPONSE".equals(type)) {
fragment = new FreeResponseQuestionFragment();
- } else if ("FRONT_PICURE".equals(type)) {
+ } else if ("FRONT_PICTURE".equals(type)) {
fragment = new FrontPictureQuestionFragment();
} else if ("REAR_PICTURE".equals(type)) {
fragment = new RearPictureQuestionFragment();
} else {
// Return free response fragment if unknown question type
// This should never happen
Log.e(TAG, "Received unknown question type: " + type);
fragment = new FreeResponseQuestionFragment();
}
Bundle args = new Bundle();
args.putLong(EXTRA_QUESTION_ID, question.getId());
fragment.setArguments(args);
return fragment;
}
}
| true | true | public static Fragment createQuestionFragment(Question question) {
String type = question.getQuestionType().toString();
Fragment fragment = null;
// TODO: Write automated test to ensure every QuestionType in
// Question.QuestionType is covered in factory
if ("SELECT_ONE".equals(type)) {
fragment = new SelectOneQuestionFragment();
} else if ("SELECT_MULTIPLE".equals(type)) {
fragment = new SelectMultipleQuestionFragment();
} else if ("SELECT_ONE_WRITE_OTHER".equals(type)) {
fragment = new SelectOneWriteOtherQuestionFragment();
} else if ("SELECT_MULTIPLE_WRITE_OTHER".equals(type)) {
fragment = new SelectMultipleWriteOtherQuestionFragment();
} else if ("FREE_RESPONSE".equals(type)) {
fragment = new FreeResponseQuestionFragment();
} else if ("FRONT_PICURE".equals(type)) {
fragment = new FrontPictureQuestionFragment();
} else if ("REAR_PICTURE".equals(type)) {
fragment = new RearPictureQuestionFragment();
} else {
// Return free response fragment if unknown question type
// This should never happen
Log.e(TAG, "Received unknown question type: " + type);
fragment = new FreeResponseQuestionFragment();
}
Bundle args = new Bundle();
args.putLong(EXTRA_QUESTION_ID, question.getId());
fragment.setArguments(args);
return fragment;
}
| public static Fragment createQuestionFragment(Question question) {
String type = question.getQuestionType().toString();
Fragment fragment = null;
// TODO: Write automated test to ensure every QuestionType in
// Question.QuestionType is covered in factory
if ("SELECT_ONE".equals(type)) {
fragment = new SelectOneQuestionFragment();
} else if ("SELECT_MULTIPLE".equals(type)) {
fragment = new SelectMultipleQuestionFragment();
} else if ("SELECT_ONE_WRITE_OTHER".equals(type)) {
fragment = new SelectOneWriteOtherQuestionFragment();
} else if ("SELECT_MULTIPLE_WRITE_OTHER".equals(type)) {
fragment = new SelectMultipleWriteOtherQuestionFragment();
} else if ("FREE_RESPONSE".equals(type)) {
fragment = new FreeResponseQuestionFragment();
} else if ("FRONT_PICTURE".equals(type)) {
fragment = new FrontPictureQuestionFragment();
} else if ("REAR_PICTURE".equals(type)) {
fragment = new RearPictureQuestionFragment();
} else {
// Return free response fragment if unknown question type
// This should never happen
Log.e(TAG, "Received unknown question type: " + type);
fragment = new FreeResponseQuestionFragment();
}
Bundle args = new Bundle();
args.putLong(EXTRA_QUESTION_ID, question.getId());
fragment.setArguments(args);
return fragment;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/ImprovisionTiffReader.java b/components/bio-formats/src/loci/formats/in/ImprovisionTiffReader.java
index b12c366e9..2ef07cd0c 100644
--- a/components/bio-formats/src/loci/formats/in/ImprovisionTiffReader.java
+++ b/components/bio-formats/src/loci/formats/in/ImprovisionTiffReader.java
@@ -1,348 +1,347 @@
//
// ImprovisionTiffReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.tiff.TiffParser;
/**
* ImprovisionTiffReader is the file format reader for
* Improvision TIFF files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/ImprovisionTiffReader.java">Trac</a>,
* <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/ImprovisionTiffReader.java">SVN</a></dd></dl>
*/
public class ImprovisionTiffReader extends BaseTiffReader {
// -- Constants --
public static final String IMPROVISION_MAGIC_STRING = "Improvision";
// -- Fields --
private String[] cNames;
private int pixelSizeT;
private double pixelSizeX, pixelSizeY, pixelSizeZ;
private String[] files;
private MinimalTiffReader[] readers;
private int lastFile = 0;
// -- Constructor --
public ImprovisionTiffReader() {
super("Improvision TIFF", new String[] {"tif", "tiff"});
suffixSufficient = false;
domains = new String[] {FormatTools.UNKNOWN_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
String comment = tp.getComment();
if (comment == null) return false;
return comment.indexOf(IMPROVISION_MAGIC_STRING) >= 0;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
cNames = null;
pixelSizeT = 1;
pixelSizeX = pixelSizeY = pixelSizeZ = 0;
if (readers != null) {
for (MinimalTiffReader reader : readers) {
if (reader != null) reader.close();
}
}
readers = null;
files = null;
lastFile = 0;
}
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
return noPixels ? null : files;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (readers == null || lastFile < 0 || lastFile >= readers.length ||
readers[lastFile] == null)
{
return super.get8BitLookupTable();
}
return readers[lastFile].get8BitLookupTable();
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (readers == null || lastFile < 0 || lastFile >= readers.length ||
readers[lastFile] == null)
{
return super.get16BitLookupTable();
}
return readers[lastFile].get16BitLookupTable();
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int[] zct = getZCTCoords(no);
int file = FormatTools.getIndex("XYZCT", getSizeZ(), getEffectiveSizeC(),
getSizeT(), getImageCount(), zct[0], zct[1], zct[2]) % files.length;
int plane = no / files.length;
lastFile = file;
return readers[file].openBytes(plane, buf, x, y, w, h);
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
put("Improvision", "yes");
// parse key/value pairs in the comment
String comment = ifds.get(0).getComment();
String tz = null, tc = null, tt = null;
if (comment != null) {
String[] lines = comment.split("\n");
for (String line : lines) {
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
addGlobalMeta(key, value);
if (key.equals("TotalZPlanes")) tz = value;
else if (key.equals("TotalChannels")) tc = value;
else if (key.equals("TotalTimepoints")) tt = value;
else if (key.equals("XCalibrationMicrons")) {
pixelSizeX = Double.parseDouble(value);
}
else if (key.equals("YCalibrationMicrons")) {
pixelSizeY = Double.parseDouble(value);
}
else if (key.equals("ZCalibrationMicrons")) {
pixelSizeZ = Double.parseDouble(value);
}
}
metadata.remove("Comment");
}
core[0].sizeT = 1;
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeC() == 0) core[0].sizeC = 1;
if (tz != null) core[0].sizeZ *= Integer.parseInt(tz);
if (tc != null) core[0].sizeC *= Integer.parseInt(tc);
if (tt != null) core[0].sizeT *= Integer.parseInt(tt);
if (getSizeZ() * getSizeC() * getSizeT() < getImageCount()) {
core[0].sizeC *= getImageCount();
}
else core[0].imageCount = getSizeZ() * getSizeT() * Integer.parseInt(tc);
// parse each of the comments to determine axis ordering
long[] stamps = new long[ifds.size()];
int[][] coords = new int[ifds.size()][3];
cNames = new String[getSizeC()];
boolean multipleFiles = false;
for (int i=0; i<ifds.size(); i++) {
Arrays.fill(coords[i], -1);
comment = ifds.get(i).getComment();
+ // TODO : can use loci.common.IniParser to parse the comments
comment = comment.replaceAll("\r\n", "\n");
comment = comment.replaceAll("\r", "\n");
String channelName = null;
String[] lines = comment.split("\n");
for (String line : lines) {
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
if (key.equals("TimeStampMicroSeconds")) {
stamps[i] = Long.parseLong(value);
}
else if (key.equals("ZPlane")) coords[i][0] = Integer.parseInt(value);
else if (key.equals("ChannelNo")) {
coords[i][1] = Integer.parseInt(value);
+ int ndx = Integer.parseInt(value) - 1;
+ if (cNames[ndx] == null) cNames[ndx] = channelName;
}
else if (key.equals("TimepointName")) {
coords[i][2] = Integer.parseInt(value);
}
else if (key.equals("ChannelName")) {
channelName = value;
}
- else if (key.equals("ChannelNo")) {
- int ndx = Integer.parseInt(value);
- if (cNames[ndx] == null) cNames[ndx] = channelName;
- }
else if (key.equals("MultiFileTIFF")) {
multipleFiles = value.equalsIgnoreCase("yes");
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM &&
coords[i][0] >= 0 && coords[i][1] >= 0 && coords[i][2] >= 0)
{
break;
}
}
}
if (multipleFiles) {
// look for other TIFF files that belong to this dataset
String currentUUID = getUUID(currentId);
Location parent =
new Location(currentId).getAbsoluteFile().getParentFile();
String[] list = parent.list(true);
Arrays.sort(list);
ArrayList<String> matchingFiles = new ArrayList<String>();
for (String f : list) {
String path = new Location(parent, f).getAbsolutePath();
if (isThisType(path) && getUUID(path).equals(currentUUID)) {
matchingFiles.add(path);
}
}
files = matchingFiles.toArray(new String[matchingFiles.size()]);
}
else {
files = new String[] {currentId};
}
readers = new MinimalTiffReader[files.length];
for (int i=0; i<readers.length; i++) {
readers[i] = new MinimalTiffReader();
readers[i].setId(files[i]);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// determine average time per plane
long sum = 0;
for (int i=1; i<stamps.length; i++) {
long diff = stamps[i] - stamps[i - 1];
if (diff > 0) sum += diff;
}
pixelSizeT = (int) (sum / getSizeT());
}
// determine dimension order
core[0].dimensionOrder = "XY";
if (isRGB()) core[0].dimensionOrder += "C";
for (int i=1; i<coords.length; i++) {
int zDiff = coords[i][0] - coords[i - 1][0];
int cDiff = coords[i][1] - coords[i - 1][1];
int tDiff = coords[i][2] - coords[i - 1][2];
if (zDiff > 0 && getDimensionOrder().indexOf("Z") < 0) {
core[0].dimensionOrder += "Z";
}
if (cDiff > 0 && getDimensionOrder().indexOf("C") < 0) {
core[0].dimensionOrder += "C";
}
if (tDiff > 0 && getDimensionOrder().indexOf("T") < 0) {
core[0].dimensionOrder += "T";
}
if (core[0].dimensionOrder.length() == 5) break;
}
if (getDimensionOrder().indexOf("Z") < 0) core[0].dimensionOrder += "Z";
if (getDimensionOrder().indexOf("C") < 0) core[0].dimensionOrder += "C";
if (getDimensionOrder().indexOf("T") < 0) core[0].dimensionOrder += "T";
}
/* @see BaseTiffReader#initMetadataStore() */
protected void initMetadataStore() throws FormatException {
super.initMetadataStore();
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
store.setPixelsPhysicalSizeX(pixelSizeX, 0);
store.setPixelsPhysicalSizeY(pixelSizeY, 0);
store.setPixelsPhysicalSizeZ(pixelSizeZ, 0);
store.setPixelsTimeIncrement(pixelSizeT / 1000000.0, 0);
for (int i=0; i<getEffectiveSizeC(); i++) {
if (cNames != null && i < cNames.length) {
store.setChannelName(cNames[i], 0, i);
}
}
store.setImageDescription("", 0);
}
}
// -- Helper methods --
private String getUUID(String path) throws FormatException, IOException {
RandomAccessInputStream s = new RandomAccessInputStream(path);
TiffParser parser = new TiffParser(s);
String comment = parser.getComment();
s.close();
comment = comment.replaceAll("\r\n", "\n");
comment = comment.replaceAll("\r", "\n");
String[] lines = comment.split("\n");
for (String line : lines) {
line = line.trim();
if (line.startsWith("SampleUUID=")) {
return line.substring(line.indexOf("=") + 1).trim();
}
}
return "";
}
}
| false | true | protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
put("Improvision", "yes");
// parse key/value pairs in the comment
String comment = ifds.get(0).getComment();
String tz = null, tc = null, tt = null;
if (comment != null) {
String[] lines = comment.split("\n");
for (String line : lines) {
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
addGlobalMeta(key, value);
if (key.equals("TotalZPlanes")) tz = value;
else if (key.equals("TotalChannels")) tc = value;
else if (key.equals("TotalTimepoints")) tt = value;
else if (key.equals("XCalibrationMicrons")) {
pixelSizeX = Double.parseDouble(value);
}
else if (key.equals("YCalibrationMicrons")) {
pixelSizeY = Double.parseDouble(value);
}
else if (key.equals("ZCalibrationMicrons")) {
pixelSizeZ = Double.parseDouble(value);
}
}
metadata.remove("Comment");
}
core[0].sizeT = 1;
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeC() == 0) core[0].sizeC = 1;
if (tz != null) core[0].sizeZ *= Integer.parseInt(tz);
if (tc != null) core[0].sizeC *= Integer.parseInt(tc);
if (tt != null) core[0].sizeT *= Integer.parseInt(tt);
if (getSizeZ() * getSizeC() * getSizeT() < getImageCount()) {
core[0].sizeC *= getImageCount();
}
else core[0].imageCount = getSizeZ() * getSizeT() * Integer.parseInt(tc);
// parse each of the comments to determine axis ordering
long[] stamps = new long[ifds.size()];
int[][] coords = new int[ifds.size()][3];
cNames = new String[getSizeC()];
boolean multipleFiles = false;
for (int i=0; i<ifds.size(); i++) {
Arrays.fill(coords[i], -1);
comment = ifds.get(i).getComment();
comment = comment.replaceAll("\r\n", "\n");
comment = comment.replaceAll("\r", "\n");
String channelName = null;
String[] lines = comment.split("\n");
for (String line : lines) {
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
if (key.equals("TimeStampMicroSeconds")) {
stamps[i] = Long.parseLong(value);
}
else if (key.equals("ZPlane")) coords[i][0] = Integer.parseInt(value);
else if (key.equals("ChannelNo")) {
coords[i][1] = Integer.parseInt(value);
}
else if (key.equals("TimepointName")) {
coords[i][2] = Integer.parseInt(value);
}
else if (key.equals("ChannelName")) {
channelName = value;
}
else if (key.equals("ChannelNo")) {
int ndx = Integer.parseInt(value);
if (cNames[ndx] == null) cNames[ndx] = channelName;
}
else if (key.equals("MultiFileTIFF")) {
multipleFiles = value.equalsIgnoreCase("yes");
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM &&
coords[i][0] >= 0 && coords[i][1] >= 0 && coords[i][2] >= 0)
{
break;
}
}
}
if (multipleFiles) {
// look for other TIFF files that belong to this dataset
String currentUUID = getUUID(currentId);
Location parent =
new Location(currentId).getAbsoluteFile().getParentFile();
String[] list = parent.list(true);
Arrays.sort(list);
ArrayList<String> matchingFiles = new ArrayList<String>();
for (String f : list) {
String path = new Location(parent, f).getAbsolutePath();
if (isThisType(path) && getUUID(path).equals(currentUUID)) {
matchingFiles.add(path);
}
}
files = matchingFiles.toArray(new String[matchingFiles.size()]);
}
else {
files = new String[] {currentId};
}
readers = new MinimalTiffReader[files.length];
for (int i=0; i<readers.length; i++) {
readers[i] = new MinimalTiffReader();
readers[i].setId(files[i]);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// determine average time per plane
long sum = 0;
for (int i=1; i<stamps.length; i++) {
long diff = stamps[i] - stamps[i - 1];
if (diff > 0) sum += diff;
}
pixelSizeT = (int) (sum / getSizeT());
}
// determine dimension order
core[0].dimensionOrder = "XY";
if (isRGB()) core[0].dimensionOrder += "C";
for (int i=1; i<coords.length; i++) {
int zDiff = coords[i][0] - coords[i - 1][0];
int cDiff = coords[i][1] - coords[i - 1][1];
int tDiff = coords[i][2] - coords[i - 1][2];
if (zDiff > 0 && getDimensionOrder().indexOf("Z") < 0) {
core[0].dimensionOrder += "Z";
}
if (cDiff > 0 && getDimensionOrder().indexOf("C") < 0) {
core[0].dimensionOrder += "C";
}
if (tDiff > 0 && getDimensionOrder().indexOf("T") < 0) {
core[0].dimensionOrder += "T";
}
if (core[0].dimensionOrder.length() == 5) break;
}
if (getDimensionOrder().indexOf("Z") < 0) core[0].dimensionOrder += "Z";
if (getDimensionOrder().indexOf("C") < 0) core[0].dimensionOrder += "C";
if (getDimensionOrder().indexOf("T") < 0) core[0].dimensionOrder += "T";
}
| protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
put("Improvision", "yes");
// parse key/value pairs in the comment
String comment = ifds.get(0).getComment();
String tz = null, tc = null, tt = null;
if (comment != null) {
String[] lines = comment.split("\n");
for (String line : lines) {
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
addGlobalMeta(key, value);
if (key.equals("TotalZPlanes")) tz = value;
else if (key.equals("TotalChannels")) tc = value;
else if (key.equals("TotalTimepoints")) tt = value;
else if (key.equals("XCalibrationMicrons")) {
pixelSizeX = Double.parseDouble(value);
}
else if (key.equals("YCalibrationMicrons")) {
pixelSizeY = Double.parseDouble(value);
}
else if (key.equals("ZCalibrationMicrons")) {
pixelSizeZ = Double.parseDouble(value);
}
}
metadata.remove("Comment");
}
core[0].sizeT = 1;
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeC() == 0) core[0].sizeC = 1;
if (tz != null) core[0].sizeZ *= Integer.parseInt(tz);
if (tc != null) core[0].sizeC *= Integer.parseInt(tc);
if (tt != null) core[0].sizeT *= Integer.parseInt(tt);
if (getSizeZ() * getSizeC() * getSizeT() < getImageCount()) {
core[0].sizeC *= getImageCount();
}
else core[0].imageCount = getSizeZ() * getSizeT() * Integer.parseInt(tc);
// parse each of the comments to determine axis ordering
long[] stamps = new long[ifds.size()];
int[][] coords = new int[ifds.size()][3];
cNames = new String[getSizeC()];
boolean multipleFiles = false;
for (int i=0; i<ifds.size(); i++) {
Arrays.fill(coords[i], -1);
comment = ifds.get(i).getComment();
// TODO : can use loci.common.IniParser to parse the comments
comment = comment.replaceAll("\r\n", "\n");
comment = comment.replaceAll("\r", "\n");
String channelName = null;
String[] lines = comment.split("\n");
for (String line : lines) {
int equals = line.indexOf("=");
if (equals < 0) continue;
String key = line.substring(0, equals);
String value = line.substring(equals + 1);
if (key.equals("TimeStampMicroSeconds")) {
stamps[i] = Long.parseLong(value);
}
else if (key.equals("ZPlane")) coords[i][0] = Integer.parseInt(value);
else if (key.equals("ChannelNo")) {
coords[i][1] = Integer.parseInt(value);
int ndx = Integer.parseInt(value) - 1;
if (cNames[ndx] == null) cNames[ndx] = channelName;
}
else if (key.equals("TimepointName")) {
coords[i][2] = Integer.parseInt(value);
}
else if (key.equals("ChannelName")) {
channelName = value;
}
else if (key.equals("MultiFileTIFF")) {
multipleFiles = value.equalsIgnoreCase("yes");
}
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM &&
coords[i][0] >= 0 && coords[i][1] >= 0 && coords[i][2] >= 0)
{
break;
}
}
}
if (multipleFiles) {
// look for other TIFF files that belong to this dataset
String currentUUID = getUUID(currentId);
Location parent =
new Location(currentId).getAbsoluteFile().getParentFile();
String[] list = parent.list(true);
Arrays.sort(list);
ArrayList<String> matchingFiles = new ArrayList<String>();
for (String f : list) {
String path = new Location(parent, f).getAbsolutePath();
if (isThisType(path) && getUUID(path).equals(currentUUID)) {
matchingFiles.add(path);
}
}
files = matchingFiles.toArray(new String[matchingFiles.size()]);
}
else {
files = new String[] {currentId};
}
readers = new MinimalTiffReader[files.length];
for (int i=0; i<readers.length; i++) {
readers[i] = new MinimalTiffReader();
readers[i].setId(files[i]);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// determine average time per plane
long sum = 0;
for (int i=1; i<stamps.length; i++) {
long diff = stamps[i] - stamps[i - 1];
if (diff > 0) sum += diff;
}
pixelSizeT = (int) (sum / getSizeT());
}
// determine dimension order
core[0].dimensionOrder = "XY";
if (isRGB()) core[0].dimensionOrder += "C";
for (int i=1; i<coords.length; i++) {
int zDiff = coords[i][0] - coords[i - 1][0];
int cDiff = coords[i][1] - coords[i - 1][1];
int tDiff = coords[i][2] - coords[i - 1][2];
if (zDiff > 0 && getDimensionOrder().indexOf("Z") < 0) {
core[0].dimensionOrder += "Z";
}
if (cDiff > 0 && getDimensionOrder().indexOf("C") < 0) {
core[0].dimensionOrder += "C";
}
if (tDiff > 0 && getDimensionOrder().indexOf("T") < 0) {
core[0].dimensionOrder += "T";
}
if (core[0].dimensionOrder.length() == 5) break;
}
if (getDimensionOrder().indexOf("Z") < 0) core[0].dimensionOrder += "Z";
if (getDimensionOrder().indexOf("C") < 0) core[0].dimensionOrder += "C";
if (getDimensionOrder().indexOf("T") < 0) core[0].dimensionOrder += "T";
}
|
diff --git a/src/main/java/org/jboss/modcluster/ha/rpc/RpcResponseFilter.java b/src/main/java/org/jboss/modcluster/ha/rpc/RpcResponseFilter.java
index 06f8e8ab..a8ba8a06 100644
--- a/src/main/java/org/jboss/modcluster/ha/rpc/RpcResponseFilter.java
+++ b/src/main/java/org/jboss/modcluster/ha/rpc/RpcResponseFilter.java
@@ -1,55 +1,54 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.modcluster.ha.rpc;
import org.jboss.ha.framework.interfaces.ClusterNode;
import org.jboss.ha.framework.interfaces.ResponseFilter;
/**
* A {@link ResponseFilter} that accepts any GroupRpcResponse and doesn't
* need any further responses after receiving the first.
*
* @author Brian Stansberry
*
*/
public class RpcResponseFilter implements ResponseFilter
{
private boolean stillNeed = true;
public boolean isAcceptable(Object response, ClusterNode responder)
{
- @SuppressWarnings("unchecked")
boolean acceptable = (response instanceof RpcResponse);
if (acceptable)
{
this.stillNeed = false;
}
return acceptable;
}
public boolean needMoreResponses()
{
return this.stillNeed;
}
}
| true | true | public boolean isAcceptable(Object response, ClusterNode responder)
{
@SuppressWarnings("unchecked")
boolean acceptable = (response instanceof RpcResponse);
if (acceptable)
{
this.stillNeed = false;
}
return acceptable;
}
| public boolean isAcceptable(Object response, ClusterNode responder)
{
boolean acceptable = (response instanceof RpcResponse);
if (acceptable)
{
this.stillNeed = false;
}
return acceptable;
}
|
diff --git a/maqetta.core.server/src/maqetta/core/server/command/Download.java b/maqetta.core.server/src/maqetta/core/server/command/Download.java
index c8eeace34..f159544a8 100644
--- a/maqetta.core.server/src/maqetta/core/server/command/Download.java
+++ b/maqetta.core.server/src/maqetta/core/server/command/Download.java
@@ -1,378 +1,382 @@
package maqetta.core.server.command;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.davinci.ajaxLibrary.Library;
import org.davinci.server.user.IUser;
import org.davinci.server.util.JSONReader;
import org.davinci.server.util.JSONWriter;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.maqetta.server.Command;
import org.maqetta.server.IDavinciServerConstants;
import org.maqetta.server.IVResource;
import org.maqetta.server.ServerManager;
import org.maqetta.server.VLibraryResource;
public class Download extends Command {
static final private Logger theLogger = Logger.getLogger(Download.class.getName());
private Vector<String> zippedEntries;
private URL buildURL = null;
//This should stay in sync with validation rules on the client
public static final String DOWNLOAD_FILE_REPLACE_REGEXP = "[^a-zA-z0-9_.]";
public static String buildBase = "http://build.dojotoolkit.org";
{
String builderProp = ServerManager.getServerManager().getDavinciProperty(IDavinciServerConstants.DOJO_WEB_BUILDER);
if (builderProp != null) {
buildBase = builderProp;
}
}
public void handleCommand(HttpServletRequest req, HttpServletResponse resp, IUser user) throws IOException {
// SECURITY, VALIDATION
// 'fileName': XXX not validated
// 'resources': contents eventually checked by User.getResource()
// 'libs': XXX validated?
// 'root': XXX not validated
if (user == null) {
return;
}
/* keep track of things we've added */
zippedEntries = new Vector<String>();
String path = req.getParameter("fileName");
path = sanitizeFileName(path);
String res = req.getParameter("resources");
String libs = req.getParameter("libs");
String root = req.getParameter("root");
String build = req.getParameter("build");
boolean useFullSource = "1".equals(req.getParameter("fullsource"));
if (build != null){
//TODO: should put this in a separate Thread
this.buildURL = getBuildURL(user, req.getRequestURL().toString());
}
ArrayList o = (ArrayList) JSONReader.read(res);
List lib = null;
boolean includeLibs = true;
if(libs!=null){
lib = (List) JSONReader.read(libs);
includeLibs= false;
}
String[] resources = (String[]) o.toArray(new String[o.size()]);
IVResource[] files = new IVResource[resources.length];
for (int i = 0; i < files.length; i++) {
files[i] = user.getResource(resources[i]);
}
try {
resp.setContentType("application/x-download");
resp.setHeader("Content-Disposition", "attachment; filename=" + path);
ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
IPath rootPath = new Path(root);
zipFiles(files, rootPath, zos, includeLibs);
if(lib!=null) zipLibs(lib, rootPath, zos, useFullSource);
zos.close();
// responseString="OK";
} catch (IOException e) {
responseString = "Error creating download file : " + e;
} finally {
- resp.getOutputStream().close();
+ try {
+ resp.getOutputStream().close();
+ } catch (java.io.EOFException eof) {
+ // User cancelled download
+ }
}
}
private URL getBuildURL(IUser user, String requestURLString) throws IOException {
URL buildURL = null;
try {
Map dependencies = analyzeWorkspace(user, requestURLString);
String statusCookie = requestBuild(dependencies);
String result = null;
while (result == null) {
// now poll for a response with a "result" property
URL status = new URL(new URL(buildBase), statusCookie);
InputStream is = status.openStream();
try {
int size;
byte[] buffer = new byte[2048];
ByteArrayOutputStream baos =
new ByteArrayOutputStream(buffer.length);
while ((size = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, size);
}
String content = baos.toString();
theLogger.finest("build status: " + content);
Map json = (Map)JSONReader.read(content);
result = (String)json.get("result");
} finally {
is.close();
}
Thread.sleep(1000);
}
theLogger.finest("build result: " + result);
buildURL = new URL(result);
} catch (InterruptedException ie) {
throw new IOException("Thread interrupted. Did not obtain build result.");
}
return buildURL;
}
private Map<String,Object> analyzeWorkspace(IUser user, String requestURL) throws IOException {
IVResource[] files = user.findFiles("*.html", false, true);
HttpClient client = new HttpClient();
PostMethod method;
Map<String,Object> result = null;
String userID = user.getUserID();
theLogger.finest("analyzeWorkspace: number of files: " + files.length);
for (int i = 0; i < files.length; i++) {
if (files[i].isVirtual()) {
theLogger.finest("isVirtual name="+files[i].getPath());
continue;
}
method = new PostMethod(buildBase + "/api/dependencies");
try {
String url = new URL(new URL(requestURL), "/maqetta/user/" + userID + "/ws/workspace/" + files[i].getPath()).toExternalForm();
theLogger.finest("build.dojotoolkit.org: Analyse url="+url);
Part[] parts = {
new StringPart("value", url, "utf-8"),
new StringPart("type", "URL")
};
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
int statusCode = client.executeMethod(method);
String body = method.getResponseBodyAsString();
if (statusCode != HttpStatus.SC_OK) {
throw new IOException(buildBase + "/api/dependencies: Analyse failed: " + method.getStatusLine() + "\n" + body);
}
int start = body.indexOf("<textarea>");
int end = body.indexOf("</textarea>");
if (start == -1 || end == -1) {
throw new IOException(buildBase + "/api/dependencies: unable to parse output: " + body);
}
String content = body.substring(start + 10, end);
theLogger.finest("build.dojotoolkit.org: Analyse result="+ content);
Map<String,Object> dependencies = (Map)JSONReader.read(content);
if (result == null) {
result = dependencies;
} else {
List<String> requiredDojoModules = (List)result.get("requiredDojoModules");
List<String> additionalModules = (List)dependencies.get("requiredDojoModules");
// TODO: Does Java provide a better way to merge lists? Sets? Use an Iterator here?
for(int j = 0; j < additionalModules.size(); j++) {
String additionalModule = additionalModules.get(j);
if (!requiredDojoModules.contains(additionalModule)) {
requiredDojoModules.add(additionalModule);
theLogger.finest("add "+additionalModule);
}
}
}
} finally {
method.releaseConnection();
}
}
return result;
}
private String requestBuild(Map<String,Object> dependencies) throws IOException {
JSONWriter jsonWriter = new JSONWriter(false);
jsonWriter/*.startObject()*/
.addField("optimise", "shrinksafe")
.addField("cdn", "none")
.addField("platforms", "all")
.addField("themes", "claro")
.addField("cssOptimise", "comments");
jsonWriter.addFieldName("packages").startArray();
jsonWriter.startObject().addField("name", "dojo").addField("version","1.8.0").endObject();
//TODO: add supplemental packages like maqetta.*
// jsonWriter.startObject().addField("name", supplemental).addField("version","1.0.0").endObject();
jsonWriter.endArray();
jsonWriter.addFieldName("layers").startArray();
jsonWriter.startObject();
jsonWriter.addField("name", "dojo.js");
jsonWriter.addFieldName("modules");
jsonWriter.startArray();
List<String> requiredDojoModules = (List)dependencies.get("requiredDojoModules");
for(int i = 0; i < requiredDojoModules.size(); i++) {
jsonWriter.startObject();
jsonWriter.addField("name", (String)requiredDojoModules.get(i));
jsonWriter.addField("package", "dojo");
jsonWriter.endObject();
}
jsonWriter.endArray();
jsonWriter.endObject();
jsonWriter.endArray();
// jsonWriter.endObject();
String content = jsonWriter.getJSON();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(buildBase + "/api/build");
theLogger.finest("/api/build: " + content);
try {
method.setRequestEntity(new StringRequestEntity(content, "application/json", "utf-8"));
int statusCode = client.executeMethod(method);
String json = method.getResponseBodyAsString();
theLogger.finest("/api/build response: " + json);
if (statusCode != HttpStatus.SC_ACCEPTED && statusCode != HttpStatus.SC_OK) {
throw new IOException(buildBase + "/api/build failed with status: " + statusCode + "\n" + json);
}
Map status = (Map)JSONReader.read(json);
String statusLink = (String)status.get("buildStatusLink");
if (statusLink == null) {
throw new IOException(buildBase + "/api/build failed with error: " + (String)status.get("error"));
}
return statusLink;
} finally {
method.releaseConnection();
}
}
private void transferBuildStream(URL resultURL, String dirString, ZipOutputStream zos) throws IOException {
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(resultURL.openStream()));
ZipEntry entry;
byte[] readBuffer = new byte[2156];
int bytesIn;
try {
while ((entry = zis.getNextEntry()) != null) {
String pathString = dirString.concat(entry.getName());
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(new ZipEntry(pathString));
// now write the content of the file to the ZipOutputStream
while ((bytesIn = zis.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesIn);
}
}
} finally {
zis.close();
}
}
private String sanitizeFileName(String fileName) {
if (fileName == null || fileName.equals("")) {
fileName = "workspace1.zip";
}
fileName = fileName.replaceAll(DOWNLOAD_FILE_REPLACE_REGEXP, "_");
return fileName;
}
private boolean addEntry(String path){
for(int i=0;i<this.zippedEntries.size();i++){
String entry = (String)zippedEntries.get(i);
if(entry.compareTo(path)==0) return false;
}
zippedEntries.add(path);
return true;
}
private void zipLibs(List libs, IPath root, ZipOutputStream zos, boolean useSource) throws IOException{
for (int i = 0; i < libs.size(); i++) {
Map libEntry = (Map) libs.get(i);
String id = (String) libEntry.get("id");
String version = (String) libEntry.get("version");
String path = (String) libEntry.get("root");
Library lib = ServerManager.getServerManager().getLibraryManager().getLibrary(id, version);
boolean sourceLibrary = (lib.getSourcePath()!=null && useSource);
IVResource libResource = new VLibraryResource(lib, lib.getURL("", sourceLibrary),path, "",sourceLibrary);
zipDir(libResource,root, zos, true);
}
}
private void zipDir(IVResource zipDir, IPath root, ZipOutputStream zos, boolean includeLibs) throws IOException {
IVResource[] dirList = zipDir.listFiles();
if(!includeLibs && zipDir instanceof VLibraryResource)
return;
zipFiles(dirList, root, zos,includeLibs);
}
private void zipFiles(IVResource[] files, IPath root, ZipOutputStream zos, boolean includeLibs) throws IOException {
byte[] readBuffer = new byte[2156];
int bytesIn;
// loop through dirList, and zip the files
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
zipDir(files[i], root, zos,includeLibs);
continue;
}
if(!includeLibs && files[i] instanceof VLibraryResource)
continue;
IPath filePath = new Path(files[i].getPath());
String pathString = filePath.removeFirstSegments(filePath.matchingFirstSegments(root)).toString();
if(pathString==null) return;
/* remove leading characters that confuse and anger windows built in archive util */
if(pathString.length() > 1 && pathString.indexOf("./")==0)
pathString = pathString.substring(2);
if(!addEntry(pathString)) continue;
String dirString = pathString.substring(0, pathString.lastIndexOf('/') + 1);
if (this.buildURL != null && files[i].getPath().equals("lib/dojo/dojo/dojo.js")) {
// substitute built version of dojo.js provided by the webservice, along with associated generated layers like nls
transferBuildStream(this.buildURL, dirString, zos);
} else {
// copy stream to zip directly
InputStream is = null;
try {
is = files[i].getInputStreem();
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(new ZipEntry(pathString));
// now write the content of the file to the ZipOutputStream
while ((bytesIn = is.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesIn);
}
} finally {
// close the Stream
if (is != null) is.close();
files[i].removeWorkingCopy();
}
}
}
}
}
| true | true | public void handleCommand(HttpServletRequest req, HttpServletResponse resp, IUser user) throws IOException {
// SECURITY, VALIDATION
// 'fileName': XXX not validated
// 'resources': contents eventually checked by User.getResource()
// 'libs': XXX validated?
// 'root': XXX not validated
if (user == null) {
return;
}
/* keep track of things we've added */
zippedEntries = new Vector<String>();
String path = req.getParameter("fileName");
path = sanitizeFileName(path);
String res = req.getParameter("resources");
String libs = req.getParameter("libs");
String root = req.getParameter("root");
String build = req.getParameter("build");
boolean useFullSource = "1".equals(req.getParameter("fullsource"));
if (build != null){
//TODO: should put this in a separate Thread
this.buildURL = getBuildURL(user, req.getRequestURL().toString());
}
ArrayList o = (ArrayList) JSONReader.read(res);
List lib = null;
boolean includeLibs = true;
if(libs!=null){
lib = (List) JSONReader.read(libs);
includeLibs= false;
}
String[] resources = (String[]) o.toArray(new String[o.size()]);
IVResource[] files = new IVResource[resources.length];
for (int i = 0; i < files.length; i++) {
files[i] = user.getResource(resources[i]);
}
try {
resp.setContentType("application/x-download");
resp.setHeader("Content-Disposition", "attachment; filename=" + path);
ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
IPath rootPath = new Path(root);
zipFiles(files, rootPath, zos, includeLibs);
if(lib!=null) zipLibs(lib, rootPath, zos, useFullSource);
zos.close();
// responseString="OK";
} catch (IOException e) {
responseString = "Error creating download file : " + e;
} finally {
resp.getOutputStream().close();
}
}
| public void handleCommand(HttpServletRequest req, HttpServletResponse resp, IUser user) throws IOException {
// SECURITY, VALIDATION
// 'fileName': XXX not validated
// 'resources': contents eventually checked by User.getResource()
// 'libs': XXX validated?
// 'root': XXX not validated
if (user == null) {
return;
}
/* keep track of things we've added */
zippedEntries = new Vector<String>();
String path = req.getParameter("fileName");
path = sanitizeFileName(path);
String res = req.getParameter("resources");
String libs = req.getParameter("libs");
String root = req.getParameter("root");
String build = req.getParameter("build");
boolean useFullSource = "1".equals(req.getParameter("fullsource"));
if (build != null){
//TODO: should put this in a separate Thread
this.buildURL = getBuildURL(user, req.getRequestURL().toString());
}
ArrayList o = (ArrayList) JSONReader.read(res);
List lib = null;
boolean includeLibs = true;
if(libs!=null){
lib = (List) JSONReader.read(libs);
includeLibs= false;
}
String[] resources = (String[]) o.toArray(new String[o.size()]);
IVResource[] files = new IVResource[resources.length];
for (int i = 0; i < files.length; i++) {
files[i] = user.getResource(resources[i]);
}
try {
resp.setContentType("application/x-download");
resp.setHeader("Content-Disposition", "attachment; filename=" + path);
ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
IPath rootPath = new Path(root);
zipFiles(files, rootPath, zos, includeLibs);
if(lib!=null) zipLibs(lib, rootPath, zos, useFullSource);
zos.close();
// responseString="OK";
} catch (IOException e) {
responseString = "Error creating download file : " + e;
} finally {
try {
resp.getOutputStream().close();
} catch (java.io.EOFException eof) {
// User cancelled download
}
}
}
|
diff --git a/eapli.expensemanager/src/Presentation/ExpenseRegisterUI.java b/eapli.expensemanager/src/Presentation/ExpenseRegisterUI.java
index 6368eda..7e26d54 100644
--- a/eapli.expensemanager/src/Presentation/ExpenseRegisterUI.java
+++ b/eapli.expensemanager/src/Presentation/ExpenseRegisterUI.java
@@ -1,75 +1,76 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Presentation;
import Controllers.ExpenseRegisterController;
import Model.PayMode;
import Model.TypeOfExpense;
import Persistence.ExpenseRepository;
import eapli.util.Console;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
*
* @author Paulo Gandra Sousa
*/
class ExpenseRegisterUI {
public void mainLoop() {
System.out.println("* * * REGISTER AN EXPENSE * * *\n");
double value = Console.readDouble("Amount:");
BigDecimal amount = new BigDecimal(value);
System.out.println("Select type of expense");
ExpenseRepository eR = new ExpenseRepository();
List<TypeOfExpense> lista = new ArrayList<TypeOfExpense>();
lista = eR.getListTExpense();
int type; /* Index of type expense */
if(lista.size() > 0)
{
for(int i = 0; i < lista.size(); i++)
{
System.out.println(i+1+":"+lista.get(i));
}
- type = Console.readInteger("Select index:");
+ type = Console.readInteger("Select index:");
+ type--;
}else{
String op;
op = Console.readLine("Do not have any type of expense created, want to creat? [y]/[n]");
while (!op.equalsIgnoreCase("y") && !op.equalsIgnoreCase("n"))
{
op = Console.readLine("Select correct option [y]/[n]");
}
if(op.equalsIgnoreCase("y"))
{
TypeOfExpenseUI uiTE = new TypeOfExpenseUI();
uiTE.mainLoop();
type = eR.getListTExpense().size() - 1;
}else{
System.out.println("Do not possible insert a expense without first create a type of expense");
System.out.println("This option will be exit!\n\n");
return;
}
}
Date date = Console.readDate("Data da Despesa: \"dd-MM-yyyy\"");
//PayMode pM = new PayMode();//Input tipo de pagamento
//Input detalhes de pagamento
String what = Console.readLine("Comentário:");
ExpenseRegisterController controller = new ExpenseRegisterController();
controller.registerExpense(amount,lista.get(type),date,null,what);
System.out.println("Despesa guardada com sucesso");
}
}
| true | true | public void mainLoop() {
System.out.println("* * * REGISTER AN EXPENSE * * *\n");
double value = Console.readDouble("Amount:");
BigDecimal amount = new BigDecimal(value);
System.out.println("Select type of expense");
ExpenseRepository eR = new ExpenseRepository();
List<TypeOfExpense> lista = new ArrayList<TypeOfExpense>();
lista = eR.getListTExpense();
int type; /* Index of type expense */
if(lista.size() > 0)
{
for(int i = 0; i < lista.size(); i++)
{
System.out.println(i+1+":"+lista.get(i));
}
type = Console.readInteger("Select index:");
}else{
String op;
op = Console.readLine("Do not have any type of expense created, want to creat? [y]/[n]");
while (!op.equalsIgnoreCase("y") && !op.equalsIgnoreCase("n"))
{
op = Console.readLine("Select correct option [y]/[n]");
}
if(op.equalsIgnoreCase("y"))
{
TypeOfExpenseUI uiTE = new TypeOfExpenseUI();
uiTE.mainLoop();
type = eR.getListTExpense().size() - 1;
}else{
System.out.println("Do not possible insert a expense without first create a type of expense");
System.out.println("This option will be exit!\n\n");
return;
}
}
Date date = Console.readDate("Data da Despesa: \"dd-MM-yyyy\"");
//PayMode pM = new PayMode();//Input tipo de pagamento
//Input detalhes de pagamento
String what = Console.readLine("Comentário:");
ExpenseRegisterController controller = new ExpenseRegisterController();
controller.registerExpense(amount,lista.get(type),date,null,what);
System.out.println("Despesa guardada com sucesso");
}
| public void mainLoop() {
System.out.println("* * * REGISTER AN EXPENSE * * *\n");
double value = Console.readDouble("Amount:");
BigDecimal amount = new BigDecimal(value);
System.out.println("Select type of expense");
ExpenseRepository eR = new ExpenseRepository();
List<TypeOfExpense> lista = new ArrayList<TypeOfExpense>();
lista = eR.getListTExpense();
int type; /* Index of type expense */
if(lista.size() > 0)
{
for(int i = 0; i < lista.size(); i++)
{
System.out.println(i+1+":"+lista.get(i));
}
type = Console.readInteger("Select index:");
type--;
}else{
String op;
op = Console.readLine("Do not have any type of expense created, want to creat? [y]/[n]");
while (!op.equalsIgnoreCase("y") && !op.equalsIgnoreCase("n"))
{
op = Console.readLine("Select correct option [y]/[n]");
}
if(op.equalsIgnoreCase("y"))
{
TypeOfExpenseUI uiTE = new TypeOfExpenseUI();
uiTE.mainLoop();
type = eR.getListTExpense().size() - 1;
}else{
System.out.println("Do not possible insert a expense without first create a type of expense");
System.out.println("This option will be exit!\n\n");
return;
}
}
Date date = Console.readDate("Data da Despesa: \"dd-MM-yyyy\"");
//PayMode pM = new PayMode();//Input tipo de pagamento
//Input detalhes de pagamento
String what = Console.readLine("Comentário:");
ExpenseRegisterController controller = new ExpenseRegisterController();
controller.registerExpense(amount,lista.get(type),date,null,what);
System.out.println("Despesa guardada com sucesso");
}
|
diff --git a/web/src/sirius/web/services/ServiceCall.java b/web/src/sirius/web/services/ServiceCall.java
index 38ab458..4c3611b 100644
--- a/web/src/sirius/web/services/ServiceCall.java
+++ b/web/src/sirius/web/services/ServiceCall.java
@@ -1,98 +1,99 @@
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.web.services;
import sirius.kernel.async.CallContext;
import sirius.kernel.commons.Strings;
import sirius.kernel.commons.Value;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.HandledException;
import sirius.kernel.health.Log;
import sirius.kernel.xml.StructuredOutput;
import sirius.web.http.WebContext;
import java.util.Arrays;
/**
* Provides access to the underlying request of a call to a {@link StructuredService}
*
* @author Andreas Haufler ([email protected])
* @since 2013/11
*/
public abstract class ServiceCall {
protected static Log LOG = Log.get("services");
protected WebContext ctx;
protected ServiceCall(WebContext ctx) {
this.ctx = ctx;
}
public void handle(String errorCode, Throwable error) {
HandledException he = Exceptions.handle(LOG, error);
StructuredOutput out = createOutput();
out.beginResult();
out.property("success", false);
+ out.property("error", true);
out.property("message", he.getMessage());
Throwable cause = error.getCause();
while (cause != null && cause.getCause() != null && !cause.getCause().equals(cause)) {
cause = cause.getCause();
}
if (cause == null) {
cause = error;
}
out.property("type", cause.getClass().getName());
if (Strings.isFilled(errorCode)) {
out.property("code", errorCode);
} else {
out.property("code", "ERROR");
}
out.property("flow", CallContext.getCurrent().getMDCValue(CallContext.MDC_FLOW));
out.endResult();
}
public WebContext getContext() {
return ctx;
}
public Value get(String... keys) {
for (String key : keys) {
Value result = ctx.get(key);
if (result.isFilled()) {
return result;
}
}
return Value.of(null);
}
public Value require(String... keys) {
for (String key : keys) {
Value result = ctx.get(key);
if (result.isFilled()) {
return result;
}
}
throw Exceptions.createHandled()
.withSystemErrorMessage(
"A required parameter was not filled. Provide at least one value for: %s",
Arrays.asList(keys))
.handle();
}
public void invoke(StructuredService serv) {
try {
serv.call(this, createOutput());
} catch (Throwable t) {
handle(null, t);
}
}
protected abstract StructuredOutput createOutput();
}
| true | true | public void handle(String errorCode, Throwable error) {
HandledException he = Exceptions.handle(LOG, error);
StructuredOutput out = createOutput();
out.beginResult();
out.property("success", false);
out.property("message", he.getMessage());
Throwable cause = error.getCause();
while (cause != null && cause.getCause() != null && !cause.getCause().equals(cause)) {
cause = cause.getCause();
}
if (cause == null) {
cause = error;
}
out.property("type", cause.getClass().getName());
if (Strings.isFilled(errorCode)) {
out.property("code", errorCode);
} else {
out.property("code", "ERROR");
}
out.property("flow", CallContext.getCurrent().getMDCValue(CallContext.MDC_FLOW));
out.endResult();
}
| public void handle(String errorCode, Throwable error) {
HandledException he = Exceptions.handle(LOG, error);
StructuredOutput out = createOutput();
out.beginResult();
out.property("success", false);
out.property("error", true);
out.property("message", he.getMessage());
Throwable cause = error.getCause();
while (cause != null && cause.getCause() != null && !cause.getCause().equals(cause)) {
cause = cause.getCause();
}
if (cause == null) {
cause = error;
}
out.property("type", cause.getClass().getName());
if (Strings.isFilled(errorCode)) {
out.property("code", errorCode);
} else {
out.property("code", "ERROR");
}
out.property("flow", CallContext.getCurrent().getMDCValue(CallContext.MDC_FLOW));
out.endResult();
}
|
diff --git a/htroot/Surftips.java b/htroot/Surftips.java
index ed87a08ee..d9934f468 100644
--- a/htroot/Surftips.java
+++ b/htroot/Surftips.java
@@ -1,341 +1,345 @@
// Surftips.java
// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 2006 on http://www.anomic.de
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $
// $LastChangedRevision: 1986 $
// $LastChangedBy: orbiter $
//
// LICENSE
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import de.anomic.http.httpHeader;
import de.anomic.net.URL;
import de.anomic.plasma.plasmaURL;
import de.anomic.kelondro.kelondroMScoreCluster;
import de.anomic.kelondro.kelondroRow;
import de.anomic.kelondro.kelondroNaturalOrder;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.urlPattern.plasmaURLPattern;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.tools.crypt;
import de.anomic.tools.nxTools;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.yacyNewsRecord;
import de.anomic.yacy.yacySeed;
public class Surftips {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = ((post == null) || (!authenticated)) ? 0 : post.getInt("display", 0);
prop.put("display", display);
boolean showScore = ((post != null) && (post.containsKey("score")));
// access control
boolean publicPage = sb.getConfigBool("publicSurftips", true);
boolean authorizedAccess = sb.verifyAuthentication(header, false);
if ((post != null) && (post.containsKey("publicPage"))) {
if (!authorizedAccess) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
publicPage = post.get("publicPage", "0").equals("1");
sb.setConfig("publicSurftips", publicPage);
}
if ((publicPage) || (authorizedAccess)) {
// read voting
String hash;
if ((post != null) && ((hash = post.get("voteNegative", null)) != null)) {
if (!sb.verifyAuthentication(header, false)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// make new news message with voting
HashMap map = new HashMap();
map.put("urlhash", hash);
map.put("vote", "negative");
map.put("refid", post.get("refid", ""));
yacyCore.newsPool.publishMyNews(new yacyNewsRecord(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map));
}
if ((post != null) && ((hash = post.get("votePositive", null)) != null)) {
if (!sb.verifyAuthentication(header, false)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// make new news message with voting
HashMap map = new HashMap();
map.put("urlhash", hash);
map.put("url", crypt.simpleDecode(post.get("url", ""), null));
map.put("title", crypt.simpleDecode(post.get("title", ""), null));
map.put("description", crypt.simpleDecode(post.get("description", ""), null));
map.put("vote", "positive");
map.put("refid", post.get("refid", ""));
map.put("comment", post.get("comment", ""));
yacyCore.newsPool.publishMyNews(new yacyNewsRecord(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map));
}
// create surftips
HashMap negativeHashes = new HashMap(); // a mapping from an url hash to Integer (count of votes)
HashMap positiveHashes = new HashMap(); // a mapping from an url hash to Integer (count of votes)
accumulateVotes(negativeHashes, positiveHashes, yacyNewsPool.INCOMING_DB);
//accumulateVotes(negativeHashes, positiveHashes, yacyNewsPool.OUTGOING_DB);
//accumulateVotes(negativeHashes, positiveHashes, yacyNewsPool.PUBLISHED_DB);
kelondroMScoreCluster ranking = new kelondroMScoreCluster(); // score cluster for url hashes
kelondroRow rowdef = new kelondroRow("String url-255, String title-120, String description-120, String refid-" + (yacyCore.universalDateShortPattern.length() + 12), kelondroNaturalOrder.naturalOrder, 0);
HashMap surftips = new HashMap(); // a mapping from an url hash to a kelondroRow.Entry with display properties
accumulateSurftips(surftips, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.INCOMING_DB);
//accumulateSurftips(surftips, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.OUTGOING_DB);
//accumulateSurftips(surftips, ranking, rowdef, negativeHashes, positiveHashes, yacyNewsPool.PUBLISHED_DB);
// read out surftipp array and create property entries
Iterator k = ranking.scores(false);
int i = 0;
kelondroRow.Entry row;
String url, urlhash, refid, title, description;
boolean voted;
while (k.hasNext()) {
urlhash = (String) k.next();
if (urlhash == null) continue;
row = (kelondroRow.Entry) surftips.get(urlhash);
if (row == null) continue;
url = row.getColString(0, null);
try{
if(plasmaSwitchboard.urlBlacklist.isListed(plasmaURLPattern.BLACKLIST_SURFTIPS ,new URL(url)))
continue;
}catch(MalformedURLException e){continue;};
title = row.getColString(1,"UTF-8");
description = row.getColString(2,"UTF-8");
if ((url == null) || (title == null) || (description == null)) continue;
refid = row.getColString(3, null);
voted = false;
try {
voted = (yacyCore.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, "refid", refid) != null) ||
(yacyCore.newsPool.getSpecific(yacyNewsPool.PUBLISHED_DB, yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, "refid", refid) != null);
} catch (IOException e) {
e.printStackTrace();
}
prop.put("surftips_results_" + i + "_authorized", (authenticated) ? 1 : 0);
prop.put("surftips_results_" + i + "_authorized_recommend", (voted) ? 0 : 1);
prop.put("surftips_results_" + i + "_authorized_recommend_urlhash", urlhash);
prop.put("surftips_results_" + i + "_authorized_recommend_refid", refid);
prop.putASIS("surftips_results_" + i + "_authorized_recommend_url", crypt.simpleEncode(url, null, 'b'));
prop.putASIS("surftips_results_" + i + "_authorized_recommend_title", crypt.simpleEncode(title, null, 'b'));
prop.putASIS("surftips_results_" + i + "_authorized_recommend_description", crypt.simpleEncode(description, null, 'b'));
prop.put("surftips_results_" + i + "_authorized_recommend_display", display);
prop.put("surftips_results_" + i + "_authorized_recommend_showScore", (showScore ? 1 : 0));
prop.put("surftips_results_" + i + "_authorized_urlhash", urlhash);
prop.put("surftips_results_" + i + "_url", de.anomic.data.htmlTools.replaceXMLEntities(url));
prop.put("surftips_results_" + i + "_urlname", nxTools.shortenURLString(url, 60));
prop.put("surftips_results_" + i + "_urlhash", urlhash);
prop.put("surftips_results_" + i + "_title", (showScore) ? ("(" + ranking.getScore(urlhash) + ") " + title) : title);
prop.put("surftips_results_" + i + "_description", description);
i++;
if (i >= 50) break;
}
prop.put("surftips_results", i);
prop.put("surftips", 1);
} else {
prop.put("surftips", 0);
}
return prop;
}
private static int timeFactor(Date created) {
return (int) Math.max(0, 10 - ((System.currentTimeMillis() - created.getTime()) / 24 / 60 / 60 / 1000));
}
private static void accumulateVotes(HashMap negativeHashes, HashMap positiveHashes, int dbtype) {
int maxCount = Math.min(1000, yacyCore.newsPool.size(dbtype));
yacyNewsRecord record;
for (int j = 0; j < maxCount; j++) try {
record = yacyCore.newsPool.get(dbtype, j);
if (record == null) continue;
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD)) {
String urlhash = record.attribute("urlhash", "");
String vote = record.attribute("vote", "");
int factor = ((dbtype == yacyNewsPool.OUTGOING_DB) || (dbtype == yacyNewsPool.PUBLISHED_DB)) ? 2 : 1;
if (vote.equals("negative")) {
Integer i = (Integer) negativeHashes.get(urlhash);
if (i == null) negativeHashes.put(urlhash, new Integer(factor));
else negativeHashes.put(urlhash, new Integer(i.intValue() + factor));
}
if (vote.equals("positive")) {
Integer i = (Integer) positiveHashes.get(urlhash);
if (i == null) positiveHashes.put(urlhash, new Integer(factor));
else positiveHashes.put(urlhash, new Integer(i.intValue() + factor));
}
}
} catch (IOException e) {e.printStackTrace();}
}
private static void accumulateSurftips(
HashMap surftips, kelondroMScoreCluster ranking, kelondroRow rowdef,
HashMap negativeHashes, HashMap positiveHashes, int dbtype) {
int maxCount = Math.min(1000, yacyCore.newsPool.size(dbtype));
yacyNewsRecord record;
String url = "", urlhash;
kelondroRow.Entry entry;
int score = 0;
Integer vote;
for (int j = 0; j < maxCount; j++) try {
record = yacyCore.newsPool.get(dbtype, j);
if (record == null) continue;
entry = null;
if (record.category().equals(yacyNewsPool.CATEGORY_CRAWL_START)) {
String intention = record.attribute("intention", "");
url = record.attribute("startURL", "");
+ if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
((intention.length() == 0) ? record.attribute("startURL", "") : intention).getBytes(),
("Crawl Start Point").getBytes("UTF-8"),
record.id().getBytes()
});
score = 2 + Math.min(10, intention.length() / 4) + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_PROFILE_UPDATE)) {
url = record.attribute("homepage", "");
- if ((url == null) || (url.length() < 12)) continue;
+ if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
("Home Page of " + record.attribute("nickname", "")).getBytes("UTF-8"),
("Profile Update").getBytes("UTF-8"),
record.id().getBytes()
});
score = 1 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_BOOKMARK_ADD)) {
url = record.attribute("url", "");
+ if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("title", "")).getBytes("UTF-8"),
("Bookmark: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 8 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_ADD)) {
url = record.attribute("url", "");
+ if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("title", "")).getBytes("UTF-8"),
("Surf Tipp: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 5 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD)) {
if (!(record.attribute("vote", "negative").equals("positive"))) continue;
url = record.attribute("url", "");
+ if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
record.attribute("title", "").getBytes("UTF-8"),
record.attribute("description", "").getBytes("UTF-8"),
record.attribute("refid", "").getBytes()
});
score = 5 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_WIKI_UPDATE)) {
yacySeed seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
if (seed != null) {
url = "http://" + seed.getPublicAddress() + "/Wiki.html?page=" + record.attribute("page", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("author", "Anonymous") + ": " + record.attribute("page", "")).getBytes("UTF-8"),
("Wiki Update: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 4 + timeFactor(record.created());
}
}
if (record.category().equals(yacyNewsPool.CATEGORY_BLOG_ADD)) {
yacySeed seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
if (seed != null) {
url = "http://" + seed.getPublicAddress() + "/Blog.html?page=" + record.attribute("page", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("author", "Anonymous") + ": " + record.attribute("page", "")).getBytes("UTF-8"),
("Blog Entry: " + record.attribute("subject", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 4 + timeFactor(record.created());
}
}
// add/subtract votes and write record
if (entry != null) {
urlhash = plasmaURL.urlHash(url);
if (urlhash == null)
urlhash=plasmaURL.urlHash("http://"+url);
if(urlhash==null){
System.out.println("Surftips: bad url '" + url + "' from news record " + record.toString());
continue;
}
if ((vote = (Integer) negativeHashes.get(urlhash)) != null) {
score = Math.max(0, score - vote.intValue()); // do not go below zero
}
if ((vote = (Integer) positiveHashes.get(urlhash)) != null) {
score += 2 * vote.intValue();
}
// consider double-entries
if (surftips.containsKey(urlhash)) {
ranking.addScore(urlhash, score);
} else {
ranking.setScore(urlhash, score);
surftips.put(urlhash, entry);
}
}
} catch (IOException e) {e.printStackTrace();}
}
}
| false | true | private static void accumulateSurftips(
HashMap surftips, kelondroMScoreCluster ranking, kelondroRow rowdef,
HashMap negativeHashes, HashMap positiveHashes, int dbtype) {
int maxCount = Math.min(1000, yacyCore.newsPool.size(dbtype));
yacyNewsRecord record;
String url = "", urlhash;
kelondroRow.Entry entry;
int score = 0;
Integer vote;
for (int j = 0; j < maxCount; j++) try {
record = yacyCore.newsPool.get(dbtype, j);
if (record == null) continue;
entry = null;
if (record.category().equals(yacyNewsPool.CATEGORY_CRAWL_START)) {
String intention = record.attribute("intention", "");
url = record.attribute("startURL", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
((intention.length() == 0) ? record.attribute("startURL", "") : intention).getBytes(),
("Crawl Start Point").getBytes("UTF-8"),
record.id().getBytes()
});
score = 2 + Math.min(10, intention.length() / 4) + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_PROFILE_UPDATE)) {
url = record.attribute("homepage", "");
if ((url == null) || (url.length() < 12)) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
("Home Page of " + record.attribute("nickname", "")).getBytes("UTF-8"),
("Profile Update").getBytes("UTF-8"),
record.id().getBytes()
});
score = 1 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_BOOKMARK_ADD)) {
url = record.attribute("url", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("title", "")).getBytes("UTF-8"),
("Bookmark: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 8 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_ADD)) {
url = record.attribute("url", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("title", "")).getBytes("UTF-8"),
("Surf Tipp: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 5 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD)) {
if (!(record.attribute("vote", "negative").equals("positive"))) continue;
url = record.attribute("url", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
record.attribute("title", "").getBytes("UTF-8"),
record.attribute("description", "").getBytes("UTF-8"),
record.attribute("refid", "").getBytes()
});
score = 5 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_WIKI_UPDATE)) {
yacySeed seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
if (seed != null) {
url = "http://" + seed.getPublicAddress() + "/Wiki.html?page=" + record.attribute("page", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("author", "Anonymous") + ": " + record.attribute("page", "")).getBytes("UTF-8"),
("Wiki Update: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 4 + timeFactor(record.created());
}
}
if (record.category().equals(yacyNewsPool.CATEGORY_BLOG_ADD)) {
yacySeed seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
if (seed != null) {
url = "http://" + seed.getPublicAddress() + "/Blog.html?page=" + record.attribute("page", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("author", "Anonymous") + ": " + record.attribute("page", "")).getBytes("UTF-8"),
("Blog Entry: " + record.attribute("subject", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 4 + timeFactor(record.created());
}
}
// add/subtract votes and write record
if (entry != null) {
urlhash = plasmaURL.urlHash(url);
if (urlhash == null)
urlhash=plasmaURL.urlHash("http://"+url);
if(urlhash==null){
System.out.println("Surftips: bad url '" + url + "' from news record " + record.toString());
continue;
}
if ((vote = (Integer) negativeHashes.get(urlhash)) != null) {
score = Math.max(0, score - vote.intValue()); // do not go below zero
}
if ((vote = (Integer) positiveHashes.get(urlhash)) != null) {
score += 2 * vote.intValue();
}
// consider double-entries
if (surftips.containsKey(urlhash)) {
ranking.addScore(urlhash, score);
} else {
ranking.setScore(urlhash, score);
surftips.put(urlhash, entry);
}
}
} catch (IOException e) {e.printStackTrace();}
}
| private static void accumulateSurftips(
HashMap surftips, kelondroMScoreCluster ranking, kelondroRow rowdef,
HashMap negativeHashes, HashMap positiveHashes, int dbtype) {
int maxCount = Math.min(1000, yacyCore.newsPool.size(dbtype));
yacyNewsRecord record;
String url = "", urlhash;
kelondroRow.Entry entry;
int score = 0;
Integer vote;
for (int j = 0; j < maxCount; j++) try {
record = yacyCore.newsPool.get(dbtype, j);
if (record == null) continue;
entry = null;
if (record.category().equals(yacyNewsPool.CATEGORY_CRAWL_START)) {
String intention = record.attribute("intention", "");
url = record.attribute("startURL", "");
if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
((intention.length() == 0) ? record.attribute("startURL", "") : intention).getBytes(),
("Crawl Start Point").getBytes("UTF-8"),
record.id().getBytes()
});
score = 2 + Math.min(10, intention.length() / 4) + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_PROFILE_UPDATE)) {
url = record.attribute("homepage", "");
if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
("Home Page of " + record.attribute("nickname", "")).getBytes("UTF-8"),
("Profile Update").getBytes("UTF-8"),
record.id().getBytes()
});
score = 1 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_BOOKMARK_ADD)) {
url = record.attribute("url", "");
if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("title", "")).getBytes("UTF-8"),
("Bookmark: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 8 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_ADD)) {
url = record.attribute("url", "");
if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("title", "")).getBytes("UTF-8"),
("Surf Tipp: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 5 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD)) {
if (!(record.attribute("vote", "negative").equals("positive"))) continue;
url = record.attribute("url", "");
if (url.length() < 12) continue;
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
record.attribute("title", "").getBytes("UTF-8"),
record.attribute("description", "").getBytes("UTF-8"),
record.attribute("refid", "").getBytes()
});
score = 5 + timeFactor(record.created());
}
if (record.category().equals(yacyNewsPool.CATEGORY_WIKI_UPDATE)) {
yacySeed seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
if (seed != null) {
url = "http://" + seed.getPublicAddress() + "/Wiki.html?page=" + record.attribute("page", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("author", "Anonymous") + ": " + record.attribute("page", "")).getBytes("UTF-8"),
("Wiki Update: " + record.attribute("description", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 4 + timeFactor(record.created());
}
}
if (record.category().equals(yacyNewsPool.CATEGORY_BLOG_ADD)) {
yacySeed seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
if (seed != null) {
url = "http://" + seed.getPublicAddress() + "/Blog.html?page=" + record.attribute("page", "");
entry = rowdef.newEntry(new byte[][]{
url.getBytes(),
(record.attribute("author", "Anonymous") + ": " + record.attribute("page", "")).getBytes("UTF-8"),
("Blog Entry: " + record.attribute("subject", "")).getBytes("UTF-8"),
record.id().getBytes()
});
score = 4 + timeFactor(record.created());
}
}
// add/subtract votes and write record
if (entry != null) {
urlhash = plasmaURL.urlHash(url);
if (urlhash == null)
urlhash=plasmaURL.urlHash("http://"+url);
if(urlhash==null){
System.out.println("Surftips: bad url '" + url + "' from news record " + record.toString());
continue;
}
if ((vote = (Integer) negativeHashes.get(urlhash)) != null) {
score = Math.max(0, score - vote.intValue()); // do not go below zero
}
if ((vote = (Integer) positiveHashes.get(urlhash)) != null) {
score += 2 * vote.intValue();
}
// consider double-entries
if (surftips.containsKey(urlhash)) {
ranking.addScore(urlhash, score);
} else {
ranking.setScore(urlhash, score);
surftips.put(urlhash, entry);
}
}
} catch (IOException e) {e.printStackTrace();}
}
|
diff --git a/src/org/rascalmpl/library/vis/util/KeySym.java b/src/org/rascalmpl/library/vis/util/KeySym.java
index 5681ad9229..92f9fd23ea 100644
--- a/src/org/rascalmpl/library/vis/util/KeySym.java
+++ b/src/org/rascalmpl/library/vis/util/KeySym.java
@@ -1,129 +1,129 @@
package org.rascalmpl.library.vis.util;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.impl.fast.ValueFactory;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.rascalmpl.interpreter.IEvaluatorContext;
import org.rascalmpl.interpreter.env.Environment;
public class KeySym {
static final Type[] empty = {};
static final String[] modifiers = {"modCtrl","modCommand","modAlt","modShift"};
static final int[] modifiersSWT = {SWT.CTRL, SWT.COMMAND, SWT.ALT, SWT.SHIFT };
public static IMap toRascalModifiers(KeyEvent e,IMap prevMap,IEvaluatorContext ctx){
TypeFactory tf = TypeFactory.getInstance();
ValueFactory vf = ValueFactory.getInstance();
Environment env = ctx.getCurrentEnvt();
for(int i = 0 ; i < modifiers.length ;i++){
Type controlType = env.lookupFirstConstructor(modifiers[i],tf.tupleEmpty());
IValue cons = vf.constructor(controlType);
prevMap = prevMap.put(cons, vf.bool((e.stateMask & modifiersSWT[i]) != 0));
}
return prevMap;
}
public static IValue toRascalKey(KeyEvent e,IEvaluatorContext ctx){
TypeFactory tf = TypeFactory.getInstance();
ValueFactory vf = ValueFactory.getInstance();
Environment env = ctx.getCurrentEnvt();
if(e.keyCode >= ' ' && e.keyCode < '~'){
String keySym = "" + (char)e.keyCode;
IString keySymR = vf.string(keySym);
Type printableKeyType = env.lookupFirstConstructor("keyPrintable", tf.tupleType(tf.stringType()));
return vf.constructor(printableKeyType, keySymR);
} else {
String name = unPrintableKeyName(e);
if(name.equals("keyUnknown")){
Type unkownType = env.lookupFirstConstructor(name,tf.tupleType(tf.integerType()));
return vf.constructor(unkownType,vf.integer(e.keyCode));
} else {
Type printableKeyType = env.lookupFirstConstructor(name,tf.tupleEmpty());
return vf.constructor(printableKeyType);
}
}
}
public static String unPrintableKeyName(KeyEvent e){
switch(e.keyCode){
case SWT.ALT:
- if(e.keyLocation == SWT.LEFT) return "keyAltLeft";
- else return "keyAltRight";
+// if(e.keyCode == SWT.LEFT) return "keyAltLeft";
+ /*else*/ return "keyAltRight";
case SWT.ARROW_DOWN: return "keyArrowDown";
case SWT.ARROW_LEFT: return "keyArrowLeft";
case SWT.ARROW_RIGHT: return "keyArrowRight";
case SWT.ARROW_UP: return "keyArrowUp";
case SWT.BREAK: return "keyBreak";
case SWT.CAPS_LOCK: return "keyCapsLock";
case SWT.COMMAND:
- if(e.keyLocation == SWT.LEFT) return "keyCommandLeft";
- else return "keyCommandRight";
+// if(e.keyLocation == SWT.LEFT) return "keyCommandLeft";
+ /*else*/ return "keyCommandRight";
case SWT.CTRL:
- if(e.keyLocation == SWT.LEFT) return "keyControlLeft";
- else return "keyControlRight";
+// if(e.keyLocation == SWT.LEFT) return "keyControlLeft";
+ /*else*/ return "keyControlRight";
case SWT.END: return "keyEnd";
case SWT.F1: return "keyF1";
case SWT.F10: return "keyF10";
case SWT.F11: return "keyF11";
case SWT.F12: return "keyF12";
case SWT.F13: return "keyF13";
case SWT.F14: return "keyF14";
case SWT.F15: return "keyF15";
- case SWT.F16: return "keyF16";
- case SWT.F17: return "keyF17";
- case SWT.F18: return "keyF18";
- case SWT.F19: return "keyF19";
+// case SWT.F16: return "keyF16";
+// case SWT.F17: return "keyF17";
+// case SWT.F18: return "keyF18";
+// case SWT.F19: return "keyF19";
case SWT.F2: return "keyF2";
- case SWT.F20: return "keyF20";
+// case SWT.F20: return "keyF20";
case SWT.F3: return "keyF3";
case SWT.F4: return "keyF4";
case SWT.F5: return "keyF5";
case SWT.F6: return "keyF6";
case SWT.F7: return "keyF7";
case SWT.F8: return "keyF8";
case SWT.F9: return "keyF9";
case SWT.HELP: return "keyHelp";
case SWT.HOME: return "keyHome";
case SWT.INSERT: return "keyInsert";
case SWT.KEYPAD_0: return "keyKeypad0";
case SWT.KEYPAD_1: return "keyKeypad1";
case SWT.KEYPAD_2: return "keyKeypad2";
case SWT.KEYPAD_3: return "keyKeypad3";
case SWT.KEYPAD_4: return "keyKeypad4";
case SWT.KEYPAD_5: return "keyKeypad5";
case SWT.KEYPAD_6: return "keyKeypad6";
case SWT.KEYPAD_7: return "keyKeypad7";
case SWT.KEYPAD_8: return "keyKeypad8";
case SWT.KEYPAD_9: return "keyKeypad9";
case SWT.KEYPAD_ADD: return "keyKeypadAdd";
case SWT.KEYPAD_CR: return "keyKeypadCr";
case SWT.KEYPAD_DECIMAL: return "keyKeypadDecimal";
case SWT.KEYPAD_DIVIDE: return "keyKeypadDivide";
case SWT.KEYPAD_EQUAL: return "keyKeypadEqual";
case SWT.KEYPAD_MULTIPLY: return "keyKeypadMultiply";
case SWT.KEYPAD_SUBTRACT: return "keyKeypadSubtract";
case SWT.NUM_LOCK: return "keyNumLock";
case SWT.PAGE_DOWN: return "keyPageDown";
case SWT.PAGE_UP: return "keyPageUp";
case SWT.PAUSE: return "keyPause";
case SWT.PRINT_SCREEN: return "keyPrintScreen";
case SWT.SCROLL_LOCK: return "keyScrollLock";
case SWT.SHIFT:
- if(e.keyLocation == SWT.LEFT) return "keyShiftLeft";
- else return "keyShiftRight";
+// if(e.keyLocation == SWT.LEFT) return "keyShiftLeft";
+ /*else*/ return "keyShiftRight";
case 8 : return "keyBackSpace";
case '\t': return "keyTab";
case 13: return "keyEnter";
case 27: return "keyEscape";
default: return "keyUnknown";
}
}
}
| false | true | public static String unPrintableKeyName(KeyEvent e){
switch(e.keyCode){
case SWT.ALT:
if(e.keyLocation == SWT.LEFT) return "keyAltLeft";
else return "keyAltRight";
case SWT.ARROW_DOWN: return "keyArrowDown";
case SWT.ARROW_LEFT: return "keyArrowLeft";
case SWT.ARROW_RIGHT: return "keyArrowRight";
case SWT.ARROW_UP: return "keyArrowUp";
case SWT.BREAK: return "keyBreak";
case SWT.CAPS_LOCK: return "keyCapsLock";
case SWT.COMMAND:
if(e.keyLocation == SWT.LEFT) return "keyCommandLeft";
else return "keyCommandRight";
case SWT.CTRL:
if(e.keyLocation == SWT.LEFT) return "keyControlLeft";
else return "keyControlRight";
case SWT.END: return "keyEnd";
case SWT.F1: return "keyF1";
case SWT.F10: return "keyF10";
case SWT.F11: return "keyF11";
case SWT.F12: return "keyF12";
case SWT.F13: return "keyF13";
case SWT.F14: return "keyF14";
case SWT.F15: return "keyF15";
case SWT.F16: return "keyF16";
case SWT.F17: return "keyF17";
case SWT.F18: return "keyF18";
case SWT.F19: return "keyF19";
case SWT.F2: return "keyF2";
case SWT.F20: return "keyF20";
case SWT.F3: return "keyF3";
case SWT.F4: return "keyF4";
case SWT.F5: return "keyF5";
case SWT.F6: return "keyF6";
case SWT.F7: return "keyF7";
case SWT.F8: return "keyF8";
case SWT.F9: return "keyF9";
case SWT.HELP: return "keyHelp";
case SWT.HOME: return "keyHome";
case SWT.INSERT: return "keyInsert";
case SWT.KEYPAD_0: return "keyKeypad0";
case SWT.KEYPAD_1: return "keyKeypad1";
case SWT.KEYPAD_2: return "keyKeypad2";
case SWT.KEYPAD_3: return "keyKeypad3";
case SWT.KEYPAD_4: return "keyKeypad4";
case SWT.KEYPAD_5: return "keyKeypad5";
case SWT.KEYPAD_6: return "keyKeypad6";
case SWT.KEYPAD_7: return "keyKeypad7";
case SWT.KEYPAD_8: return "keyKeypad8";
case SWT.KEYPAD_9: return "keyKeypad9";
case SWT.KEYPAD_ADD: return "keyKeypadAdd";
case SWT.KEYPAD_CR: return "keyKeypadCr";
case SWT.KEYPAD_DECIMAL: return "keyKeypadDecimal";
case SWT.KEYPAD_DIVIDE: return "keyKeypadDivide";
case SWT.KEYPAD_EQUAL: return "keyKeypadEqual";
case SWT.KEYPAD_MULTIPLY: return "keyKeypadMultiply";
case SWT.KEYPAD_SUBTRACT: return "keyKeypadSubtract";
case SWT.NUM_LOCK: return "keyNumLock";
case SWT.PAGE_DOWN: return "keyPageDown";
case SWT.PAGE_UP: return "keyPageUp";
case SWT.PAUSE: return "keyPause";
case SWT.PRINT_SCREEN: return "keyPrintScreen";
case SWT.SCROLL_LOCK: return "keyScrollLock";
case SWT.SHIFT:
if(e.keyLocation == SWT.LEFT) return "keyShiftLeft";
else return "keyShiftRight";
case 8 : return "keyBackSpace";
case '\t': return "keyTab";
case 13: return "keyEnter";
case 27: return "keyEscape";
default: return "keyUnknown";
}
}
| public static String unPrintableKeyName(KeyEvent e){
switch(e.keyCode){
case SWT.ALT:
// if(e.keyCode == SWT.LEFT) return "keyAltLeft";
/*else*/ return "keyAltRight";
case SWT.ARROW_DOWN: return "keyArrowDown";
case SWT.ARROW_LEFT: return "keyArrowLeft";
case SWT.ARROW_RIGHT: return "keyArrowRight";
case SWT.ARROW_UP: return "keyArrowUp";
case SWT.BREAK: return "keyBreak";
case SWT.CAPS_LOCK: return "keyCapsLock";
case SWT.COMMAND:
// if(e.keyLocation == SWT.LEFT) return "keyCommandLeft";
/*else*/ return "keyCommandRight";
case SWT.CTRL:
// if(e.keyLocation == SWT.LEFT) return "keyControlLeft";
/*else*/ return "keyControlRight";
case SWT.END: return "keyEnd";
case SWT.F1: return "keyF1";
case SWT.F10: return "keyF10";
case SWT.F11: return "keyF11";
case SWT.F12: return "keyF12";
case SWT.F13: return "keyF13";
case SWT.F14: return "keyF14";
case SWT.F15: return "keyF15";
// case SWT.F16: return "keyF16";
// case SWT.F17: return "keyF17";
// case SWT.F18: return "keyF18";
// case SWT.F19: return "keyF19";
case SWT.F2: return "keyF2";
// case SWT.F20: return "keyF20";
case SWT.F3: return "keyF3";
case SWT.F4: return "keyF4";
case SWT.F5: return "keyF5";
case SWT.F6: return "keyF6";
case SWT.F7: return "keyF7";
case SWT.F8: return "keyF8";
case SWT.F9: return "keyF9";
case SWT.HELP: return "keyHelp";
case SWT.HOME: return "keyHome";
case SWT.INSERT: return "keyInsert";
case SWT.KEYPAD_0: return "keyKeypad0";
case SWT.KEYPAD_1: return "keyKeypad1";
case SWT.KEYPAD_2: return "keyKeypad2";
case SWT.KEYPAD_3: return "keyKeypad3";
case SWT.KEYPAD_4: return "keyKeypad4";
case SWT.KEYPAD_5: return "keyKeypad5";
case SWT.KEYPAD_6: return "keyKeypad6";
case SWT.KEYPAD_7: return "keyKeypad7";
case SWT.KEYPAD_8: return "keyKeypad8";
case SWT.KEYPAD_9: return "keyKeypad9";
case SWT.KEYPAD_ADD: return "keyKeypadAdd";
case SWT.KEYPAD_CR: return "keyKeypadCr";
case SWT.KEYPAD_DECIMAL: return "keyKeypadDecimal";
case SWT.KEYPAD_DIVIDE: return "keyKeypadDivide";
case SWT.KEYPAD_EQUAL: return "keyKeypadEqual";
case SWT.KEYPAD_MULTIPLY: return "keyKeypadMultiply";
case SWT.KEYPAD_SUBTRACT: return "keyKeypadSubtract";
case SWT.NUM_LOCK: return "keyNumLock";
case SWT.PAGE_DOWN: return "keyPageDown";
case SWT.PAGE_UP: return "keyPageUp";
case SWT.PAUSE: return "keyPause";
case SWT.PRINT_SCREEN: return "keyPrintScreen";
case SWT.SCROLL_LOCK: return "keyScrollLock";
case SWT.SHIFT:
// if(e.keyLocation == SWT.LEFT) return "keyShiftLeft";
/*else*/ return "keyShiftRight";
case 8 : return "keyBackSpace";
case '\t': return "keyTab";
case 13: return "keyEnter";
case 27: return "keyEscape";
default: return "keyUnknown";
}
}
|
diff --git a/TextureAtlas.java b/TextureAtlas.java
index c032e83..5514eac 100644
--- a/TextureAtlas.java
+++ b/TextureAtlas.java
@@ -1,468 +1,468 @@
package rokon;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* TextureAtlas is a way of optimizing the use of multiple textures in OpenGL.
* OpenGL stores each of its textures as seperate images on the hardware, and to render
* one of these requires a command to tell OpenGL to scrap the image it has loaded, and
* load up a new image into its immediate memory. It makes more sense to provide OpenGL
* with one large texture, so it never has to change between which it has selected, and
* for us to simply choose which parts of that texture we place onto a Sprite. This is
* called texture mapping.
*
* TextureAtlas uses a very basic, and rather inefficient, largest-first bin packing
* algorithm to squeeze all your textures and fonts on to one large image. This will be
* improved for future versions.
*
* TextureAtlas provides OpenGL with a power-of-two sized texture (2,4,8,16,32 etc.) as
* this is needed for the hardware to work efficiently. It is possible for you however
* to load Texture's of any dimenion into the atlas, and Rokon will clip it for you.
*/
public class TextureAtlas {
public final static int MAX_TEXTURES = 5;
public static boolean ready = false;
public static boolean readyToLoad = false;
public static HashMap<Integer, HashMap<Integer, Texture>> _textureSets = new HashMap<Integer, HashMap<Integer, Texture>>();;
public static HashMap<Integer, Texture> _texture = new HashMap<Integer, Texture>();;
private static int _textureCount = 0;
private static int _textureSetCount = 0;
private static Bitmap[] _bmp = new Bitmap[MAX_TEXTURES];
public static int[] texId = new int[MAX_TEXTURES];
private static int _greatestWidth;
private static int _width;
private static int[] _height = new int[MAX_TEXTURES];
public static int currentAtlas = 0;
public static String idString = "";
public static Paint paint = new Paint();
public static boolean reloadTextures = false;
public static HashSet<Integer> reloadTextureIndices = new HashSet<Integer>();
/**
* Resets the TextureAtlas ready to load another set of textures.
*/
public static void reset() {
_texture = new HashMap<Integer, Texture>();
_textureCount = 0;
readyToLoad = false;
ready = false;
idString = "";
System.gc();
}
/**
* @return the width of the texture atlas
*/
public static int getWidth() {
return _width;
}
/**
* @return the height of the texture atlas
*/
public static int getHeight(int tex) {
try {
return _height[tex];
} catch (Exception e ) {
e.printStackTrace();
Debug.print("EXCEPTION GETTING " + tex);
return 0;
}
}
/**
* Creates a Texture from the /assets/ folder
* @param path path to the file in /assets/
* @return Texture pointer
*/
public static Texture createTexture(String path) {
try {
Bitmap bmp = BitmapFactory.decodeStream(Rokon.getRokon().getActivity().getAssets().open(path));
Texture texture = new Texture(path, bmp);
if(bmp.getWidth() > _greatestWidth)
_greatestWidth = bmp.getWidth();
_texture.put(_textureCount, texture);
_textureCount++;
idString += path + "/" + bmp.getWidth() + "/" + bmp.getHeight();
bmp.recycle();
//System.gc();
return texture;
} catch (IOException e) {
Debug.print("CANNOT FIND " + path);
e.printStackTrace();
}
return null;
}
/**
* Creates a Texture and puts it onto the atlas
* @param resourceId reference to a drawable resource file, as described in R.java
* @return NULL if failed
*/
public static Texture createTextureFromResource(int resourceId) {
Bitmap bmp = BitmapFactory.decodeResource(Rokon.getRokon().getActivity().getResources(), resourceId);
Texture t = createTextureFromBitmap(bmp);
return t;
}
/**
* Creates a Texture and puts it onto the atlas
* @param bmp a Bitmap object to build the texture from
* @return NLUL if failed
*/
public static Texture createTextureFromBitmap(Bitmap bmp) {
Texture texture = new Texture(bmp);
if(bmp.getWidth() > _greatestWidth)
_greatestWidth = bmp.getWidth();
_texture.put(_textureCount, texture);
_textureCount++;
return texture;
}
/**
* Adds a Texture to the atlas, note: this is done automatically if createTextureXXX functions are used
* @param texture
*/
public static void addTexture(Texture texture) {
_texture.put(_textureCount, texture);
_textureCount++;
}
/**
* Calculates a TextureAtlas from all the loaded Texture's
*/
public static void compute() {
compute(1024);
}
/**
* Calculates a TextureAtlas from all the loaded Texture's
* The Texture's are sorted into largest-first order, and a bin packing algorithm is used to squeeze
* into the atlas. There is a maximum total atlas size of 1024x1024 pixels, imposed by OpenGL.
* If your Texture's and Font's do not fit into this space, an exception will be raised.
*
* An improvement - to allow more atlases simulatenously, is being worked on.
* @param initwidth the minimum width of the atlas
*/
@SuppressWarnings("unchecked")
public static void compute(int initwidth) {
boolean isNew;
//Debug.print("# COMPUTING TEXTURES IDSTR=" + idString);
- if(getLastIdString().equals(idString) && !Rokon.getRokon().isForceTextureRefresh()) {
+ if(getLastIdString() == idString && !Rokon.getRokon().isForceTextureRefresh()) {
//Debug.print("## MATCHES LAST ID STRING");
isNew = false;
} else {
//Debug.print("## NEW ID STRING");
saveLastIdString();
isNew = true;
}
if(isNew) {
_textureSets.put(_textureSetCount, (HashMap<Integer, Texture>)_texture.clone());
_height[0] = 0;
int i = 0;
int curK = 0;
_width = initwidth;
if(_width == 0)
while(_width < _greatestWidth)
_width = (int)Math.pow(2, i++);
for(i = 0; i < _textureSetCount; i++)
for(int h = 0; h < _textureSets.size(); h++)
_textureSets.get(h).get(i).inserted = false;
for(curK = 0; curK <= _textureSetCount; curK++) {
for(i = 0; i < _textureSets.get(curK).size(); i++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
int greatestArea = 0;
int greatestIndex = -1;
for(int j = 0; j < _textureSets.get(curK).size(); j++) {
if(!textureSet.get(j).inserted && textureSet.get(j).getWidth() * textureSet.get(j).getHeight() > greatestArea) {
greatestIndex = j;
greatestArea = textureSet.get(j).getWidth() * textureSet.get(j).getHeight();
}
}
if(greatestIndex != -1) {
Texture texture = textureSet.get(greatestIndex);
int x = 0;
int y = 0;
boolean found = false;
while(!found) {
if(y + texture.getHeight() > 1024) {
Debug.print("Current atlas is full, moving on... x=" + x + " y=" + y + " w=" + texture.getWidth() + " h=" + texture.getHeight());
saveBitmap(_width);
x = 0;
y = 0;
currentAtlas++;
_height[currentAtlas] = 0;
}
int resX = isAnyoneWithinX(x, y, x + texture.getWidth(), y + texture.getHeight());
int resY = isAnyoneWithinY(x, y, x + texture.getWidth(), y + texture.getHeight());
if(resX == -1) {
texture.atlasX = x;
texture.atlasY = y;
texture.atlasIndex = currentAtlas;
texture.inserted = true;
found = true;
if(texture.atlasY + texture.getHeight() > _height[currentAtlas])
_height[currentAtlas] = texture.atlasY + texture.getHeight();
} else {
x = resX;
if(x + texture.getWidth() >= _width) {
x = 0;
y = resY;
}
}
}
} else
break;
}
saveBitmap(_width);
currentAtlas++;
_height[currentAtlas] = 0;
Debug.print("reached split");
}
saveNewSettings();
} else {
//Debug.print("## LOADING OLD TEXTURES");
_textureSets.put(_textureSetCount, (HashMap<Integer, Texture>)_texture.clone());
loadOldSettings();
_height[0] = 0;
int i = 0;
int curK = 0;
_width = initwidth;
if(_width == 0)
while(_width < _greatestWidth)
_width = (int)Math.pow(2, i++);
for(i = 0; i < _textureSetCount; i++)
for(int h = 0; h < _textureSets.size(); h++)
_textureSets.get(h).get(i).inserted = false;
for(curK = 0; curK <= _textureSetCount; curK++) {
for(i = 0; i < _textureSets.get(curK).size(); i++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
Texture texture = textureSet.get(i);
texture.atlasX = texture.suggestX;
texture.atlasY = texture.suggestY;
texture.atlasIndex = texture.suggestAtlas;
texture.inserted = true;
if(texture.atlasY + texture.getHeight() > _height[currentAtlas])
_height[currentAtlas] = texture.atlasY + texture.getHeight();
}
saveBitmap(_width);
currentAtlas++;
_height[currentAtlas] = 0;
//Debug.print("reached split");
}
}
System.gc();
}
public static void saveBitmap(int _width) {
int theight = _height[currentAtlas];
_height[currentAtlas] = 0;
int i = 0;
while(_height[currentAtlas] < theight)
_height[currentAtlas] = (int)Math.pow(2, i++);
_bmp[currentAtlas] = Bitmap.createBitmap(_width, _height[currentAtlas], Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(_bmp[currentAtlas]);
for(int f = 0; f < _textureSets.size(); f++)
for(int h = 0; h < _textureSets.get(f).size(); h++) {
Texture texture = _textureSets.get(f).get(h);
if(texture.atlasIndex == currentAtlas) {
Bitmap bmp = null;
if(texture.isAsset) {
try {
bmp = BitmapFactory.decodeStream(Rokon.getRokon().getActivity().getAssets().open(texture.assetPath));
}
catch (Exception e) {
Debug.print("CANNOT FIND saveBitmap");
System.exit(0);
}
} else {
bmp = texture.getBitmap();
}
canvas.drawBitmap(bmp, texture.atlasX, texture.atlasY, new Paint());
texture.cleanBitmap();
bmp.recycle();
Runtime.getRuntime().gc();
}
}
readyToLoad = true;
}
public static Bitmap getBitmap(int index) {
return _bmp[index];
}
private static int isAnyoneWithinX(int x, int y, int x2, int y2) {
for(int i = 0; i < _textureSets.size(); i++)
for(int h = 0; h < _textureSets.get(i).size(); h++) {
Texture texture = _textureSets.get(i).get(h);
if(texture.inserted && texture.atlasIndex == currentAtlas) {
boolean maybe = false;
if(texture.atlasX >= x && texture.atlasX <= x2)
maybe = true;
if(texture.atlasX <= x && texture.atlasX + texture.getWidth() > x)
maybe = true;
if(maybe) {
if(texture.atlasY >= y && texture.atlasY <= y2)
return texture.atlasX + texture.getWidth();
if(texture.atlasY <= y && texture.atlasY + texture.getHeight() > y)
return texture.atlasX + texture.getWidth();
}
}
}
return -1;
}
private static int isAnyoneWithinY(int x, int y, int x2, int y2) {
for(int i = 0; i < _textureSets.size(); i++)
for(int h = 0; h < _textureSets.get(i).size(); h++) {
Texture texture = _textureSets.get(i).get(h);
if(texture.inserted && texture.atlasIndex == currentAtlas) {
boolean maybe = false;
if(texture.atlasX >= x && texture.atlasX <= x2)
maybe = true;
if(texture.atlasX <= x && texture.atlasX + texture.getWidth() > x)
maybe = true;
if(maybe) {
if(texture.atlasY >= y && texture.atlasY <= y2)
return texture.atlasY + texture.getHeight();
if(texture.atlasY <= y && texture.atlasY + texture.getHeight() > y)
return texture.atlasY + texture.getHeight();
}
}
}
return -1;
}
@SuppressWarnings("unchecked")
public static void textureSplit() {
_textureSets.put(_textureSetCount, (HashMap<Integer, Texture>)_texture.clone());
_textureSetCount++;
_textureCount = 0;
_texture.clear();
}
public static void clearAll() {
//Debug.print("Clearing bitmaps");
for(HashMap<Integer, Texture> h : _textureSets.values()) {
for(Texture t : h.values()) {
try {
t.cleanBitmap();
} catch (Exception e) { }
}
}
for(int i = 0; i < _bmp.length; i++) {
try {
_bmp[i].recycle();
} catch (Exception e) { }
}
}
private static String getLastIdString() {
try {
FileInputStream input = Rokon.getRokon().getActivity().openFileInput("textures");
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
return new String(buffer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void saveLastIdString() {
try {
FileOutputStream output = Rokon.getRokon().getActivity().openFileOutput("textures", 0);
output.write(idString.getBytes());
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void loadOldSettings() {
try {
FileInputStream input = Rokon.getRokon().getActivity().openFileInput("textures_info");
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
parseOldSettings(new String(buffer));
return;
} catch (Exception e) {
e.printStackTrace();
}
}
private static void parseOldSettings(String string) {
String line[] = string.split("\n");
for(int i = 0; i < line.length; i++) {
String info[] = line[i].split(",");
for(int curK = 0; curK <= _textureSetCount; curK++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
for(int j = 0; j < _textureSets.get(curK).size(); j++) {
Texture texture = textureSet.get(j);
if(texture.assetPath.equals(info[0])) {
texture.suggestX = Integer.parseInt(info[1]);
texture.suggestY = Integer.parseInt(info[2]);
texture.suggestAtlas = Integer.parseInt(info[3]);
break;
}
}
}
}
}
private static void saveNewSettings() {
String settings = "";
for(int curK = 0; curK <= _textureSetCount; curK++) {
for(int i = 0; i < _textureSets.get(curK).size(); i++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
Texture texture = textureSet.get(i);
settings += texture.assetPath + "," + texture.atlasX + "," + texture.atlasY + "," + texture.atlasIndex + "\n";
}
}
try {
FileOutputStream output = Rokon.getRokon().getActivity().openFileOutput("textures_info", 0);
output.write(settings.getBytes());
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void reloadTexture(int index, Bitmap bitmap) {
reloadTextures = true;
if(!reloadTextureIndices.contains(index))
reloadTextureIndices.add(index);
_bmp[index] = bitmap;
}
}
| true | true | public static void compute(int initwidth) {
boolean isNew;
//Debug.print("# COMPUTING TEXTURES IDSTR=" + idString);
if(getLastIdString().equals(idString) && !Rokon.getRokon().isForceTextureRefresh()) {
//Debug.print("## MATCHES LAST ID STRING");
isNew = false;
} else {
//Debug.print("## NEW ID STRING");
saveLastIdString();
isNew = true;
}
if(isNew) {
_textureSets.put(_textureSetCount, (HashMap<Integer, Texture>)_texture.clone());
_height[0] = 0;
int i = 0;
int curK = 0;
_width = initwidth;
if(_width == 0)
while(_width < _greatestWidth)
_width = (int)Math.pow(2, i++);
for(i = 0; i < _textureSetCount; i++)
for(int h = 0; h < _textureSets.size(); h++)
_textureSets.get(h).get(i).inserted = false;
for(curK = 0; curK <= _textureSetCount; curK++) {
for(i = 0; i < _textureSets.get(curK).size(); i++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
int greatestArea = 0;
int greatestIndex = -1;
for(int j = 0; j < _textureSets.get(curK).size(); j++) {
if(!textureSet.get(j).inserted && textureSet.get(j).getWidth() * textureSet.get(j).getHeight() > greatestArea) {
greatestIndex = j;
greatestArea = textureSet.get(j).getWidth() * textureSet.get(j).getHeight();
}
}
if(greatestIndex != -1) {
Texture texture = textureSet.get(greatestIndex);
int x = 0;
int y = 0;
boolean found = false;
while(!found) {
if(y + texture.getHeight() > 1024) {
Debug.print("Current atlas is full, moving on... x=" + x + " y=" + y + " w=" + texture.getWidth() + " h=" + texture.getHeight());
saveBitmap(_width);
x = 0;
y = 0;
currentAtlas++;
_height[currentAtlas] = 0;
}
int resX = isAnyoneWithinX(x, y, x + texture.getWidth(), y + texture.getHeight());
int resY = isAnyoneWithinY(x, y, x + texture.getWidth(), y + texture.getHeight());
if(resX == -1) {
texture.atlasX = x;
texture.atlasY = y;
texture.atlasIndex = currentAtlas;
texture.inserted = true;
found = true;
if(texture.atlasY + texture.getHeight() > _height[currentAtlas])
_height[currentAtlas] = texture.atlasY + texture.getHeight();
} else {
x = resX;
if(x + texture.getWidth() >= _width) {
x = 0;
y = resY;
}
}
}
} else
break;
}
saveBitmap(_width);
currentAtlas++;
_height[currentAtlas] = 0;
Debug.print("reached split");
}
saveNewSettings();
} else {
//Debug.print("## LOADING OLD TEXTURES");
_textureSets.put(_textureSetCount, (HashMap<Integer, Texture>)_texture.clone());
loadOldSettings();
_height[0] = 0;
int i = 0;
int curK = 0;
_width = initwidth;
if(_width == 0)
while(_width < _greatestWidth)
_width = (int)Math.pow(2, i++);
for(i = 0; i < _textureSetCount; i++)
for(int h = 0; h < _textureSets.size(); h++)
_textureSets.get(h).get(i).inserted = false;
for(curK = 0; curK <= _textureSetCount; curK++) {
for(i = 0; i < _textureSets.get(curK).size(); i++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
Texture texture = textureSet.get(i);
texture.atlasX = texture.suggestX;
texture.atlasY = texture.suggestY;
texture.atlasIndex = texture.suggestAtlas;
texture.inserted = true;
if(texture.atlasY + texture.getHeight() > _height[currentAtlas])
_height[currentAtlas] = texture.atlasY + texture.getHeight();
}
saveBitmap(_width);
currentAtlas++;
_height[currentAtlas] = 0;
//Debug.print("reached split");
}
}
System.gc();
}
| public static void compute(int initwidth) {
boolean isNew;
//Debug.print("# COMPUTING TEXTURES IDSTR=" + idString);
if(getLastIdString() == idString && !Rokon.getRokon().isForceTextureRefresh()) {
//Debug.print("## MATCHES LAST ID STRING");
isNew = false;
} else {
//Debug.print("## NEW ID STRING");
saveLastIdString();
isNew = true;
}
if(isNew) {
_textureSets.put(_textureSetCount, (HashMap<Integer, Texture>)_texture.clone());
_height[0] = 0;
int i = 0;
int curK = 0;
_width = initwidth;
if(_width == 0)
while(_width < _greatestWidth)
_width = (int)Math.pow(2, i++);
for(i = 0; i < _textureSetCount; i++)
for(int h = 0; h < _textureSets.size(); h++)
_textureSets.get(h).get(i).inserted = false;
for(curK = 0; curK <= _textureSetCount; curK++) {
for(i = 0; i < _textureSets.get(curK).size(); i++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
int greatestArea = 0;
int greatestIndex = -1;
for(int j = 0; j < _textureSets.get(curK).size(); j++) {
if(!textureSet.get(j).inserted && textureSet.get(j).getWidth() * textureSet.get(j).getHeight() > greatestArea) {
greatestIndex = j;
greatestArea = textureSet.get(j).getWidth() * textureSet.get(j).getHeight();
}
}
if(greatestIndex != -1) {
Texture texture = textureSet.get(greatestIndex);
int x = 0;
int y = 0;
boolean found = false;
while(!found) {
if(y + texture.getHeight() > 1024) {
Debug.print("Current atlas is full, moving on... x=" + x + " y=" + y + " w=" + texture.getWidth() + " h=" + texture.getHeight());
saveBitmap(_width);
x = 0;
y = 0;
currentAtlas++;
_height[currentAtlas] = 0;
}
int resX = isAnyoneWithinX(x, y, x + texture.getWidth(), y + texture.getHeight());
int resY = isAnyoneWithinY(x, y, x + texture.getWidth(), y + texture.getHeight());
if(resX == -1) {
texture.atlasX = x;
texture.atlasY = y;
texture.atlasIndex = currentAtlas;
texture.inserted = true;
found = true;
if(texture.atlasY + texture.getHeight() > _height[currentAtlas])
_height[currentAtlas] = texture.atlasY + texture.getHeight();
} else {
x = resX;
if(x + texture.getWidth() >= _width) {
x = 0;
y = resY;
}
}
}
} else
break;
}
saveBitmap(_width);
currentAtlas++;
_height[currentAtlas] = 0;
Debug.print("reached split");
}
saveNewSettings();
} else {
//Debug.print("## LOADING OLD TEXTURES");
_textureSets.put(_textureSetCount, (HashMap<Integer, Texture>)_texture.clone());
loadOldSettings();
_height[0] = 0;
int i = 0;
int curK = 0;
_width = initwidth;
if(_width == 0)
while(_width < _greatestWidth)
_width = (int)Math.pow(2, i++);
for(i = 0; i < _textureSetCount; i++)
for(int h = 0; h < _textureSets.size(); h++)
_textureSets.get(h).get(i).inserted = false;
for(curK = 0; curK <= _textureSetCount; curK++) {
for(i = 0; i < _textureSets.get(curK).size(); i++) {
HashMap<Integer, Texture> textureSet = _textureSets.get(curK);
Texture texture = textureSet.get(i);
texture.atlasX = texture.suggestX;
texture.atlasY = texture.suggestY;
texture.atlasIndex = texture.suggestAtlas;
texture.inserted = true;
if(texture.atlasY + texture.getHeight() > _height[currentAtlas])
_height[currentAtlas] = texture.atlasY + texture.getHeight();
}
saveBitmap(_width);
currentAtlas++;
_height[currentAtlas] = 0;
//Debug.print("reached split");
}
}
System.gc();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.